babylon.2.1-alpha.debug.js 1.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489
  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.GetClipFactor = function (vector0, vector1, axis, size) {
  589. var d0 = Vector3.Dot(vector0, axis) - size;
  590. var d1 = Vector3.Dot(vector1, axis) - size;
  591. var s = d0 / (d0 - d1);
  592. return s;
  593. };
  594. Vector3.FromArray = function (array, offset) {
  595. if (!offset) {
  596. offset = 0;
  597. }
  598. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  599. };
  600. Vector3.FromArrayToRef = function (array, offset, result) {
  601. result.x = array[offset];
  602. result.y = array[offset + 1];
  603. result.z = array[offset + 2];
  604. };
  605. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  606. result.x = array[offset];
  607. result.y = array[offset + 1];
  608. result.z = array[offset + 2];
  609. };
  610. Vector3.FromFloatsToRef = function (x, y, z, result) {
  611. result.x = x;
  612. result.y = y;
  613. result.z = z;
  614. };
  615. Vector3.Zero = function () {
  616. return new Vector3(0, 0, 0);
  617. };
  618. Vector3.Up = function () {
  619. return new Vector3(0, 1.0, 0);
  620. };
  621. Vector3.TransformCoordinates = function (vector, transformation) {
  622. var result = Vector3.Zero();
  623. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  624. return result;
  625. };
  626. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  627. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  628. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  629. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  630. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  631. result.x = x / w;
  632. result.y = y / w;
  633. result.z = z / w;
  634. };
  635. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  636. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  637. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  638. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  639. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  640. result.x = rx / rw;
  641. result.y = ry / rw;
  642. result.z = rz / rw;
  643. };
  644. Vector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  645. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  646. var m0 = SIMD.float32x4.load(transformation.m, 0);
  647. var m1 = SIMD.float32x4.load(transformation.m, 4);
  648. var m2 = SIMD.float32x4.load(transformation.m, 8);
  649. var m3 = SIMD.float32x4.load(transformation.m, 12);
  650. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
  651. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  652. SIMD.float32x4.storeXYZ(result._data, 0, r);
  653. };
  654. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  655. var v0 = SIMD.float32x4.splat(x);
  656. var v1 = SIMD.float32x4.splat(y);
  657. var v2 = SIMD.float32x4.splat(z);
  658. var m0 = SIMD.float32x4.load(transformation.m, 0);
  659. var m1 = SIMD.float32x4.load(transformation.m, 4);
  660. var m2 = SIMD.float32x4.load(transformation.m, 8);
  661. var m3 = SIMD.float32x4.load(transformation.m, 12);
  662. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
  663. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  664. SIMD.float32x4.storeXYZ(result._data, 0, r);
  665. };
  666. Vector3.TransformNormal = function (vector, transformation) {
  667. var result = Vector3.Zero();
  668. Vector3.TransformNormalToRef(vector, transformation, result);
  669. return result;
  670. };
  671. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  672. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  673. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  674. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  675. };
  676. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  677. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  678. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  679. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  680. };
  681. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  682. var squared = amount * amount;
  683. var cubed = amount * squared;
  684. 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));
  685. 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));
  686. 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));
  687. return new Vector3(x, y, z);
  688. };
  689. Vector3.Clamp = function (value, min, max) {
  690. var x = value.x;
  691. x = (x > max.x) ? max.x : x;
  692. x = (x < min.x) ? min.x : x;
  693. var y = value.y;
  694. y = (y > max.y) ? max.y : y;
  695. y = (y < min.y) ? min.y : y;
  696. var z = value.z;
  697. z = (z > max.z) ? max.z : z;
  698. z = (z < min.z) ? min.z : z;
  699. return new Vector3(x, y, z);
  700. };
  701. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  702. var squared = amount * amount;
  703. var cubed = amount * squared;
  704. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  705. var part2 = (-2.0 * cubed) + (3.0 * squared);
  706. var part3 = (cubed - (2.0 * squared)) + amount;
  707. var part4 = cubed - squared;
  708. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  709. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  710. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  711. return new Vector3(x, y, z);
  712. };
  713. Vector3.Lerp = function (start, end, amount) {
  714. var x = start.x + ((end.x - start.x) * amount);
  715. var y = start.y + ((end.y - start.y) * amount);
  716. var z = start.z + ((end.z - start.z) * amount);
  717. return new Vector3(x, y, z);
  718. };
  719. Vector3.Dot = function (left, right) {
  720. return (left.x * right.x + left.y * right.y + left.z * right.z);
  721. };
  722. Vector3.Cross = function (left, right) {
  723. var result = Vector3.Zero();
  724. Vector3.CrossToRef(left, right, result);
  725. return result;
  726. };
  727. Vector3.CrossToRef = function (left, right, result) {
  728. result.x = left.y * right.z - left.z * right.y;
  729. result.y = left.z * right.x - left.x * right.z;
  730. result.z = left.x * right.y - left.y * right.x;
  731. };
  732. Vector3.Normalize = function (vector) {
  733. var result = Vector3.Zero();
  734. Vector3.NormalizeToRef(vector, result);
  735. return result;
  736. };
  737. Vector3.NormalizeToRef = function (vector, result) {
  738. result.copyFrom(vector);
  739. result.normalize();
  740. };
  741. Vector3.Project = function (vector, world, transform, viewport) {
  742. var cw = viewport.width;
  743. var ch = viewport.height;
  744. var cx = viewport.x;
  745. var cy = viewport.y;
  746. 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);
  747. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  748. return Vector3.TransformCoordinates(vector, finalMatrix);
  749. };
  750. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  751. var matrix = world.multiply(transform);
  752. matrix.invert();
  753. source.x = source.x / viewportWidth * 2 - 1;
  754. source.y = -(source.y / viewportHeight * 2 - 1);
  755. var vector = Vector3.TransformCoordinates(source, matrix);
  756. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  757. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  758. vector = vector.scale(1.0 / num);
  759. }
  760. return vector;
  761. };
  762. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  763. var matrix = world.multiply(view).multiply(projection);
  764. matrix.invert();
  765. source.x = source.x / viewportWidth * 2 - 1;
  766. source.y = -(source.y / viewportHeight * 2 - 1);
  767. var vector = Vector3.TransformCoordinates(source, matrix);
  768. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  769. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  770. vector = vector.scale(1.0 / num);
  771. }
  772. return vector;
  773. };
  774. Vector3.Minimize = function (left, right) {
  775. var min = left.clone();
  776. min.MinimizeInPlace(right);
  777. return min;
  778. };
  779. Vector3.Maximize = function (left, right) {
  780. var max = left.clone();
  781. max.MaximizeInPlace(right);
  782. return max;
  783. };
  784. Vector3.Distance = function (value1, value2) {
  785. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  786. };
  787. Vector3.DistanceSquared = function (value1, value2) {
  788. var x = value1.x - value2.x;
  789. var y = value1.y - value2.y;
  790. var z = value1.z - value2.z;
  791. return (x * x) + (y * y) + (z * z);
  792. };
  793. Vector3.Center = function (value1, value2) {
  794. var center = value1.add(value2);
  795. center.scaleInPlace(0.5);
  796. return center;
  797. };
  798. return Vector3;
  799. })();
  800. BABYLON.Vector3 = Vector3;
  801. //Vector4 class created for EulerAngle class conversion to Quaternion
  802. var Vector4 = (function () {
  803. function Vector4(x, y, z, w) {
  804. this.x = x;
  805. this.y = y;
  806. this.z = z;
  807. this.w = w;
  808. }
  809. Vector4.prototype.toString = function () {
  810. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  811. };
  812. // Operators
  813. Vector4.prototype.asArray = function () {
  814. var result = [];
  815. this.toArray(result, 0);
  816. return result;
  817. };
  818. Vector4.prototype.toArray = function (array, index) {
  819. if (index === undefined) {
  820. index = 0;
  821. }
  822. array[index] = this.x;
  823. array[index + 1] = this.y;
  824. array[index + 2] = this.z;
  825. array[index + 3] = this.w;
  826. return this;
  827. };
  828. Vector4.prototype.addInPlace = function (otherVector) {
  829. this.x += otherVector.x;
  830. this.y += otherVector.y;
  831. this.z += otherVector.z;
  832. this.w += otherVector.w;
  833. return this;
  834. };
  835. Vector4.prototype.add = function (otherVector) {
  836. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  837. };
  838. Vector4.prototype.addToRef = function (otherVector, result) {
  839. result.x = this.x + otherVector.x;
  840. result.y = this.y + otherVector.y;
  841. result.z = this.z + otherVector.z;
  842. result.w = this.w + otherVector.w;
  843. return this;
  844. };
  845. Vector4.prototype.subtractInPlace = function (otherVector) {
  846. this.x -= otherVector.x;
  847. this.y -= otherVector.y;
  848. this.z -= otherVector.z;
  849. this.w -= otherVector.w;
  850. return this;
  851. };
  852. Vector4.prototype.subtract = function (otherVector) {
  853. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  854. };
  855. Vector4.prototype.subtractToRef = function (otherVector, result) {
  856. result.x = this.x - otherVector.x;
  857. result.y = this.y - otherVector.y;
  858. result.z = this.z - otherVector.z;
  859. result.w = this.w - otherVector.w;
  860. return this;
  861. };
  862. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  863. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  864. };
  865. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  866. result.x = this.x - x;
  867. result.y = this.y - y;
  868. result.z = this.z - z;
  869. result.w = this.w - w;
  870. return this;
  871. };
  872. Vector4.prototype.negate = function () {
  873. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  874. };
  875. Vector4.prototype.scaleInPlace = function (scale) {
  876. this.x *= scale;
  877. this.y *= scale;
  878. this.z *= scale;
  879. this.w *= scale;
  880. return this;
  881. };
  882. Vector4.prototype.scale = function (scale) {
  883. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  884. };
  885. Vector4.prototype.scaleToRef = function (scale, result) {
  886. result.x = this.x * scale;
  887. result.y = this.y * scale;
  888. result.z = this.z * scale;
  889. result.w = this.w * scale;
  890. };
  891. Vector4.prototype.equals = function (otherVector) {
  892. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  893. };
  894. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  895. 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;
  896. };
  897. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  898. return this.x === x && this.y === y && this.z === z && this.w === w;
  899. };
  900. Vector4.prototype.multiplyInPlace = function (otherVector) {
  901. this.x *= otherVector.x;
  902. this.y *= otherVector.y;
  903. this.z *= otherVector.z;
  904. this.w *= otherVector.w;
  905. return this;
  906. };
  907. Vector4.prototype.multiply = function (otherVector) {
  908. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  909. };
  910. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  911. result.x = this.x * otherVector.x;
  912. result.y = this.y * otherVector.y;
  913. result.z = this.z * otherVector.z;
  914. result.w = this.w * otherVector.w;
  915. return this;
  916. };
  917. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  918. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  919. };
  920. Vector4.prototype.divide = function (otherVector) {
  921. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  922. };
  923. Vector4.prototype.divideToRef = function (otherVector, result) {
  924. result.x = this.x / otherVector.x;
  925. result.y = this.y / otherVector.y;
  926. result.z = this.z / otherVector.z;
  927. result.w = this.w / otherVector.w;
  928. return this;
  929. };
  930. Vector4.prototype.MinimizeInPlace = function (other) {
  931. if (other.x < this.x)
  932. this.x = other.x;
  933. if (other.y < this.y)
  934. this.y = other.y;
  935. if (other.z < this.z)
  936. this.z = other.z;
  937. if (other.w < this.w)
  938. this.w = other.w;
  939. return this;
  940. };
  941. Vector4.prototype.MaximizeInPlace = function (other) {
  942. if (other.x > this.x)
  943. this.x = other.x;
  944. if (other.y > this.y)
  945. this.y = other.y;
  946. if (other.z > this.z)
  947. this.z = other.z;
  948. if (other.w > this.w)
  949. this.w = other.w;
  950. return this;
  951. };
  952. // Properties
  953. Vector4.prototype.length = function () {
  954. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  955. };
  956. Vector4.prototype.lengthSquared = function () {
  957. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  958. };
  959. // Methods
  960. Vector4.prototype.normalize = function () {
  961. var len = this.length();
  962. if (len === 0)
  963. return this;
  964. var num = 1.0 / len;
  965. this.x *= num;
  966. this.y *= num;
  967. this.z *= num;
  968. this.w *= num;
  969. return this;
  970. };
  971. Vector4.prototype.clone = function () {
  972. return new Vector4(this.x, this.y, this.z, this.w);
  973. };
  974. Vector4.prototype.copyFrom = function (source) {
  975. this.x = source.x;
  976. this.y = source.y;
  977. this.z = source.z;
  978. this.w = source.w;
  979. return this;
  980. };
  981. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  982. this.x = x;
  983. this.y = y;
  984. this.z = z;
  985. this.w = w;
  986. return this;
  987. };
  988. // Statics
  989. Vector4.FromArray = function (array, offset) {
  990. if (!offset) {
  991. offset = 0;
  992. }
  993. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  994. };
  995. Vector4.FromArrayToRef = function (array, offset, result) {
  996. result.x = array[offset];
  997. result.y = array[offset + 1];
  998. result.z = array[offset + 2];
  999. result.w = array[offset + 3];
  1000. };
  1001. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1002. result.x = array[offset];
  1003. result.y = array[offset + 1];
  1004. result.z = array[offset + 2];
  1005. result.w = array[offset + 3];
  1006. };
  1007. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1008. result.x = x;
  1009. result.y = y;
  1010. result.z = z;
  1011. result.w = w;
  1012. };
  1013. Vector4.Zero = function () {
  1014. return new Vector4(0, 0, 0, 0);
  1015. };
  1016. Vector4.Normalize = function (vector) {
  1017. var result = Vector4.Zero();
  1018. Vector4.NormalizeToRef(vector, result);
  1019. return result;
  1020. };
  1021. Vector4.NormalizeToRef = function (vector, result) {
  1022. result.copyFrom(vector);
  1023. result.normalize();
  1024. };
  1025. Vector4.Minimize = function (left, right) {
  1026. var min = left.clone();
  1027. min.MinimizeInPlace(right);
  1028. return min;
  1029. };
  1030. Vector4.Maximize = function (left, right) {
  1031. var max = left.clone();
  1032. max.MaximizeInPlace(right);
  1033. return max;
  1034. };
  1035. Vector4.Distance = function (value1, value2) {
  1036. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1037. };
  1038. Vector4.DistanceSquared = function (value1, value2) {
  1039. var x = value1.x - value2.x;
  1040. var y = value1.y - value2.y;
  1041. var z = value1.z - value2.z;
  1042. var w = value1.w - value2.w;
  1043. return (x * x) + (y * y) + (z * z) + (w * w);
  1044. };
  1045. Vector4.Center = function (value1, value2) {
  1046. var center = value1.add(value2);
  1047. center.scaleInPlace(0.5);
  1048. return center;
  1049. };
  1050. return Vector4;
  1051. })();
  1052. BABYLON.Vector4 = Vector4;
  1053. var Quaternion = (function () {
  1054. function Quaternion(x, y, z, w) {
  1055. if (x === void 0) { x = 0; }
  1056. if (y === void 0) { y = 0; }
  1057. if (z === void 0) { z = 0; }
  1058. if (w === void 0) { w = 1; }
  1059. this.x = x;
  1060. this.y = y;
  1061. this.z = z;
  1062. this.w = w;
  1063. }
  1064. Quaternion.prototype.toString = function () {
  1065. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1066. };
  1067. Quaternion.prototype.asArray = function () {
  1068. return [this.x, this.y, this.z, this.w];
  1069. };
  1070. Quaternion.prototype.equals = function (otherQuaternion) {
  1071. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1072. };
  1073. Quaternion.prototype.clone = function () {
  1074. return new Quaternion(this.x, this.y, this.z, this.w);
  1075. };
  1076. Quaternion.prototype.copyFrom = function (other) {
  1077. this.x = other.x;
  1078. this.y = other.y;
  1079. this.z = other.z;
  1080. this.w = other.w;
  1081. return this;
  1082. };
  1083. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1084. this.x = x;
  1085. this.y = y;
  1086. this.z = z;
  1087. this.w = w;
  1088. return this;
  1089. };
  1090. Quaternion.prototype.add = function (other) {
  1091. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1092. };
  1093. Quaternion.prototype.subtract = function (other) {
  1094. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1095. };
  1096. Quaternion.prototype.scale = function (value) {
  1097. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1098. };
  1099. Quaternion.prototype.multiply = function (q1) {
  1100. var result = new Quaternion(0, 0, 0, 1.0);
  1101. this.multiplyToRef(q1, result);
  1102. return result;
  1103. };
  1104. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1105. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1106. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1107. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1108. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1109. return this;
  1110. };
  1111. Quaternion.prototype.length = function () {
  1112. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1113. };
  1114. Quaternion.prototype.normalize = function () {
  1115. var length = 1.0 / this.length();
  1116. this.x *= length;
  1117. this.y *= length;
  1118. this.z *= length;
  1119. this.w *= length;
  1120. return this;
  1121. };
  1122. Quaternion.prototype.toEulerAngles = function () {
  1123. var result = Vector3.Zero();
  1124. this.toEulerAnglesToRef(result);
  1125. return result;
  1126. };
  1127. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1128. //result is an EulerAngles in the in the z-x-z convention
  1129. var qx = this.x;
  1130. var qy = this.y;
  1131. var qz = this.z;
  1132. var qw = this.w;
  1133. var qxy = qx * qy;
  1134. var qxz = qx * qz;
  1135. var qwy = qw * qy;
  1136. var qwz = qw * qz;
  1137. var qwx = qw * qx;
  1138. var qyz = qy * qz;
  1139. var sqx = qx * qx;
  1140. var sqy = qy * qy;
  1141. var determinant = sqx + sqy;
  1142. if (determinant !== 0.000 && determinant !== 1.000) {
  1143. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1144. result.y = Math.acos(1 - 2 * determinant);
  1145. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1146. }
  1147. else {
  1148. if (determinant === 0.0) {
  1149. result.x = 0.0;
  1150. result.y = 0.0;
  1151. 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)
  1152. }
  1153. else {
  1154. 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)
  1155. result.y = Math.PI;
  1156. result.z = 0.0;
  1157. }
  1158. }
  1159. return this;
  1160. };
  1161. Quaternion.prototype.toRotationMatrix = function (result) {
  1162. var xx = this.x * this.x;
  1163. var yy = this.y * this.y;
  1164. var zz = this.z * this.z;
  1165. var xy = this.x * this.y;
  1166. var zw = this.z * this.w;
  1167. var zx = this.z * this.x;
  1168. var yw = this.y * this.w;
  1169. var yz = this.y * this.z;
  1170. var xw = this.x * this.w;
  1171. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1172. result.m[1] = 2.0 * (xy + zw);
  1173. result.m[2] = 2.0 * (zx - yw);
  1174. result.m[3] = 0;
  1175. result.m[4] = 2.0 * (xy - zw);
  1176. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1177. result.m[6] = 2.0 * (yz + xw);
  1178. result.m[7] = 0;
  1179. result.m[8] = 2.0 * (zx + yw);
  1180. result.m[9] = 2.0 * (yz - xw);
  1181. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1182. result.m[11] = 0;
  1183. result.m[12] = 0;
  1184. result.m[13] = 0;
  1185. result.m[14] = 0;
  1186. result.m[15] = 1.0;
  1187. return this;
  1188. };
  1189. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1190. Quaternion.FromRotationMatrixToRef(matrix, this);
  1191. return this;
  1192. };
  1193. // Statics
  1194. Quaternion.FromRotationMatrix = function (matrix) {
  1195. var result = new Quaternion();
  1196. Quaternion.FromRotationMatrixToRef(matrix, result);
  1197. return result;
  1198. };
  1199. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1200. var data = matrix.m;
  1201. var m11 = data[0], m12 = data[4], m13 = data[8];
  1202. var m21 = data[1], m22 = data[5], m23 = data[9];
  1203. var m31 = data[2], m32 = data[6], m33 = data[10];
  1204. var trace = m11 + m22 + m33;
  1205. var s;
  1206. if (trace > 0) {
  1207. s = 0.5 / Math.sqrt(trace + 1.0);
  1208. result.w = 0.25 / s;
  1209. result.x = (m32 - m23) * s;
  1210. result.y = (m13 - m31) * s;
  1211. result.z = (m21 - m12) * s;
  1212. }
  1213. else if (m11 > m22 && m11 > m33) {
  1214. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1215. result.w = (m32 - m23) / s;
  1216. result.x = 0.25 * s;
  1217. result.y = (m12 + m21) / s;
  1218. result.z = (m13 + m31) / s;
  1219. }
  1220. else if (m22 > m33) {
  1221. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1222. result.w = (m13 - m31) / s;
  1223. result.x = (m12 + m21) / s;
  1224. result.y = 0.25 * s;
  1225. result.z = (m23 + m32) / s;
  1226. }
  1227. else {
  1228. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1229. result.w = (m21 - m12) / s;
  1230. result.x = (m13 + m31) / s;
  1231. result.y = (m23 + m32) / s;
  1232. result.z = 0.25 * s;
  1233. }
  1234. };
  1235. Quaternion.Inverse = function (q) {
  1236. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1237. };
  1238. Quaternion.Identity = function () {
  1239. return new Quaternion(0, 0, 0, 1);
  1240. };
  1241. Quaternion.RotationAxis = function (axis, angle) {
  1242. var result = new Quaternion();
  1243. var sin = Math.sin(angle / 2);
  1244. result.w = Math.cos(angle / 2);
  1245. result.x = axis.x * sin;
  1246. result.y = axis.y * sin;
  1247. result.z = axis.z * sin;
  1248. return result;
  1249. };
  1250. Quaternion.FromArray = function (array, offset) {
  1251. if (!offset) {
  1252. offset = 0;
  1253. }
  1254. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1255. };
  1256. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1257. var result = new Quaternion();
  1258. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1259. return result;
  1260. };
  1261. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1262. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1263. var halfRoll = roll * 0.5;
  1264. var halfPitch = pitch * 0.5;
  1265. var halfYaw = yaw * 0.5;
  1266. var sinRoll = Math.sin(halfRoll);
  1267. var cosRoll = Math.cos(halfRoll);
  1268. var sinPitch = Math.sin(halfPitch);
  1269. var cosPitch = Math.cos(halfPitch);
  1270. var sinYaw = Math.sin(halfYaw);
  1271. var cosYaw = Math.cos(halfYaw);
  1272. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1273. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1274. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1275. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1276. };
  1277. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1278. var result = new Quaternion();
  1279. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1280. return result;
  1281. };
  1282. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1283. // Produces a quaternion from Euler angles in the z-x-z orientation
  1284. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1285. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1286. var halfBeta = beta * 0.5;
  1287. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1288. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1289. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1290. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1291. };
  1292. Quaternion.Slerp = function (left, right, amount) {
  1293. var num2;
  1294. var num3;
  1295. var num = amount;
  1296. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1297. var flag = false;
  1298. if (num4 < 0) {
  1299. flag = true;
  1300. num4 = -num4;
  1301. }
  1302. if (num4 > 0.999999) {
  1303. num3 = 1 - num;
  1304. num2 = flag ? -num : num;
  1305. }
  1306. else {
  1307. var num5 = Math.acos(num4);
  1308. var num6 = (1.0 / Math.sin(num5));
  1309. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1310. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1311. }
  1312. 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));
  1313. };
  1314. return Quaternion;
  1315. })();
  1316. BABYLON.Quaternion = Quaternion;
  1317. var Matrix = (function () {
  1318. function Matrix() {
  1319. this.m = new Float32Array(16);
  1320. }
  1321. // Properties
  1322. Matrix.prototype.isIdentity = function () {
  1323. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1324. return false;
  1325. 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)
  1326. return false;
  1327. return true;
  1328. };
  1329. Matrix.prototype.determinant = function () {
  1330. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1331. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1332. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1333. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1334. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1335. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1336. 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))));
  1337. };
  1338. // Methods
  1339. Matrix.prototype.toArray = function () {
  1340. return this.m;
  1341. };
  1342. Matrix.prototype.asArray = function () {
  1343. return this.toArray();
  1344. };
  1345. Matrix.prototype.invert = function () {
  1346. this.invertToRef(this);
  1347. return this;
  1348. };
  1349. Matrix.prototype.invertToRef = function (other) {
  1350. var l1 = this.m[0];
  1351. var l2 = this.m[1];
  1352. var l3 = this.m[2];
  1353. var l4 = this.m[3];
  1354. var l5 = this.m[4];
  1355. var l6 = this.m[5];
  1356. var l7 = this.m[6];
  1357. var l8 = this.m[7];
  1358. var l9 = this.m[8];
  1359. var l10 = this.m[9];
  1360. var l11 = this.m[10];
  1361. var l12 = this.m[11];
  1362. var l13 = this.m[12];
  1363. var l14 = this.m[13];
  1364. var l15 = this.m[14];
  1365. var l16 = this.m[15];
  1366. var l17 = (l11 * l16) - (l12 * l15);
  1367. var l18 = (l10 * l16) - (l12 * l14);
  1368. var l19 = (l10 * l15) - (l11 * l14);
  1369. var l20 = (l9 * l16) - (l12 * l13);
  1370. var l21 = (l9 * l15) - (l11 * l13);
  1371. var l22 = (l9 * l14) - (l10 * l13);
  1372. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1373. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1374. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1375. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1376. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1377. var l28 = (l7 * l16) - (l8 * l15);
  1378. var l29 = (l6 * l16) - (l8 * l14);
  1379. var l30 = (l6 * l15) - (l7 * l14);
  1380. var l31 = (l5 * l16) - (l8 * l13);
  1381. var l32 = (l5 * l15) - (l7 * l13);
  1382. var l33 = (l5 * l14) - (l6 * l13);
  1383. var l34 = (l7 * l12) - (l8 * l11);
  1384. var l35 = (l6 * l12) - (l8 * l10);
  1385. var l36 = (l6 * l11) - (l7 * l10);
  1386. var l37 = (l5 * l12) - (l8 * l9);
  1387. var l38 = (l5 * l11) - (l7 * l9);
  1388. var l39 = (l5 * l10) - (l6 * l9);
  1389. other.m[0] = l23 * l27;
  1390. other.m[4] = l24 * l27;
  1391. other.m[8] = l25 * l27;
  1392. other.m[12] = l26 * l27;
  1393. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1394. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1395. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1396. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1397. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1398. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1399. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1400. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1401. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1402. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1403. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1404. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1405. return this;
  1406. };
  1407. Matrix.prototype.invertToRefSIMD = function (other) {
  1408. var src = this.m;
  1409. var dest = other.m;
  1410. var row0, row1, row2, row3;
  1411. var tmp1;
  1412. var minor0, minor1, minor2, minor3;
  1413. var det;
  1414. // Load the 4 rows
  1415. var src0 = SIMD.float32x4.load(src, 0);
  1416. var src1 = SIMD.float32x4.load(src, 4);
  1417. var src2 = SIMD.float32x4.load(src, 8);
  1418. var src3 = SIMD.float32x4.load(src, 12);
  1419. // Transpose the source matrix. Sort of. Not a true transpose operation
  1420. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1421. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1422. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1423. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1424. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1425. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1426. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1427. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1428. // This is a true transposition, but it will lead to an incorrect result
  1429. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1430. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1431. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1432. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1433. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1434. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1435. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1436. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1437. // ----
  1438. tmp1 = SIMD.float32x4.mul(row2, row3);
  1439. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1440. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1441. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1442. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1443. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1444. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1445. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1446. // ----
  1447. tmp1 = SIMD.float32x4.mul(row1, row2);
  1448. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1449. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1450. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1451. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1452. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1453. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1454. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1455. // ----
  1456. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1457. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1458. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1459. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1460. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1461. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1462. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1463. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1464. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1465. // ----
  1466. tmp1 = SIMD.float32x4.mul(row0, row1);
  1467. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1468. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1469. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1470. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1471. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1472. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1473. // ----
  1474. tmp1 = SIMD.float32x4.mul(row0, row3);
  1475. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1476. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1477. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1478. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1479. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1480. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1481. // ----
  1482. tmp1 = SIMD.float32x4.mul(row0, row2);
  1483. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1484. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1485. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1486. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1487. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1488. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1489. // Compute determinant
  1490. det = SIMD.float32x4.mul(row0, minor0);
  1491. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1492. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1493. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  1494. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1495. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1496. // These shuffles aren't necessary if the faulty transposition is done
  1497. // up at the top of this function.
  1498. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1499. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1500. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1501. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1502. // Compute final values by multiplying with 1/det
  1503. minor0 = SIMD.float32x4.mul(det, minor0);
  1504. minor1 = SIMD.float32x4.mul(det, minor1);
  1505. minor2 = SIMD.float32x4.mul(det, minor2);
  1506. minor3 = SIMD.float32x4.mul(det, minor3);
  1507. SIMD.float32x4.store(dest, 0, minor0);
  1508. SIMD.float32x4.store(dest, 4, minor1);
  1509. SIMD.float32x4.store(dest, 8, minor2);
  1510. SIMD.float32x4.store(dest, 12, minor3);
  1511. return this;
  1512. };
  1513. Matrix.prototype.setTranslation = function (vector3) {
  1514. this.m[12] = vector3.x;
  1515. this.m[13] = vector3.y;
  1516. this.m[14] = vector3.z;
  1517. return this;
  1518. };
  1519. Matrix.prototype.multiply = function (other) {
  1520. var result = new Matrix();
  1521. this.multiplyToRef(other, result);
  1522. return result;
  1523. };
  1524. Matrix.prototype.copyFrom = function (other) {
  1525. for (var index = 0; index < 16; index++) {
  1526. this.m[index] = other.m[index];
  1527. }
  1528. return this;
  1529. };
  1530. Matrix.prototype.copyToArray = function (array, offset) {
  1531. if (offset === void 0) { offset = 0; }
  1532. for (var index = 0; index < 16; index++) {
  1533. array[offset + index] = this.m[index];
  1534. }
  1535. return this;
  1536. };
  1537. Matrix.prototype.multiplyToRef = function (other, result) {
  1538. this.multiplyToArray(other, result.m, 0);
  1539. return this;
  1540. };
  1541. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1542. var tm0 = this.m[0];
  1543. var tm1 = this.m[1];
  1544. var tm2 = this.m[2];
  1545. var tm3 = this.m[3];
  1546. var tm4 = this.m[4];
  1547. var tm5 = this.m[5];
  1548. var tm6 = this.m[6];
  1549. var tm7 = this.m[7];
  1550. var tm8 = this.m[8];
  1551. var tm9 = this.m[9];
  1552. var tm10 = this.m[10];
  1553. var tm11 = this.m[11];
  1554. var tm12 = this.m[12];
  1555. var tm13 = this.m[13];
  1556. var tm14 = this.m[14];
  1557. var tm15 = this.m[15];
  1558. var om0 = other.m[0];
  1559. var om1 = other.m[1];
  1560. var om2 = other.m[2];
  1561. var om3 = other.m[3];
  1562. var om4 = other.m[4];
  1563. var om5 = other.m[5];
  1564. var om6 = other.m[6];
  1565. var om7 = other.m[7];
  1566. var om8 = other.m[8];
  1567. var om9 = other.m[9];
  1568. var om10 = other.m[10];
  1569. var om11 = other.m[11];
  1570. var om12 = other.m[12];
  1571. var om13 = other.m[13];
  1572. var om14 = other.m[14];
  1573. var om15 = other.m[15];
  1574. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1575. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1576. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1577. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1578. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1579. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1580. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1581. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1582. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1583. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1584. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1585. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1586. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1587. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1588. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1589. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1590. return this;
  1591. };
  1592. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1593. if (offset === void 0) { offset = 0; }
  1594. var tm = this.m;
  1595. var om = other.m;
  1596. var om0 = SIMD.float32x4.load(om, 0);
  1597. var om1 = SIMD.float32x4.load(om, 4);
  1598. var om2 = SIMD.float32x4.load(om, 8);
  1599. var om3 = SIMD.float32x4.load(om, 12);
  1600. var tm0 = SIMD.float32x4.load(tm, 0);
  1601. SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
  1602. var tm1 = SIMD.float32x4.load(tm, 4);
  1603. SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
  1604. var tm2 = SIMD.float32x4.load(tm, 8);
  1605. SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
  1606. var tm3 = SIMD.float32x4.load(tm, 12);
  1607. SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
  1608. };
  1609. Matrix.prototype.equals = function (value) {
  1610. 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]);
  1611. };
  1612. Matrix.prototype.clone = function () {
  1613. 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]);
  1614. };
  1615. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1616. translation.x = this.m[12];
  1617. translation.y = this.m[13];
  1618. translation.z = this.m[14];
  1619. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1620. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1621. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1622. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1623. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1624. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1625. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1626. rotation.x = 0;
  1627. rotation.y = 0;
  1628. rotation.z = 0;
  1629. rotation.w = 1;
  1630. return false;
  1631. }
  1632. 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);
  1633. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1634. return true;
  1635. };
  1636. // Statics
  1637. Matrix.FromArray = function (array, offset) {
  1638. var result = new Matrix();
  1639. if (!offset) {
  1640. offset = 0;
  1641. }
  1642. Matrix.FromArrayToRef(array, offset, result);
  1643. return result;
  1644. };
  1645. Matrix.FromArrayToRef = function (array, offset, result) {
  1646. for (var index = 0; index < 16; index++) {
  1647. result.m[index] = array[index + offset];
  1648. }
  1649. };
  1650. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1651. result.m[0] = initialM11;
  1652. result.m[1] = initialM12;
  1653. result.m[2] = initialM13;
  1654. result.m[3] = initialM14;
  1655. result.m[4] = initialM21;
  1656. result.m[5] = initialM22;
  1657. result.m[6] = initialM23;
  1658. result.m[7] = initialM24;
  1659. result.m[8] = initialM31;
  1660. result.m[9] = initialM32;
  1661. result.m[10] = initialM33;
  1662. result.m[11] = initialM34;
  1663. result.m[12] = initialM41;
  1664. result.m[13] = initialM42;
  1665. result.m[14] = initialM43;
  1666. result.m[15] = initialM44;
  1667. };
  1668. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1669. var result = new Matrix();
  1670. result.m[0] = initialM11;
  1671. result.m[1] = initialM12;
  1672. result.m[2] = initialM13;
  1673. result.m[3] = initialM14;
  1674. result.m[4] = initialM21;
  1675. result.m[5] = initialM22;
  1676. result.m[6] = initialM23;
  1677. result.m[7] = initialM24;
  1678. result.m[8] = initialM31;
  1679. result.m[9] = initialM32;
  1680. result.m[10] = initialM33;
  1681. result.m[11] = initialM34;
  1682. result.m[12] = initialM41;
  1683. result.m[13] = initialM42;
  1684. result.m[14] = initialM43;
  1685. result.m[15] = initialM44;
  1686. return result;
  1687. };
  1688. Matrix.Compose = function (scale, rotation, translation) {
  1689. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1690. var rotationMatrix = Matrix.Identity();
  1691. rotation.toRotationMatrix(rotationMatrix);
  1692. result = result.multiply(rotationMatrix);
  1693. result.setTranslation(translation);
  1694. return result;
  1695. };
  1696. Matrix.Identity = function () {
  1697. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1698. };
  1699. Matrix.IdentityToRef = function (result) {
  1700. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1701. };
  1702. Matrix.Zero = function () {
  1703. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1704. };
  1705. Matrix.RotationX = function (angle) {
  1706. var result = new Matrix();
  1707. Matrix.RotationXToRef(angle, result);
  1708. return result;
  1709. };
  1710. Matrix.Invert = function (source) {
  1711. var result = new Matrix();
  1712. source.invertToRef(result);
  1713. return result;
  1714. };
  1715. Matrix.RotationXToRef = function (angle, result) {
  1716. var s = Math.sin(angle);
  1717. var c = Math.cos(angle);
  1718. result.m[0] = 1.0;
  1719. result.m[15] = 1.0;
  1720. result.m[5] = c;
  1721. result.m[10] = c;
  1722. result.m[9] = -s;
  1723. result.m[6] = s;
  1724. result.m[1] = 0;
  1725. result.m[2] = 0;
  1726. result.m[3] = 0;
  1727. result.m[4] = 0;
  1728. result.m[7] = 0;
  1729. result.m[8] = 0;
  1730. result.m[11] = 0;
  1731. result.m[12] = 0;
  1732. result.m[13] = 0;
  1733. result.m[14] = 0;
  1734. };
  1735. Matrix.RotationY = function (angle) {
  1736. var result = new Matrix();
  1737. Matrix.RotationYToRef(angle, result);
  1738. return result;
  1739. };
  1740. Matrix.RotationYToRef = function (angle, result) {
  1741. var s = Math.sin(angle);
  1742. var c = Math.cos(angle);
  1743. result.m[5] = 1.0;
  1744. result.m[15] = 1.0;
  1745. result.m[0] = c;
  1746. result.m[2] = -s;
  1747. result.m[8] = s;
  1748. result.m[10] = c;
  1749. result.m[1] = 0;
  1750. result.m[3] = 0;
  1751. result.m[4] = 0;
  1752. result.m[6] = 0;
  1753. result.m[7] = 0;
  1754. result.m[9] = 0;
  1755. result.m[11] = 0;
  1756. result.m[12] = 0;
  1757. result.m[13] = 0;
  1758. result.m[14] = 0;
  1759. };
  1760. Matrix.RotationZ = function (angle) {
  1761. var result = new Matrix();
  1762. Matrix.RotationZToRef(angle, result);
  1763. return result;
  1764. };
  1765. Matrix.RotationZToRef = function (angle, result) {
  1766. var s = Math.sin(angle);
  1767. var c = Math.cos(angle);
  1768. result.m[10] = 1.0;
  1769. result.m[15] = 1.0;
  1770. result.m[0] = c;
  1771. result.m[1] = s;
  1772. result.m[4] = -s;
  1773. result.m[5] = c;
  1774. result.m[2] = 0;
  1775. result.m[3] = 0;
  1776. result.m[6] = 0;
  1777. result.m[7] = 0;
  1778. result.m[8] = 0;
  1779. result.m[9] = 0;
  1780. result.m[11] = 0;
  1781. result.m[12] = 0;
  1782. result.m[13] = 0;
  1783. result.m[14] = 0;
  1784. };
  1785. Matrix.RotationAxis = function (axis, angle) {
  1786. var s = Math.sin(-angle);
  1787. var c = Math.cos(-angle);
  1788. var c1 = 1 - c;
  1789. axis.normalize();
  1790. var result = Matrix.Zero();
  1791. result.m[0] = (axis.x * axis.x) * c1 + c;
  1792. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1793. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1794. result.m[3] = 0.0;
  1795. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1796. result.m[5] = (axis.y * axis.y) * c1 + c;
  1797. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1798. result.m[7] = 0.0;
  1799. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1800. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1801. result.m[10] = (axis.z * axis.z) * c1 + c;
  1802. result.m[11] = 0.0;
  1803. result.m[15] = 1.0;
  1804. return result;
  1805. };
  1806. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1807. var result = new Matrix();
  1808. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1809. return result;
  1810. };
  1811. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1812. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1813. this._tempQuaternion.toRotationMatrix(result);
  1814. };
  1815. Matrix.Scaling = function (x, y, z) {
  1816. var result = Matrix.Zero();
  1817. Matrix.ScalingToRef(x, y, z, result);
  1818. return result;
  1819. };
  1820. Matrix.ScalingToRef = function (x, y, z, result) {
  1821. result.m[0] = x;
  1822. result.m[1] = 0;
  1823. result.m[2] = 0;
  1824. result.m[3] = 0;
  1825. result.m[4] = 0;
  1826. result.m[5] = y;
  1827. result.m[6] = 0;
  1828. result.m[7] = 0;
  1829. result.m[8] = 0;
  1830. result.m[9] = 0;
  1831. result.m[10] = z;
  1832. result.m[11] = 0;
  1833. result.m[12] = 0;
  1834. result.m[13] = 0;
  1835. result.m[14] = 0;
  1836. result.m[15] = 1.0;
  1837. };
  1838. Matrix.Translation = function (x, y, z) {
  1839. var result = Matrix.Identity();
  1840. Matrix.TranslationToRef(x, y, z, result);
  1841. return result;
  1842. };
  1843. Matrix.TranslationToRef = function (x, y, z, result) {
  1844. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1845. };
  1846. Matrix.LookAtLH = function (eye, target, up) {
  1847. var result = Matrix.Zero();
  1848. Matrix.LookAtLHToRef(eye, target, up, result);
  1849. return result;
  1850. };
  1851. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1852. // Z axis
  1853. target.subtractToRef(eye, this._zAxis);
  1854. this._zAxis.normalize();
  1855. // X axis
  1856. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1857. this._xAxis.normalize();
  1858. // Y axis
  1859. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1860. this._yAxis.normalize();
  1861. // Eye angles
  1862. var ex = -Vector3.Dot(this._xAxis, eye);
  1863. var ey = -Vector3.Dot(this._yAxis, eye);
  1864. var ez = -Vector3.Dot(this._zAxis, eye);
  1865. 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);
  1866. };
  1867. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  1868. var out = result.m;
  1869. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  1870. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  1871. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  1872. // cc.kmVec3Subtract(f, pCenter, pEye);
  1873. var f = SIMD.float32x4.sub(center, eye);
  1874. // cc.kmVec3Normalize(f, f);
  1875. var tmp = SIMD.float32x4.mul(f, f);
  1876. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1877. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1878. // cc.kmVec3Assign(up, pUp);
  1879. // cc.kmVec3Normalize(up, up);
  1880. tmp = SIMD.float32x4.mul(up, up);
  1881. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1882. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1883. // cc.kmVec3Cross(s, f, up);
  1884. var s = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 1, 2, 0, 3), SIMD.float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 2, 0, 1, 3), SIMD.float32x4.swizzle(up, 1, 2, 0, 3)));
  1885. // cc.kmVec3Normalize(s, s);
  1886. tmp = SIMD.float32x4.mul(s, s);
  1887. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1888. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1889. // cc.kmVec3Cross(u, s, f);
  1890. var u = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 1, 2, 0, 3), SIMD.float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 2, 0, 1, 3), SIMD.float32x4.swizzle(f, 1, 2, 0, 3)));
  1891. // cc.kmVec3Normalize(s, s);
  1892. tmp = SIMD.float32x4.mul(s, s);
  1893. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1894. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1895. var zero = SIMD.float32x4.splat(0.0);
  1896. s = SIMD.float32x4.neg(s);
  1897. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  1898. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  1899. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1900. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  1901. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  1902. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  1903. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1904. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  1905. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  1906. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  1907. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  1908. var b3 = SIMD.float32x4.neg(eye);
  1909. b3 = SIMD.float32x4.withW(b3, 1.0);
  1910. SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
  1911. SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
  1912. SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
  1913. SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
  1914. };
  1915. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1916. var matrix = Matrix.Zero();
  1917. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1918. return matrix;
  1919. };
  1920. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1921. var hw = 2.0 / width;
  1922. var hh = 2.0 / height;
  1923. var id = 1.0 / (zfar - znear);
  1924. var nid = znear / (znear - zfar);
  1925. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1926. };
  1927. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1928. var matrix = Matrix.Zero();
  1929. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1930. return matrix;
  1931. };
  1932. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1933. result.m[0] = 2.0 / (right - left);
  1934. result.m[1] = result.m[2] = result.m[3] = 0;
  1935. result.m[5] = 2.0 / (top - bottom);
  1936. result.m[4] = result.m[6] = result.m[7] = 0;
  1937. result.m[10] = -1.0 / (znear - zfar);
  1938. result.m[8] = result.m[9] = result.m[11] = 0;
  1939. result.m[12] = (left + right) / (left - right);
  1940. result.m[13] = (top + bottom) / (bottom - top);
  1941. result.m[14] = znear / (znear - zfar);
  1942. result.m[15] = 1.0;
  1943. };
  1944. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1945. var matrix = Matrix.Zero();
  1946. matrix.m[0] = (2.0 * znear) / width;
  1947. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1948. matrix.m[5] = (2.0 * znear) / height;
  1949. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1950. matrix.m[10] = -zfar / (znear - zfar);
  1951. matrix.m[8] = matrix.m[9] = 0.0;
  1952. matrix.m[11] = 1.0;
  1953. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1954. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1955. return matrix;
  1956. };
  1957. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1958. var matrix = Matrix.Zero();
  1959. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1960. return matrix;
  1961. };
  1962. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1963. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1964. var tan = 1.0 / (Math.tan(fov * 0.5));
  1965. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1966. if (v_fixed) {
  1967. result.m[0] = tan / aspect;
  1968. }
  1969. else {
  1970. result.m[0] = tan;
  1971. }
  1972. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1973. if (v_fixed) {
  1974. result.m[5] = tan;
  1975. }
  1976. else {
  1977. result.m[5] = tan * aspect;
  1978. }
  1979. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1980. result.m[8] = result.m[9] = 0.0;
  1981. result.m[10] = -zfar / (znear - zfar);
  1982. result.m[11] = 1.0;
  1983. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1984. result.m[14] = (znear * zfar) / (znear - zfar);
  1985. };
  1986. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1987. var cw = viewport.width;
  1988. var ch = viewport.height;
  1989. var cx = viewport.x;
  1990. var cy = viewport.y;
  1991. 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);
  1992. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1993. };
  1994. Matrix.Transpose = function (matrix) {
  1995. var result = new Matrix();
  1996. result.m[0] = matrix.m[0];
  1997. result.m[1] = matrix.m[4];
  1998. result.m[2] = matrix.m[8];
  1999. result.m[3] = matrix.m[12];
  2000. result.m[4] = matrix.m[1];
  2001. result.m[5] = matrix.m[5];
  2002. result.m[6] = matrix.m[9];
  2003. result.m[7] = matrix.m[13];
  2004. result.m[8] = matrix.m[2];
  2005. result.m[9] = matrix.m[6];
  2006. result.m[10] = matrix.m[10];
  2007. result.m[11] = matrix.m[14];
  2008. result.m[12] = matrix.m[3];
  2009. result.m[13] = matrix.m[7];
  2010. result.m[14] = matrix.m[11];
  2011. result.m[15] = matrix.m[15];
  2012. return result;
  2013. };
  2014. Matrix.Reflection = function (plane) {
  2015. var matrix = new Matrix();
  2016. Matrix.ReflectionToRef(plane, matrix);
  2017. return matrix;
  2018. };
  2019. Matrix.ReflectionToRef = function (plane, result) {
  2020. plane.normalize();
  2021. var x = plane.normal.x;
  2022. var y = plane.normal.y;
  2023. var z = plane.normal.z;
  2024. var temp = -2 * x;
  2025. var temp2 = -2 * y;
  2026. var temp3 = -2 * z;
  2027. result.m[0] = (temp * x) + 1;
  2028. result.m[1] = temp2 * x;
  2029. result.m[2] = temp3 * x;
  2030. result.m[3] = 0.0;
  2031. result.m[4] = temp * y;
  2032. result.m[5] = (temp2 * y) + 1;
  2033. result.m[6] = temp3 * y;
  2034. result.m[7] = 0.0;
  2035. result.m[8] = temp * z;
  2036. result.m[9] = temp2 * z;
  2037. result.m[10] = (temp3 * z) + 1;
  2038. result.m[11] = 0.0;
  2039. result.m[12] = temp * plane.d;
  2040. result.m[13] = temp2 * plane.d;
  2041. result.m[14] = temp3 * plane.d;
  2042. result.m[15] = 1.0;
  2043. };
  2044. Matrix._tempQuaternion = new Quaternion();
  2045. Matrix._xAxis = Vector3.Zero();
  2046. Matrix._yAxis = Vector3.Zero();
  2047. Matrix._zAxis = Vector3.Zero();
  2048. return Matrix;
  2049. })();
  2050. BABYLON.Matrix = Matrix;
  2051. var Plane = (function () {
  2052. function Plane(a, b, c, d) {
  2053. this.normal = new Vector3(a, b, c);
  2054. this.d = d;
  2055. }
  2056. Plane.prototype.asArray = function () {
  2057. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2058. };
  2059. // Methods
  2060. Plane.prototype.clone = function () {
  2061. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2062. };
  2063. Plane.prototype.normalize = function () {
  2064. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2065. var magnitude = 0;
  2066. if (norm !== 0) {
  2067. magnitude = 1.0 / norm;
  2068. }
  2069. this.normal.x *= magnitude;
  2070. this.normal.y *= magnitude;
  2071. this.normal.z *= magnitude;
  2072. this.d *= magnitude;
  2073. return this;
  2074. };
  2075. Plane.prototype.transform = function (transformation) {
  2076. var transposedMatrix = Matrix.Transpose(transformation);
  2077. var x = this.normal.x;
  2078. var y = this.normal.y;
  2079. var z = this.normal.z;
  2080. var d = this.d;
  2081. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2082. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2083. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2084. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2085. return new Plane(normalX, normalY, normalZ, finalD);
  2086. };
  2087. Plane.prototype.dotCoordinate = function (point) {
  2088. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2089. };
  2090. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2091. var x1 = point2.x - point1.x;
  2092. var y1 = point2.y - point1.y;
  2093. var z1 = point2.z - point1.z;
  2094. var x2 = point3.x - point1.x;
  2095. var y2 = point3.y - point1.y;
  2096. var z2 = point3.z - point1.z;
  2097. var yz = (y1 * z2) - (z1 * y2);
  2098. var xz = (z1 * x2) - (x1 * z2);
  2099. var xy = (x1 * y2) - (y1 * x2);
  2100. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2101. var invPyth;
  2102. if (pyth !== 0) {
  2103. invPyth = 1.0 / pyth;
  2104. }
  2105. else {
  2106. invPyth = 0;
  2107. }
  2108. this.normal.x = yz * invPyth;
  2109. this.normal.y = xz * invPyth;
  2110. this.normal.z = xy * invPyth;
  2111. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2112. return this;
  2113. };
  2114. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2115. var dot = Vector3.Dot(this.normal, direction);
  2116. return (dot <= epsilon);
  2117. };
  2118. Plane.prototype.signedDistanceTo = function (point) {
  2119. return Vector3.Dot(point, this.normal) + this.d;
  2120. };
  2121. // Statics
  2122. Plane.FromArray = function (array) {
  2123. return new Plane(array[0], array[1], array[2], array[3]);
  2124. };
  2125. Plane.FromPoints = function (point1, point2, point3) {
  2126. var result = new Plane(0, 0, 0, 0);
  2127. result.copyFromPoints(point1, point2, point3);
  2128. return result;
  2129. };
  2130. Plane.FromPositionAndNormal = function (origin, normal) {
  2131. var result = new Plane(0, 0, 0, 0);
  2132. normal.normalize();
  2133. result.normal = normal;
  2134. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2135. return result;
  2136. };
  2137. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2138. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2139. return Vector3.Dot(point, normal) + d;
  2140. };
  2141. return Plane;
  2142. })();
  2143. BABYLON.Plane = Plane;
  2144. var Viewport = (function () {
  2145. function Viewport(x, y, width, height) {
  2146. this.x = x;
  2147. this.y = y;
  2148. this.width = width;
  2149. this.height = height;
  2150. }
  2151. Viewport.prototype.toGlobal = function (engine) {
  2152. var width = engine.getRenderWidth();
  2153. var height = engine.getRenderHeight();
  2154. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2155. };
  2156. return Viewport;
  2157. })();
  2158. BABYLON.Viewport = Viewport;
  2159. var Frustum = (function () {
  2160. function Frustum() {
  2161. }
  2162. Frustum.GetPlanes = function (transform) {
  2163. var frustumPlanes = [];
  2164. for (var index = 0; index < 6; index++) {
  2165. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2166. }
  2167. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2168. return frustumPlanes;
  2169. };
  2170. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2171. // Near
  2172. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2173. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2174. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  2175. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2176. frustumPlanes[0].normalize();
  2177. // Far
  2178. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2179. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2180. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2181. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2182. frustumPlanes[1].normalize();
  2183. // Left
  2184. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2185. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2186. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2187. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2188. frustumPlanes[2].normalize();
  2189. // Right
  2190. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2191. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2192. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2193. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2194. frustumPlanes[3].normalize();
  2195. // Top
  2196. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2197. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2198. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2199. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2200. frustumPlanes[4].normalize();
  2201. // Bottom
  2202. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2203. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2204. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2205. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2206. frustumPlanes[5].normalize();
  2207. };
  2208. return Frustum;
  2209. })();
  2210. BABYLON.Frustum = Frustum;
  2211. var Ray = (function () {
  2212. function Ray(origin, direction, length) {
  2213. if (length === void 0) { length = Number.MAX_VALUE; }
  2214. this.origin = origin;
  2215. this.direction = direction;
  2216. this.length = length;
  2217. }
  2218. // Methods
  2219. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2220. var d = 0.0;
  2221. var maxValue = Number.MAX_VALUE;
  2222. if (Math.abs(this.direction.x) < 0.0000001) {
  2223. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2224. return false;
  2225. }
  2226. }
  2227. else {
  2228. var inv = 1.0 / this.direction.x;
  2229. var min = (minimum.x - this.origin.x) * inv;
  2230. var max = (maximum.x - this.origin.x) * inv;
  2231. if (max === -Infinity) {
  2232. max = Infinity;
  2233. }
  2234. if (min > max) {
  2235. var temp = min;
  2236. min = max;
  2237. max = temp;
  2238. }
  2239. d = Math.max(min, d);
  2240. maxValue = Math.min(max, maxValue);
  2241. if (d > maxValue) {
  2242. return false;
  2243. }
  2244. }
  2245. if (Math.abs(this.direction.y) < 0.0000001) {
  2246. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2247. return false;
  2248. }
  2249. }
  2250. else {
  2251. inv = 1.0 / this.direction.y;
  2252. min = (minimum.y - this.origin.y) * inv;
  2253. max = (maximum.y - this.origin.y) * inv;
  2254. if (max === -Infinity) {
  2255. max = Infinity;
  2256. }
  2257. if (min > max) {
  2258. temp = min;
  2259. min = max;
  2260. max = temp;
  2261. }
  2262. d = Math.max(min, d);
  2263. maxValue = Math.min(max, maxValue);
  2264. if (d > maxValue) {
  2265. return false;
  2266. }
  2267. }
  2268. if (Math.abs(this.direction.z) < 0.0000001) {
  2269. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2270. return false;
  2271. }
  2272. }
  2273. else {
  2274. inv = 1.0 / this.direction.z;
  2275. min = (minimum.z - this.origin.z) * inv;
  2276. max = (maximum.z - this.origin.z) * inv;
  2277. if (max === -Infinity) {
  2278. max = Infinity;
  2279. }
  2280. if (min > max) {
  2281. temp = min;
  2282. min = max;
  2283. max = temp;
  2284. }
  2285. d = Math.max(min, d);
  2286. maxValue = Math.min(max, maxValue);
  2287. if (d > maxValue) {
  2288. return false;
  2289. }
  2290. }
  2291. return true;
  2292. };
  2293. Ray.prototype.intersectsBox = function (box) {
  2294. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2295. };
  2296. Ray.prototype.intersectsSphere = function (sphere) {
  2297. var x = sphere.center.x - this.origin.x;
  2298. var y = sphere.center.y - this.origin.y;
  2299. var z = sphere.center.z - this.origin.z;
  2300. var pyth = (x * x) + (y * y) + (z * z);
  2301. var rr = sphere.radius * sphere.radius;
  2302. if (pyth <= rr) {
  2303. return true;
  2304. }
  2305. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2306. if (dot < 0.0) {
  2307. return false;
  2308. }
  2309. var temp = pyth - (dot * dot);
  2310. return temp <= rr;
  2311. };
  2312. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2313. if (!this._edge1) {
  2314. this._edge1 = Vector3.Zero();
  2315. this._edge2 = Vector3.Zero();
  2316. this._pvec = Vector3.Zero();
  2317. this._tvec = Vector3.Zero();
  2318. this._qvec = Vector3.Zero();
  2319. }
  2320. vertex1.subtractToRef(vertex0, this._edge1);
  2321. vertex2.subtractToRef(vertex0, this._edge2);
  2322. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2323. var det = Vector3.Dot(this._edge1, this._pvec);
  2324. if (det === 0) {
  2325. return null;
  2326. }
  2327. var invdet = 1 / det;
  2328. this.origin.subtractToRef(vertex0, this._tvec);
  2329. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2330. if (bu < 0 || bu > 1.0) {
  2331. return null;
  2332. }
  2333. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2334. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2335. if (bv < 0 || bu + bv > 1.0) {
  2336. return null;
  2337. }
  2338. //check if the distance is longer than the predefined length.
  2339. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2340. if (distance > this.length) {
  2341. return null;
  2342. }
  2343. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2344. };
  2345. // Statics
  2346. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2347. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2348. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2349. var direction = end.subtract(start);
  2350. direction.normalize();
  2351. return new Ray(start, direction);
  2352. };
  2353. /**
  2354. * 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
  2355. * transformed to the given world matrix.
  2356. * @param origin The origin point
  2357. * @param end The end point
  2358. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2359. */
  2360. Ray.CreateNewFromTo = function (origin, end, world) {
  2361. if (world === void 0) { world = Matrix.Identity(); }
  2362. var direction = end.subtract(origin);
  2363. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2364. direction.normalize();
  2365. return Ray.Transform(new Ray(origin, direction, length), world);
  2366. };
  2367. Ray.Transform = function (ray, matrix) {
  2368. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2369. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2370. return new Ray(newOrigin, newDirection, ray.length);
  2371. };
  2372. return Ray;
  2373. })();
  2374. BABYLON.Ray = Ray;
  2375. (function (Space) {
  2376. Space[Space["LOCAL"] = 0] = "LOCAL";
  2377. Space[Space["WORLD"] = 1] = "WORLD";
  2378. })(BABYLON.Space || (BABYLON.Space = {}));
  2379. var Space = BABYLON.Space;
  2380. var Axis = (function () {
  2381. function Axis() {
  2382. }
  2383. Axis.X = new Vector3(1, 0, 0);
  2384. Axis.Y = new Vector3(0, 1, 0);
  2385. Axis.Z = new Vector3(0, 0, 1);
  2386. return Axis;
  2387. })();
  2388. BABYLON.Axis = Axis;
  2389. ;
  2390. var BezierCurve = (function () {
  2391. function BezierCurve() {
  2392. }
  2393. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2394. // Extract X (which is equal to time here)
  2395. var f0 = 1 - 3 * x2 + 3 * x1;
  2396. var f1 = 3 * x2 - 6 * x1;
  2397. var f2 = 3 * x1;
  2398. var refinedT = t;
  2399. for (var i = 0; i < 5; i++) {
  2400. var refinedT2 = refinedT * refinedT;
  2401. var refinedT3 = refinedT2 * refinedT;
  2402. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2403. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2404. refinedT -= (x - t) * slope;
  2405. refinedT = Math.min(1, Math.max(0, refinedT));
  2406. }
  2407. // Resolve cubic bezier for the given x
  2408. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2409. };
  2410. return BezierCurve;
  2411. })();
  2412. BABYLON.BezierCurve = BezierCurve;
  2413. (function (Orientation) {
  2414. Orientation[Orientation["CW"] = 0] = "CW";
  2415. Orientation[Orientation["CCW"] = 1] = "CCW";
  2416. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2417. var Orientation = BABYLON.Orientation;
  2418. var Angle = (function () {
  2419. function Angle(radians) {
  2420. var _this = this;
  2421. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2422. this.radians = function () { return _this._radians; };
  2423. this._radians = radians;
  2424. if (this._radians < 0)
  2425. this._radians += (2 * Math.PI);
  2426. }
  2427. Angle.BetweenTwoPoints = function (a, b) {
  2428. var delta = b.subtract(a);
  2429. var theta = Math.atan2(delta.y, delta.x);
  2430. return new Angle(theta);
  2431. };
  2432. Angle.FromRadians = function (radians) {
  2433. return new Angle(radians);
  2434. };
  2435. Angle.FromDegrees = function (degrees) {
  2436. return new Angle(degrees * Math.PI / 180);
  2437. };
  2438. return Angle;
  2439. })();
  2440. BABYLON.Angle = Angle;
  2441. var Arc2 = (function () {
  2442. function Arc2(startPoint, midPoint, endPoint) {
  2443. this.startPoint = startPoint;
  2444. this.midPoint = midPoint;
  2445. this.endPoint = endPoint;
  2446. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2447. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2448. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2449. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2450. 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);
  2451. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2452. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2453. var a1 = this.startAngle.degrees();
  2454. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2455. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2456. // angles correction
  2457. if (a2 - a1 > +180.0)
  2458. a2 -= 360.0;
  2459. if (a2 - a1 < -180.0)
  2460. a2 += 360.0;
  2461. if (a3 - a2 > +180.0)
  2462. a3 -= 360.0;
  2463. if (a3 - a2 < -180.0)
  2464. a3 += 360.0;
  2465. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2466. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2467. }
  2468. return Arc2;
  2469. })();
  2470. BABYLON.Arc2 = Arc2;
  2471. var PathCursor = (function () {
  2472. function PathCursor(path) {
  2473. this.path = path;
  2474. this._onchange = new Array();
  2475. this.value = 0;
  2476. this.animations = new Array();
  2477. }
  2478. PathCursor.prototype.getPoint = function () {
  2479. var point = this.path.getPointAtLengthPosition(this.value);
  2480. return new Vector3(point.x, 0, point.y);
  2481. };
  2482. PathCursor.prototype.moveAhead = function (step) {
  2483. if (step === void 0) { step = 0.002; }
  2484. this.move(step);
  2485. return this;
  2486. };
  2487. PathCursor.prototype.moveBack = function (step) {
  2488. if (step === void 0) { step = 0.002; }
  2489. this.move(-step);
  2490. return this;
  2491. };
  2492. PathCursor.prototype.move = function (step) {
  2493. if (Math.abs(step) > 1) {
  2494. throw "step size should be less than 1.";
  2495. }
  2496. this.value += step;
  2497. this.ensureLimits();
  2498. this.raiseOnChange();
  2499. return this;
  2500. };
  2501. PathCursor.prototype.ensureLimits = function () {
  2502. while (this.value > 1) {
  2503. this.value -= 1;
  2504. }
  2505. while (this.value < 0) {
  2506. this.value += 1;
  2507. }
  2508. return this;
  2509. };
  2510. // used by animation engine
  2511. PathCursor.prototype.markAsDirty = function (propertyName) {
  2512. this.ensureLimits();
  2513. this.raiseOnChange();
  2514. return this;
  2515. };
  2516. PathCursor.prototype.raiseOnChange = function () {
  2517. var _this = this;
  2518. this._onchange.forEach(function (f) { return f(_this); });
  2519. return this;
  2520. };
  2521. PathCursor.prototype.onchange = function (f) {
  2522. this._onchange.push(f);
  2523. return this;
  2524. };
  2525. return PathCursor;
  2526. })();
  2527. BABYLON.PathCursor = PathCursor;
  2528. var Path2 = (function () {
  2529. function Path2(x, y) {
  2530. this._points = new Array();
  2531. this._length = 0;
  2532. this.closed = false;
  2533. this._points.push(new Vector2(x, y));
  2534. }
  2535. Path2.prototype.addLineTo = function (x, y) {
  2536. if (closed) {
  2537. BABYLON.Tools.Error("cannot add lines to closed paths");
  2538. return this;
  2539. }
  2540. var newPoint = new Vector2(x, y);
  2541. var previousPoint = this._points[this._points.length - 1];
  2542. this._points.push(newPoint);
  2543. this._length += newPoint.subtract(previousPoint).length();
  2544. return this;
  2545. };
  2546. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2547. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2548. if (closed) {
  2549. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2550. return this;
  2551. }
  2552. var startPoint = this._points[this._points.length - 1];
  2553. var midPoint = new Vector2(midX, midY);
  2554. var endPoint = new Vector2(endX, endY);
  2555. var arc = new Arc2(startPoint, midPoint, endPoint);
  2556. var increment = arc.angle.radians() / numberOfSegments;
  2557. if (arc.orientation === 0 /* CW */)
  2558. increment *= -1;
  2559. var currentAngle = arc.startAngle.radians() + increment;
  2560. for (var i = 0; i < numberOfSegments; i++) {
  2561. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2562. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2563. this.addLineTo(x, y);
  2564. currentAngle += increment;
  2565. }
  2566. return this;
  2567. };
  2568. Path2.prototype.close = function () {
  2569. this.closed = true;
  2570. return this;
  2571. };
  2572. Path2.prototype.length = function () {
  2573. var result = this._length;
  2574. if (!this.closed) {
  2575. var lastPoint = this._points[this._points.length - 1];
  2576. var firstPoint = this._points[0];
  2577. result += (firstPoint.subtract(lastPoint).length());
  2578. }
  2579. return result;
  2580. };
  2581. Path2.prototype.getPoints = function () {
  2582. return this._points;
  2583. };
  2584. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2585. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2586. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2587. return Vector2.Zero();
  2588. }
  2589. var lengthPosition = normalizedLengthPosition * this.length();
  2590. var previousOffset = 0;
  2591. for (var i = 0; i < this._points.length; i++) {
  2592. var j = (i + 1) % this._points.length;
  2593. var a = this._points[i];
  2594. var b = this._points[j];
  2595. var bToA = b.subtract(a);
  2596. var nextOffset = (bToA.length() + previousOffset);
  2597. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2598. var dir = bToA.normalize();
  2599. var localOffset = lengthPosition - previousOffset;
  2600. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2601. }
  2602. previousOffset = nextOffset;
  2603. }
  2604. BABYLON.Tools.Error("internal error");
  2605. return Vector2.Zero();
  2606. };
  2607. Path2.StartingAt = function (x, y) {
  2608. return new Path2(x, y);
  2609. };
  2610. return Path2;
  2611. })();
  2612. BABYLON.Path2 = Path2;
  2613. var Path3D = (function () {
  2614. function Path3D(path) {
  2615. this.path = path;
  2616. this._curve = new Array();
  2617. this._distances = new Array();
  2618. this._tangents = new Array();
  2619. this._normals = new Array();
  2620. this._binormals = new Array();
  2621. this._curve = path.slice(); // copy array
  2622. this._compute();
  2623. }
  2624. Path3D.prototype.getCurve = function () {
  2625. return this._curve;
  2626. };
  2627. Path3D.prototype.getTangents = function () {
  2628. return this._tangents;
  2629. };
  2630. Path3D.prototype.getNormals = function () {
  2631. return this._normals;
  2632. };
  2633. Path3D.prototype.getBinormals = function () {
  2634. return this._binormals;
  2635. };
  2636. Path3D.prototype.getDistances = function () {
  2637. return this._distances;
  2638. };
  2639. Path3D.prototype.update = function (path) {
  2640. for (var i = 0; i < path.length; i++) {
  2641. this._curve[i] = path[i];
  2642. }
  2643. this._compute();
  2644. return this;
  2645. };
  2646. // private function compute() : computes tangents, normals and binormals
  2647. Path3D.prototype._compute = function () {
  2648. var l = this._curve.length;
  2649. // first and last tangents
  2650. this._tangents[0] = this._curve[1].subtract(this._curve[0]);
  2651. this._tangents[0].normalize();
  2652. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2653. this._tangents[l - 1].normalize();
  2654. // normals and binormals at first point : arbitrary vector with _normalVector()
  2655. var tg0 = this._tangents[0];
  2656. var pp0 = this._normalVector(this._curve[0], tg0);
  2657. this._normals[0] = pp0;
  2658. this._normals[0].normalize();
  2659. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2660. this._normals[0].normalize();
  2661. this._distances[0] = 0;
  2662. // normals and binormals : next points
  2663. var prev; // previous vector (segment)
  2664. var cur; // current vector (segment)
  2665. var curTang; // current tangent
  2666. var prevNorm; // previous normal
  2667. var prevBinor; // previous binormal
  2668. for (var i = 1; i < l; i++) {
  2669. // tangents
  2670. prev = this._curve[i].subtract(this._curve[i - 1]);
  2671. if (i < l - 1) {
  2672. cur = this._curve[i + 1].subtract(this._curve[i]);
  2673. this._tangents[i] = prev.add(cur);
  2674. this._tangents[i].normalize();
  2675. }
  2676. this._distances[i] = this._distances[i - 1] + prev.length();
  2677. // normals and binormals
  2678. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2679. curTang = this._tangents[i];
  2680. prevNorm = this._normals[i - 1];
  2681. prevBinor = this._binormals[i - 1];
  2682. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2683. this._normals[i].normalize();
  2684. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2685. this._binormals[i].normalize();
  2686. }
  2687. };
  2688. // private function normalVector(v0, vt) :
  2689. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2690. Path3D.prototype._normalVector = function (v0, vt) {
  2691. var point;
  2692. if (vt.x !== 1) {
  2693. point = new Vector3(1, 0, 0);
  2694. }
  2695. else if (vt.y !== 1) {
  2696. point = new Vector3(0, 1, 0);
  2697. }
  2698. else if (vt.z !== 1) {
  2699. point = new Vector3(0, 0, 1);
  2700. }
  2701. var normal0 = Vector3.Cross(vt, point);
  2702. normal0.normalize();
  2703. return normal0;
  2704. };
  2705. return Path3D;
  2706. })();
  2707. BABYLON.Path3D = Path3D;
  2708. var Curve3 = (function () {
  2709. function Curve3(points) {
  2710. this._points = points;
  2711. }
  2712. // QuadraticBezier(origin_V3, control_V3, destination_V3 )
  2713. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2714. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2715. var bez = new Array();
  2716. var step = 1 / nbPoints;
  2717. var equation = function (t, val0, val1, val2) {
  2718. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2719. return res;
  2720. };
  2721. for (var i = 0; i <= 1; i += step) {
  2722. bez.push(new Vector3(equation(i, v0.x, v1.x, v2.x), equation(i, v0.y, v1.y, v2.y), equation(i, v0.z, v1.z, v2.z)));
  2723. }
  2724. return new Curve3(bez);
  2725. };
  2726. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3)
  2727. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2728. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2729. var bez = new Array();
  2730. var step = 1 / nbPoints;
  2731. var equation = function (t, val0, val1, val2, val3) {
  2732. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2733. return res;
  2734. };
  2735. for (var i = 0; i <= 1; i += step) {
  2736. bez.push(new Vector3(equation(i, v0.x, v1.x, v2.x, v3.x), equation(i, v0.y, v1.y, v2.y, v3.y), equation(i, v0.z, v1.z, v2.z, v3.z)));
  2737. }
  2738. return new Curve3(bez);
  2739. };
  2740. Curve3.prototype.getPoints = function () {
  2741. return this._points;
  2742. };
  2743. Curve3.prototype.continue = function (curve) {
  2744. var lastPoint = this._points[this._points.length - 1];
  2745. var continuedPoints = this._points.slice();
  2746. var curvePoints = curve.getPoints();
  2747. for (var i = 1; i < curvePoints.length; i++) {
  2748. continuedPoints.push(curvePoints[i].add(lastPoint));
  2749. }
  2750. return new Curve3(continuedPoints);
  2751. };
  2752. return Curve3;
  2753. })();
  2754. BABYLON.Curve3 = Curve3;
  2755. // Vertex formats
  2756. var PositionNormalVertex = (function () {
  2757. function PositionNormalVertex(position, normal) {
  2758. if (position === void 0) { position = Vector3.Zero(); }
  2759. if (normal === void 0) { normal = Vector3.Up(); }
  2760. this.position = position;
  2761. this.normal = normal;
  2762. }
  2763. PositionNormalVertex.prototype.clone = function () {
  2764. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2765. };
  2766. return PositionNormalVertex;
  2767. })();
  2768. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2769. var PositionNormalTextureVertex = (function () {
  2770. function PositionNormalTextureVertex(position, normal, uv) {
  2771. if (position === void 0) { position = Vector3.Zero(); }
  2772. if (normal === void 0) { normal = Vector3.Up(); }
  2773. if (uv === void 0) { uv = Vector2.Zero(); }
  2774. this.position = position;
  2775. this.normal = normal;
  2776. this.uv = uv;
  2777. }
  2778. PositionNormalTextureVertex.prototype.clone = function () {
  2779. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2780. };
  2781. return PositionNormalTextureVertex;
  2782. })();
  2783. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2784. // SIMD
  2785. var previousMultiplyToArray = Matrix.prototype.multiplyToArray;
  2786. var previousInvertToRef = Matrix.prototype.invertToRef;
  2787. var previousLookAtLHToRef = Matrix.LookAtLHToRef;
  2788. var previousTransformCoordinatesToRef = Vector3.TransformCoordinatesToRef;
  2789. var previousTransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRef;
  2790. var SIMDHelper = (function () {
  2791. function SIMDHelper() {
  2792. }
  2793. Object.defineProperty(SIMDHelper, "IsEnabled", {
  2794. get: function () {
  2795. return SIMDHelper._isEnabled;
  2796. },
  2797. enumerable: true,
  2798. configurable: true
  2799. });
  2800. SIMDHelper.DisableSIMD = function () {
  2801. // Replace functions
  2802. Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  2803. Matrix.prototype.invertToRef = previousInvertToRef;
  2804. Matrix.LookAtLHToRef = previousLookAtLHToRef;
  2805. Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  2806. Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  2807. SIMDHelper._isEnabled = false;
  2808. };
  2809. SIMDHelper.EnableSIMD = function () {
  2810. if (window.SIMD === undefined) {
  2811. return;
  2812. }
  2813. // Replace functions
  2814. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  2815. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  2816. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  2817. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  2818. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  2819. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  2820. get: function () {
  2821. return this._data[0];
  2822. },
  2823. set: function (value) {
  2824. if (!this._data) {
  2825. this._data = new Float32Array(3);
  2826. }
  2827. this._data[0] = value;
  2828. }
  2829. });
  2830. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  2831. get: function () {
  2832. return this._data[1];
  2833. },
  2834. set: function (value) {
  2835. this._data[1] = value;
  2836. }
  2837. });
  2838. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  2839. get: function () {
  2840. return this._data[2];
  2841. },
  2842. set: function (value) {
  2843. this._data[2] = value;
  2844. }
  2845. });
  2846. SIMDHelper._isEnabled = true;
  2847. };
  2848. SIMDHelper._isEnabled = false;
  2849. return SIMDHelper;
  2850. })();
  2851. BABYLON.SIMDHelper = SIMDHelper;
  2852. if (window.SIMD !== undefined) {
  2853. SIMDHelper.EnableSIMD();
  2854. }
  2855. })(BABYLON || (BABYLON = {}));
  2856. //# sourceMappingURL=babylon.math.js.mapvar BABYLON;
  2857. (function (BABYLON) {
  2858. // Screenshots
  2859. var screenshotCanvas;
  2860. var cloneValue = function (source, destinationObject) {
  2861. if (!source)
  2862. return null;
  2863. if (source instanceof BABYLON.Mesh) {
  2864. return null;
  2865. }
  2866. if (source instanceof BABYLON.SubMesh) {
  2867. return source.clone(destinationObject);
  2868. }
  2869. else if (source.clone) {
  2870. return source.clone();
  2871. }
  2872. return null;
  2873. };
  2874. var Tools = (function () {
  2875. function Tools() {
  2876. }
  2877. Tools.GetFilename = function (path) {
  2878. var index = path.lastIndexOf("/");
  2879. if (index < 0)
  2880. return path;
  2881. return path.substring(index + 1);
  2882. };
  2883. Tools.GetDOMTextContent = function (element) {
  2884. var result = "";
  2885. var child = element.firstChild;
  2886. while (child) {
  2887. if (child.nodeType === 3) {
  2888. result += child.textContent;
  2889. }
  2890. child = child.nextSibling;
  2891. }
  2892. return result;
  2893. };
  2894. Tools.ToDegrees = function (angle) {
  2895. return angle * 180 / Math.PI;
  2896. };
  2897. Tools.ToRadians = function (angle) {
  2898. return angle * Math.PI / 180;
  2899. };
  2900. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2901. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2902. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2903. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2904. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2905. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2906. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2907. }
  2908. return {
  2909. minimum: minimum,
  2910. maximum: maximum
  2911. };
  2912. };
  2913. Tools.ExtractMinAndMax = function (positions, start, count) {
  2914. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2915. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2916. for (var index = start; index < start + count; index++) {
  2917. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2918. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2919. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2920. }
  2921. return {
  2922. minimum: minimum,
  2923. maximum: maximum
  2924. };
  2925. };
  2926. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2927. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2928. return undefined;
  2929. return Array.isArray(obj) ? obj : [obj];
  2930. };
  2931. // Misc.
  2932. Tools.GetPointerPrefix = function () {
  2933. var eventPrefix = "pointer";
  2934. // Check if hand.js is referenced or if the browser natively supports pointer events
  2935. if (!navigator.pointerEnabled) {
  2936. eventPrefix = "mouse";
  2937. }
  2938. return eventPrefix;
  2939. };
  2940. Tools.QueueNewFrame = function (func) {
  2941. if (window.requestAnimationFrame)
  2942. window.requestAnimationFrame(func);
  2943. else if (window.msRequestAnimationFrame)
  2944. window.msRequestAnimationFrame(func);
  2945. else if (window.webkitRequestAnimationFrame)
  2946. window.webkitRequestAnimationFrame(func);
  2947. else if (window.mozRequestAnimationFrame)
  2948. window.mozRequestAnimationFrame(func);
  2949. else if (window.oRequestAnimationFrame)
  2950. window.oRequestAnimationFrame(func);
  2951. else {
  2952. window.setTimeout(func, 16);
  2953. }
  2954. };
  2955. Tools.RequestFullscreen = function (element) {
  2956. if (element.requestFullscreen)
  2957. element.requestFullscreen();
  2958. else if (element.msRequestFullscreen)
  2959. element.msRequestFullscreen();
  2960. else if (element.webkitRequestFullscreen)
  2961. element.webkitRequestFullscreen();
  2962. else if (element.mozRequestFullScreen)
  2963. element.mozRequestFullScreen();
  2964. };
  2965. Tools.ExitFullscreen = function () {
  2966. if (document.exitFullscreen) {
  2967. document.exitFullscreen();
  2968. }
  2969. else if (document.mozCancelFullScreen) {
  2970. document.mozCancelFullScreen();
  2971. }
  2972. else if (document.webkitCancelFullScreen) {
  2973. document.webkitCancelFullScreen();
  2974. }
  2975. else if (document.msCancelFullScreen) {
  2976. document.msCancelFullScreen();
  2977. }
  2978. };
  2979. // External files
  2980. Tools.CleanUrl = function (url) {
  2981. url = url.replace(/#/mg, "%23");
  2982. return url;
  2983. };
  2984. Tools.LoadImage = function (url, onload, onerror, database) {
  2985. url = Tools.CleanUrl(url);
  2986. var img = new Image();
  2987. if (url.substr(0, 5) !== "data:")
  2988. img.crossOrigin = 'anonymous';
  2989. img.onload = function () {
  2990. onload(img);
  2991. };
  2992. img.onerror = function (err) {
  2993. onerror(img, err);
  2994. };
  2995. var noIndexedDB = function () {
  2996. img.src = url;
  2997. };
  2998. var loadFromIndexedDB = function () {
  2999. database.loadImageFromDB(url, img);
  3000. };
  3001. //ANY database to do!
  3002. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  3003. database.openAsync(loadFromIndexedDB, noIndexedDB);
  3004. }
  3005. else {
  3006. if (url.indexOf("file:") === -1) {
  3007. noIndexedDB();
  3008. }
  3009. else {
  3010. try {
  3011. var textureName = url.substring(5);
  3012. var blobURL;
  3013. try {
  3014. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  3015. }
  3016. catch (ex) {
  3017. // Chrome doesn't support oneTimeOnly parameter
  3018. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  3019. }
  3020. img.src = blobURL;
  3021. }
  3022. catch (e) {
  3023. Tools.Log("Error while trying to load texture: " + textureName);
  3024. img.src = null;
  3025. }
  3026. }
  3027. }
  3028. return img;
  3029. };
  3030. //ANY
  3031. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  3032. url = Tools.CleanUrl(url);
  3033. var noIndexedDB = function () {
  3034. var request = new XMLHttpRequest();
  3035. var loadUrl = Tools.BaseUrl + url;
  3036. request.open('GET', loadUrl, true);
  3037. if (useArrayBuffer) {
  3038. request.responseType = "arraybuffer";
  3039. }
  3040. request.onprogress = progressCallBack;
  3041. request.onreadystatechange = function () {
  3042. if (request.readyState === 4) {
  3043. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  3044. callback(!useArrayBuffer ? request.responseText : request.response);
  3045. }
  3046. else {
  3047. if (onError) {
  3048. onError();
  3049. }
  3050. else {
  3051. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  3052. }
  3053. }
  3054. }
  3055. };
  3056. request.send(null);
  3057. };
  3058. var loadFromIndexedDB = function () {
  3059. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  3060. };
  3061. if (url.indexOf("file:") !== -1) {
  3062. var fileName = url.substring(5);
  3063. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  3064. }
  3065. else {
  3066. // Caching all files
  3067. if (database && database.enableSceneOffline) {
  3068. database.openAsync(loadFromIndexedDB, noIndexedDB);
  3069. }
  3070. else {
  3071. noIndexedDB();
  3072. }
  3073. }
  3074. };
  3075. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  3076. var reader = new FileReader();
  3077. reader.onload = function (e) {
  3078. //target doesn't have result from ts 1.3
  3079. callback(e.target['result']);
  3080. };
  3081. reader.onprogress = progressCallback;
  3082. reader.readAsDataURL(fileToLoad);
  3083. };
  3084. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  3085. var reader = new FileReader();
  3086. reader.onerror = function (e) {
  3087. Tools.Log("Error while reading file: " + fileToLoad.name);
  3088. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  3089. };
  3090. reader.onload = function (e) {
  3091. //target doesn't have result from ts 1.3
  3092. callback(e.target['result']);
  3093. };
  3094. reader.onprogress = progressCallBack;
  3095. if (!useArrayBuffer) {
  3096. // Asynchronous read
  3097. reader.readAsText(fileToLoad);
  3098. }
  3099. else {
  3100. reader.readAsArrayBuffer(fileToLoad);
  3101. }
  3102. };
  3103. // Misc.
  3104. Tools.Clamp = function (value, min, max) {
  3105. if (min === void 0) { min = 0; }
  3106. if (max === void 0) { max = 1; }
  3107. return Math.min(max, Math.max(min, value));
  3108. };
  3109. // Returns -1 when value is a negative number and
  3110. // +1 when value is a positive number.
  3111. Tools.Sign = function (value) {
  3112. value = +value; // convert to a number
  3113. if (value === 0 || isNaN(value))
  3114. return value;
  3115. return value > 0 ? 1 : -1;
  3116. };
  3117. Tools.Format = function (value, decimals) {
  3118. if (decimals === void 0) { decimals = 2; }
  3119. return value.toFixed(decimals);
  3120. };
  3121. Tools.CheckExtends = function (v, min, max) {
  3122. if (v.x < min.x)
  3123. min.x = v.x;
  3124. if (v.y < min.y)
  3125. min.y = v.y;
  3126. if (v.z < min.z)
  3127. min.z = v.z;
  3128. if (v.x > max.x)
  3129. max.x = v.x;
  3130. if (v.y > max.y)
  3131. max.y = v.y;
  3132. if (v.z > max.z)
  3133. max.z = v.z;
  3134. };
  3135. Tools.WithinEpsilon = function (a, b, epsilon) {
  3136. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  3137. var num = a - b;
  3138. return -epsilon <= num && num <= epsilon;
  3139. };
  3140. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  3141. for (var prop in source) {
  3142. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  3143. continue;
  3144. }
  3145. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  3146. continue;
  3147. }
  3148. var sourceValue = source[prop];
  3149. var typeOfSourceValue = typeof sourceValue;
  3150. if (typeOfSourceValue === "function") {
  3151. continue;
  3152. }
  3153. if (typeOfSourceValue === "object") {
  3154. if (sourceValue instanceof Array) {
  3155. destination[prop] = [];
  3156. if (sourceValue.length > 0) {
  3157. if (typeof sourceValue[0] == "object") {
  3158. for (var index = 0; index < sourceValue.length; index++) {
  3159. var clonedValue = cloneValue(sourceValue[index], destination);
  3160. if (destination[prop].indexOf(clonedValue) === -1) {
  3161. destination[prop].push(clonedValue);
  3162. }
  3163. }
  3164. }
  3165. else {
  3166. destination[prop] = sourceValue.slice(0);
  3167. }
  3168. }
  3169. }
  3170. else {
  3171. destination[prop] = cloneValue(sourceValue, destination);
  3172. }
  3173. }
  3174. else {
  3175. destination[prop] = sourceValue;
  3176. }
  3177. }
  3178. };
  3179. Tools.IsEmpty = function (obj) {
  3180. for (var i in obj) {
  3181. return false;
  3182. }
  3183. return true;
  3184. };
  3185. Tools.RegisterTopRootEvents = function (events) {
  3186. for (var index = 0; index < events.length; index++) {
  3187. var event = events[index];
  3188. window.addEventListener(event.name, event.handler, false);
  3189. try {
  3190. if (window.parent) {
  3191. window.parent.addEventListener(event.name, event.handler, false);
  3192. }
  3193. }
  3194. catch (e) {
  3195. }
  3196. }
  3197. };
  3198. Tools.UnregisterTopRootEvents = function (events) {
  3199. for (var index = 0; index < events.length; index++) {
  3200. var event = events[index];
  3201. window.removeEventListener(event.name, event.handler);
  3202. try {
  3203. if (window.parent) {
  3204. window.parent.removeEventListener(event.name, event.handler);
  3205. }
  3206. }
  3207. catch (e) {
  3208. }
  3209. }
  3210. };
  3211. Tools.DumpFramebuffer = function (width, height, engine) {
  3212. // Read the contents of the framebuffer
  3213. var numberOfChannelsByLine = width * 4;
  3214. var halfHeight = height / 2;
  3215. //Reading datas from WebGL
  3216. var data = engine.readPixels(0, 0, width, height);
  3217. for (var i = 0; i < halfHeight; i++) {
  3218. for (var j = 0; j < numberOfChannelsByLine; j++) {
  3219. var currentCell = j + i * numberOfChannelsByLine;
  3220. var targetLine = height - i - 1;
  3221. var targetCell = j + targetLine * numberOfChannelsByLine;
  3222. var temp = data[currentCell];
  3223. data[currentCell] = data[targetCell];
  3224. data[targetCell] = temp;
  3225. }
  3226. }
  3227. // Create a 2D canvas to store the result
  3228. if (!screenshotCanvas) {
  3229. screenshotCanvas = document.createElement('canvas');
  3230. }
  3231. screenshotCanvas.width = width;
  3232. screenshotCanvas.height = height;
  3233. var context = screenshotCanvas.getContext('2d');
  3234. // Copy the pixels to a 2D canvas
  3235. var imageData = context.createImageData(width, height);
  3236. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  3237. var castData = imageData.data;
  3238. castData.set(data);
  3239. context.putImageData(imageData, 0, 0);
  3240. var base64Image = screenshotCanvas.toDataURL();
  3241. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  3242. if (("download" in document.createElement("a"))) {
  3243. var a = window.document.createElement("a");
  3244. a.href = base64Image;
  3245. var date = new Date();
  3246. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  3247. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  3248. window.document.body.appendChild(a);
  3249. a.addEventListener("click", function () {
  3250. a.parentElement.removeChild(a);
  3251. });
  3252. a.click();
  3253. }
  3254. else {
  3255. var newWindow = window.open("");
  3256. var img = newWindow.document.createElement("img");
  3257. img.src = base64Image;
  3258. newWindow.document.body.appendChild(img);
  3259. }
  3260. };
  3261. Tools.CreateScreenshot = function (engine, camera, size) {
  3262. var width;
  3263. var height;
  3264. var scene = camera.getScene();
  3265. var previousCamera = null;
  3266. if (scene.activeCamera !== camera) {
  3267. previousCamera = scene.activeCamera;
  3268. scene.activeCamera = camera;
  3269. }
  3270. //If a precision value is specified
  3271. if (size.precision) {
  3272. width = Math.round(engine.getRenderWidth() * size.precision);
  3273. height = Math.round(width / engine.getAspectRatio(camera));
  3274. size = { width: width, height: height };
  3275. }
  3276. else if (size.width && size.height) {
  3277. width = size.width;
  3278. height = size.height;
  3279. }
  3280. else if (size.width && !size.height) {
  3281. width = size.width;
  3282. height = Math.round(width / engine.getAspectRatio(camera));
  3283. size = { width: width, height: height };
  3284. }
  3285. else if (size.height && !size.width) {
  3286. height = size.height;
  3287. width = Math.round(height * engine.getAspectRatio(camera));
  3288. size = { width: width, height: height };
  3289. }
  3290. else if (!isNaN(size)) {
  3291. height = size;
  3292. width = size;
  3293. }
  3294. else {
  3295. Tools.Error("Invalid 'size' parameter !");
  3296. return;
  3297. }
  3298. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  3299. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  3300. texture.renderList = scene.meshes;
  3301. texture.onAfterRender = function () {
  3302. Tools.DumpFramebuffer(width, height, engine);
  3303. };
  3304. scene.incrementRenderId();
  3305. texture.render(true);
  3306. texture.dispose();
  3307. if (previousCamera) {
  3308. scene.activeCamera = previousCamera;
  3309. }
  3310. };
  3311. // XHR response validator for local file scenario
  3312. Tools.ValidateXHRData = function (xhr, dataType) {
  3313. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  3314. if (dataType === void 0) { dataType = 7; }
  3315. try {
  3316. if (dataType & 1) {
  3317. if (xhr.responseText && xhr.responseText.length > 0) {
  3318. return true;
  3319. }
  3320. else if (dataType === 1) {
  3321. return false;
  3322. }
  3323. }
  3324. if (dataType & 2) {
  3325. // Check header width and height since there is no "TGA" magic number
  3326. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  3327. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  3328. return true;
  3329. }
  3330. else if (dataType === 2) {
  3331. return false;
  3332. }
  3333. }
  3334. if (dataType & 4) {
  3335. // Check for the "DDS" magic number
  3336. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  3337. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  3338. return true;
  3339. }
  3340. else {
  3341. return false;
  3342. }
  3343. }
  3344. }
  3345. catch (e) {
  3346. }
  3347. return false;
  3348. };
  3349. Object.defineProperty(Tools, "NoneLogLevel", {
  3350. get: function () {
  3351. return Tools._NoneLogLevel;
  3352. },
  3353. enumerable: true,
  3354. configurable: true
  3355. });
  3356. Object.defineProperty(Tools, "MessageLogLevel", {
  3357. get: function () {
  3358. return Tools._MessageLogLevel;
  3359. },
  3360. enumerable: true,
  3361. configurable: true
  3362. });
  3363. Object.defineProperty(Tools, "WarningLogLevel", {
  3364. get: function () {
  3365. return Tools._WarningLogLevel;
  3366. },
  3367. enumerable: true,
  3368. configurable: true
  3369. });
  3370. Object.defineProperty(Tools, "ErrorLogLevel", {
  3371. get: function () {
  3372. return Tools._ErrorLogLevel;
  3373. },
  3374. enumerable: true,
  3375. configurable: true
  3376. });
  3377. Object.defineProperty(Tools, "AllLogLevel", {
  3378. get: function () {
  3379. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  3380. },
  3381. enumerable: true,
  3382. configurable: true
  3383. });
  3384. Tools._AddLogEntry = function (entry) {
  3385. Tools._LogCache = entry + Tools._LogCache;
  3386. if (Tools.OnNewCacheEntry) {
  3387. Tools.OnNewCacheEntry(entry);
  3388. }
  3389. };
  3390. Tools._FormatMessage = function (message) {
  3391. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  3392. var date = new Date();
  3393. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  3394. };
  3395. Tools._LogDisabled = function (message) {
  3396. // nothing to do
  3397. };
  3398. Tools._LogEnabled = function (message) {
  3399. var formattedMessage = Tools._FormatMessage(message);
  3400. console.log("BJS - " + formattedMessage);
  3401. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  3402. Tools._AddLogEntry(entry);
  3403. };
  3404. Tools._WarnDisabled = function (message) {
  3405. // nothing to do
  3406. };
  3407. Tools._WarnEnabled = function (message) {
  3408. var formattedMessage = Tools._FormatMessage(message);
  3409. console.warn("BJS - " + formattedMessage);
  3410. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  3411. Tools._AddLogEntry(entry);
  3412. };
  3413. Tools._ErrorDisabled = function (message) {
  3414. // nothing to do
  3415. };
  3416. Tools._ErrorEnabled = function (message) {
  3417. var formattedMessage = Tools._FormatMessage(message);
  3418. console.error("BJS - " + formattedMessage);
  3419. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  3420. Tools._AddLogEntry(entry);
  3421. };
  3422. Object.defineProperty(Tools, "LogCache", {
  3423. get: function () {
  3424. return Tools._LogCache;
  3425. },
  3426. enumerable: true,
  3427. configurable: true
  3428. });
  3429. Object.defineProperty(Tools, "LogLevels", {
  3430. set: function (level) {
  3431. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  3432. Tools.Log = Tools._LogEnabled;
  3433. }
  3434. else {
  3435. Tools.Log = Tools._LogDisabled;
  3436. }
  3437. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  3438. Tools.Warn = Tools._WarnEnabled;
  3439. }
  3440. else {
  3441. Tools.Warn = Tools._WarnDisabled;
  3442. }
  3443. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  3444. Tools.Error = Tools._ErrorEnabled;
  3445. }
  3446. else {
  3447. Tools.Error = Tools._ErrorDisabled;
  3448. }
  3449. },
  3450. enumerable: true,
  3451. configurable: true
  3452. });
  3453. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  3454. get: function () {
  3455. return Tools._PerformanceNoneLogLevel;
  3456. },
  3457. enumerable: true,
  3458. configurable: true
  3459. });
  3460. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  3461. get: function () {
  3462. return Tools._PerformanceUserMarkLogLevel;
  3463. },
  3464. enumerable: true,
  3465. configurable: true
  3466. });
  3467. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  3468. get: function () {
  3469. return Tools._PerformanceConsoleLogLevel;
  3470. },
  3471. enumerable: true,
  3472. configurable: true
  3473. });
  3474. Object.defineProperty(Tools, "PerformanceLogLevel", {
  3475. set: function (level) {
  3476. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  3477. Tools.StartPerformanceCounter = Tools._StartUserMark;
  3478. Tools.EndPerformanceCounter = Tools._EndUserMark;
  3479. return;
  3480. }
  3481. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  3482. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  3483. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  3484. return;
  3485. }
  3486. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3487. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3488. },
  3489. enumerable: true,
  3490. configurable: true
  3491. });
  3492. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  3493. };
  3494. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  3495. };
  3496. Tools._StartUserMark = function (counterName, condition) {
  3497. if (condition === void 0) { condition = true; }
  3498. if (!condition || !Tools._performance.mark) {
  3499. return;
  3500. }
  3501. Tools._performance.mark(counterName + "-Begin");
  3502. };
  3503. Tools._EndUserMark = function (counterName, condition) {
  3504. if (condition === void 0) { condition = true; }
  3505. if (!condition || !Tools._performance.mark) {
  3506. return;
  3507. }
  3508. Tools._performance.mark(counterName + "-End");
  3509. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  3510. };
  3511. Tools._StartPerformanceConsole = function (counterName, condition) {
  3512. if (condition === void 0) { condition = true; }
  3513. if (!condition) {
  3514. return;
  3515. }
  3516. Tools._StartUserMark(counterName, condition);
  3517. if (console.time) {
  3518. console.time(counterName);
  3519. }
  3520. };
  3521. Tools._EndPerformanceConsole = function (counterName, condition) {
  3522. if (condition === void 0) { condition = true; }
  3523. if (!condition) {
  3524. return;
  3525. }
  3526. Tools._EndUserMark(counterName, condition);
  3527. if (console.time) {
  3528. console.timeEnd(counterName);
  3529. }
  3530. };
  3531. Object.defineProperty(Tools, "Now", {
  3532. get: function () {
  3533. if (window.performance && window.performance.now) {
  3534. return window.performance.now();
  3535. }
  3536. return new Date().getTime();
  3537. },
  3538. enumerable: true,
  3539. configurable: true
  3540. });
  3541. // Deprecated
  3542. Tools.GetFps = function () {
  3543. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  3544. return 0;
  3545. };
  3546. Tools.BaseUrl = "";
  3547. Tools.GetExponantOfTwo = function (value, max) {
  3548. var count = 1;
  3549. do {
  3550. count *= 2;
  3551. } while (count < value);
  3552. if (count > max)
  3553. count = max;
  3554. return count;
  3555. };
  3556. // Logs
  3557. Tools._NoneLogLevel = 0;
  3558. Tools._MessageLogLevel = 1;
  3559. Tools._WarningLogLevel = 2;
  3560. Tools._ErrorLogLevel = 4;
  3561. Tools._LogCache = "";
  3562. Tools.Log = Tools._LogEnabled;
  3563. Tools.Warn = Tools._WarnEnabled;
  3564. Tools.Error = Tools._ErrorEnabled;
  3565. // Performances
  3566. Tools._PerformanceNoneLogLevel = 0;
  3567. Tools._PerformanceUserMarkLogLevel = 1;
  3568. Tools._PerformanceConsoleLogLevel = 2;
  3569. Tools._performance = window.performance;
  3570. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3571. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3572. return Tools;
  3573. })();
  3574. BABYLON.Tools = Tools;
  3575. /**
  3576. * An implementation of a loop for asynchronous functions.
  3577. */
  3578. var AsyncLoop = (function () {
  3579. /**
  3580. * Constroctor.
  3581. * @param iterations the number of iterations.
  3582. * @param _fn the function to run each iteration
  3583. * @param _successCallback the callback that will be called upon succesful execution
  3584. * @param offset starting offset.
  3585. */
  3586. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3587. if (offset === void 0) { offset = 0; }
  3588. this.iterations = iterations;
  3589. this._fn = _fn;
  3590. this._successCallback = _successCallback;
  3591. this.index = offset - 1;
  3592. this._done = false;
  3593. }
  3594. /**
  3595. * Execute the next iteration. Must be called after the last iteration was finished.
  3596. */
  3597. AsyncLoop.prototype.executeNext = function () {
  3598. if (!this._done) {
  3599. if (this.index + 1 < this.iterations) {
  3600. ++this.index;
  3601. this._fn(this);
  3602. }
  3603. else {
  3604. this.breakLoop();
  3605. }
  3606. }
  3607. };
  3608. /**
  3609. * Break the loop and run the success callback.
  3610. */
  3611. AsyncLoop.prototype.breakLoop = function () {
  3612. this._done = true;
  3613. this._successCallback();
  3614. };
  3615. /**
  3616. * Helper function
  3617. */
  3618. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3619. if (offset === void 0) { offset = 0; }
  3620. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3621. loop.executeNext();
  3622. return loop;
  3623. };
  3624. /**
  3625. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3626. * @param iterations total number of iterations
  3627. * @param syncedIterations number of synchronous iterations in each async iteration.
  3628. * @param fn the function to call each iteration.
  3629. * @param callback a success call back that will be called when iterating stops.
  3630. * @param breakFunction a break condition (optional)
  3631. * @param timeout timeout settings for the setTimeout function. default - 0.
  3632. * @constructor
  3633. */
  3634. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3635. if (timeout === void 0) { timeout = 0; }
  3636. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3637. if (breakFunction && breakFunction())
  3638. loop.breakLoop();
  3639. else {
  3640. setTimeout(function () {
  3641. for (var i = 0; i < syncedIterations; ++i) {
  3642. var iteration = (loop.index * syncedIterations) + i;
  3643. if (iteration >= iterations)
  3644. break;
  3645. fn(iteration);
  3646. if (breakFunction && breakFunction()) {
  3647. loop.breakLoop();
  3648. break;
  3649. }
  3650. }
  3651. loop.executeNext();
  3652. }, timeout);
  3653. }
  3654. }, callback);
  3655. };
  3656. return AsyncLoop;
  3657. })();
  3658. BABYLON.AsyncLoop = AsyncLoop;
  3659. })(BABYLON || (BABYLON = {}));
  3660. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3661. (function (BABYLON) {
  3662. var _DepthCullingState = (function () {
  3663. function _DepthCullingState() {
  3664. this._isDepthTestDirty = false;
  3665. this._isDepthMaskDirty = false;
  3666. this._isDepthFuncDirty = false;
  3667. this._isCullFaceDirty = false;
  3668. this._isCullDirty = false;
  3669. this._isZOffsetDirty = false;
  3670. }
  3671. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3672. get: function () {
  3673. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  3674. },
  3675. enumerable: true,
  3676. configurable: true
  3677. });
  3678. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  3679. get: function () {
  3680. return this._zOffset;
  3681. },
  3682. set: function (value) {
  3683. if (this._zOffset === value) {
  3684. return;
  3685. }
  3686. this._zOffset = value;
  3687. this._isZOffsetDirty = true;
  3688. },
  3689. enumerable: true,
  3690. configurable: true
  3691. });
  3692. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3693. get: function () {
  3694. return this._cullFace;
  3695. },
  3696. set: function (value) {
  3697. if (this._cullFace === value) {
  3698. return;
  3699. }
  3700. this._cullFace = value;
  3701. this._isCullFaceDirty = true;
  3702. },
  3703. enumerable: true,
  3704. configurable: true
  3705. });
  3706. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3707. get: function () {
  3708. return this._cull;
  3709. },
  3710. set: function (value) {
  3711. if (this._cull === value) {
  3712. return;
  3713. }
  3714. this._cull = value;
  3715. this._isCullDirty = true;
  3716. },
  3717. enumerable: true,
  3718. configurable: true
  3719. });
  3720. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3721. get: function () {
  3722. return this._depthFunc;
  3723. },
  3724. set: function (value) {
  3725. if (this._depthFunc === value) {
  3726. return;
  3727. }
  3728. this._depthFunc = value;
  3729. this._isDepthFuncDirty = true;
  3730. },
  3731. enumerable: true,
  3732. configurable: true
  3733. });
  3734. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3735. get: function () {
  3736. return this._depthMask;
  3737. },
  3738. set: function (value) {
  3739. if (this._depthMask === value) {
  3740. return;
  3741. }
  3742. this._depthMask = value;
  3743. this._isDepthMaskDirty = true;
  3744. },
  3745. enumerable: true,
  3746. configurable: true
  3747. });
  3748. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3749. get: function () {
  3750. return this._depthTest;
  3751. },
  3752. set: function (value) {
  3753. if (this._depthTest === value) {
  3754. return;
  3755. }
  3756. this._depthTest = value;
  3757. this._isDepthTestDirty = true;
  3758. },
  3759. enumerable: true,
  3760. configurable: true
  3761. });
  3762. _DepthCullingState.prototype.reset = function () {
  3763. this._depthMask = true;
  3764. this._depthTest = true;
  3765. this._depthFunc = null;
  3766. this._cull = null;
  3767. this._cullFace = null;
  3768. this._zOffset = 0;
  3769. this._isDepthTestDirty = true;
  3770. this._isDepthMaskDirty = true;
  3771. this._isDepthFuncDirty = false;
  3772. this._isCullFaceDirty = false;
  3773. this._isCullDirty = false;
  3774. this._isZOffsetDirty = false;
  3775. };
  3776. _DepthCullingState.prototype.apply = function (gl) {
  3777. if (!this.isDirty) {
  3778. return;
  3779. }
  3780. // Cull
  3781. if (this._isCullDirty) {
  3782. if (this.cull) {
  3783. gl.enable(gl.CULL_FACE);
  3784. }
  3785. else {
  3786. gl.disable(gl.CULL_FACE);
  3787. }
  3788. this._isCullDirty = false;
  3789. }
  3790. // Cull face
  3791. if (this._isCullFaceDirty) {
  3792. gl.cullFace(this.cullFace);
  3793. this._isCullFaceDirty = false;
  3794. }
  3795. // Depth mask
  3796. if (this._isDepthMaskDirty) {
  3797. gl.depthMask(this.depthMask);
  3798. this._isDepthMaskDirty = false;
  3799. }
  3800. // Depth test
  3801. if (this._isDepthTestDirty) {
  3802. if (this.depthTest) {
  3803. gl.enable(gl.DEPTH_TEST);
  3804. }
  3805. else {
  3806. gl.disable(gl.DEPTH_TEST);
  3807. }
  3808. this._isDepthTestDirty = false;
  3809. }
  3810. // Depth func
  3811. if (this._isDepthFuncDirty) {
  3812. gl.depthFunc(this.depthFunc);
  3813. this._isDepthFuncDirty = false;
  3814. }
  3815. // zOffset
  3816. if (this._isZOffsetDirty) {
  3817. if (this.zOffset) {
  3818. gl.enable(gl.POLYGON_OFFSET_FILL);
  3819. gl.polygonOffset(this.zOffset, 0);
  3820. }
  3821. else {
  3822. gl.disable(gl.POLYGON_OFFSET_FILL);
  3823. }
  3824. this._isZOffsetDirty = false;
  3825. }
  3826. };
  3827. return _DepthCullingState;
  3828. })();
  3829. BABYLON._DepthCullingState = _DepthCullingState;
  3830. var _AlphaState = (function () {
  3831. function _AlphaState() {
  3832. this._isAlphaBlendDirty = false;
  3833. this._isBlendFunctionParametersDirty = false;
  3834. this._alphaBlend = false;
  3835. this._blendFunctionParameters = new Array(4);
  3836. }
  3837. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3838. get: function () {
  3839. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3840. },
  3841. enumerable: true,
  3842. configurable: true
  3843. });
  3844. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3845. get: function () {
  3846. return this._alphaBlend;
  3847. },
  3848. set: function (value) {
  3849. if (this._alphaBlend === value) {
  3850. return;
  3851. }
  3852. this._alphaBlend = value;
  3853. this._isAlphaBlendDirty = true;
  3854. },
  3855. enumerable: true,
  3856. configurable: true
  3857. });
  3858. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3859. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3860. return;
  3861. }
  3862. this._blendFunctionParameters[0] = value0;
  3863. this._blendFunctionParameters[1] = value1;
  3864. this._blendFunctionParameters[2] = value2;
  3865. this._blendFunctionParameters[3] = value3;
  3866. this._isBlendFunctionParametersDirty = true;
  3867. };
  3868. _AlphaState.prototype.reset = function () {
  3869. this._alphaBlend = false;
  3870. this._blendFunctionParameters[0] = null;
  3871. this._blendFunctionParameters[1] = null;
  3872. this._blendFunctionParameters[2] = null;
  3873. this._blendFunctionParameters[3] = null;
  3874. this._isAlphaBlendDirty = true;
  3875. this._isBlendFunctionParametersDirty = false;
  3876. };
  3877. _AlphaState.prototype.apply = function (gl) {
  3878. if (!this.isDirty) {
  3879. return;
  3880. }
  3881. // Alpha blend
  3882. if (this._isAlphaBlendDirty) {
  3883. if (this._alphaBlend) {
  3884. gl.enable(gl.BLEND);
  3885. }
  3886. else {
  3887. gl.disable(gl.BLEND);
  3888. }
  3889. this._isAlphaBlendDirty = false;
  3890. }
  3891. // Alpha function
  3892. if (this._isBlendFunctionParametersDirty) {
  3893. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3894. this._isBlendFunctionParametersDirty = false;
  3895. }
  3896. };
  3897. return _AlphaState;
  3898. })();
  3899. BABYLON._AlphaState = _AlphaState;
  3900. var compileShader = function (gl, source, type, defines) {
  3901. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3902. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3903. gl.compileShader(shader);
  3904. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3905. throw new Error(gl.getShaderInfoLog(shader));
  3906. }
  3907. return shader;
  3908. };
  3909. var getWebGLTextureType = function (gl, type) {
  3910. var textureType = gl.UNSIGNED_BYTE;
  3911. if (type === Engine.TEXTURETYPE_FLOAT)
  3912. textureType = gl.FLOAT;
  3913. return textureType;
  3914. };
  3915. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3916. var magFilter = gl.NEAREST;
  3917. var minFilter = gl.NEAREST;
  3918. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3919. magFilter = gl.LINEAR;
  3920. if (generateMipMaps) {
  3921. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3922. }
  3923. else {
  3924. minFilter = gl.LINEAR;
  3925. }
  3926. }
  3927. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3928. magFilter = gl.LINEAR;
  3929. if (generateMipMaps) {
  3930. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3931. }
  3932. else {
  3933. minFilter = gl.LINEAR;
  3934. }
  3935. }
  3936. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3937. magFilter = gl.NEAREST;
  3938. if (generateMipMaps) {
  3939. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3940. }
  3941. else {
  3942. minFilter = gl.NEAREST;
  3943. }
  3944. }
  3945. return {
  3946. min: minFilter,
  3947. mag: magFilter
  3948. };
  3949. };
  3950. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3951. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3952. var engine = scene.getEngine();
  3953. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3954. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3955. gl.bindTexture(gl.TEXTURE_2D, texture);
  3956. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3957. processFunction(potWidth, potHeight);
  3958. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3959. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3960. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3961. if (!noMipmap && !isCompressed) {
  3962. gl.generateMipmap(gl.TEXTURE_2D);
  3963. }
  3964. gl.bindTexture(gl.TEXTURE_2D, null);
  3965. engine._activeTexturesCache = [];
  3966. texture._baseWidth = width;
  3967. texture._baseHeight = height;
  3968. texture._width = potWidth;
  3969. texture._height = potHeight;
  3970. texture.isReady = true;
  3971. texture.samplingMode = samplingMode;
  3972. scene._removePendingData(texture);
  3973. };
  3974. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3975. var onload = function () {
  3976. loadedImages[index] = img;
  3977. loadedImages._internalCount++;
  3978. scene._removePendingData(img);
  3979. if (loadedImages._internalCount === 6) {
  3980. onfinish(loadedImages);
  3981. }
  3982. };
  3983. var onerror = function () {
  3984. scene._removePendingData(img);
  3985. };
  3986. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3987. scene._addPendingData(img);
  3988. };
  3989. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3990. var loadedImages = [];
  3991. loadedImages._internalCount = 0;
  3992. for (var index = 0; index < 6; index++) {
  3993. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3994. }
  3995. };
  3996. var EngineCapabilities = (function () {
  3997. function EngineCapabilities() {
  3998. }
  3999. return EngineCapabilities;
  4000. })();
  4001. BABYLON.EngineCapabilities = EngineCapabilities;
  4002. /**
  4003. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  4004. */
  4005. var Engine = (function () {
  4006. /**
  4007. * @constructor
  4008. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  4009. * @param {boolean} [antialias] - enable antialias
  4010. * @param options - further options to be sent to the getContext function
  4011. */
  4012. function Engine(canvas, antialias, options) {
  4013. var _this = this;
  4014. // Public members
  4015. this.isFullscreen = false;
  4016. this.isPointerLock = false;
  4017. this.cullBackFaces = true;
  4018. this.renderEvenInBackground = true;
  4019. this.scenes = new Array();
  4020. this._windowIsBackground = false;
  4021. this._loadingDivBackgroundColor = "black";
  4022. this._drawCalls = 0;
  4023. this._renderingQueueLaunched = false;
  4024. this._activeRenderLoops = [];
  4025. // FPS
  4026. this.fpsRange = 60;
  4027. this.previousFramesDuration = [];
  4028. this.fps = 60;
  4029. this.deltaTime = 0;
  4030. // States
  4031. this._depthCullingState = new _DepthCullingState();
  4032. this._alphaState = new _AlphaState();
  4033. this._alphaMode = Engine.ALPHA_DISABLE;
  4034. // Cache
  4035. this._loadedTexturesCache = new Array();
  4036. this._activeTexturesCache = new Array();
  4037. this._compiledEffects = {};
  4038. this._uintIndicesCurrentlySet = false;
  4039. this._renderingCanvas = canvas;
  4040. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4041. options = options || {};
  4042. options.antialias = antialias;
  4043. try {
  4044. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  4045. }
  4046. catch (e) {
  4047. throw new Error("WebGL not supported");
  4048. }
  4049. if (!this._gl) {
  4050. throw new Error("WebGL not supported");
  4051. }
  4052. this._onBlur = function () {
  4053. _this._windowIsBackground = true;
  4054. };
  4055. this._onFocus = function () {
  4056. _this._windowIsBackground = false;
  4057. };
  4058. window.addEventListener("blur", this._onBlur);
  4059. window.addEventListener("focus", this._onFocus);
  4060. // Viewport
  4061. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  4062. this.resize();
  4063. // Caps
  4064. this._caps = new EngineCapabilities();
  4065. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  4066. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  4067. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  4068. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  4069. // Infos
  4070. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  4071. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  4072. if (rendererInfo != null) {
  4073. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  4074. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  4075. }
  4076. if (!this._glVendor) {
  4077. this._glVendor = "Unknown vendor";
  4078. }
  4079. if (!this._glRenderer) {
  4080. this._glRenderer = "Unknown renderer";
  4081. }
  4082. // Extensions
  4083. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  4084. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  4085. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  4086. 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');
  4087. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  4088. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  4089. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  4090. this._caps.highPrecisionShaderSupported = true;
  4091. if (this._gl.getShaderPrecisionFormat) {
  4092. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  4093. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  4094. }
  4095. // Depth buffer
  4096. this.setDepthBuffer(true);
  4097. this.setDepthFunctionToLessOrEqual();
  4098. this.setDepthWrite(true);
  4099. // Fullscreen
  4100. this._onFullscreenChange = function () {
  4101. if (document.fullscreen !== undefined) {
  4102. _this.isFullscreen = document.fullscreen;
  4103. }
  4104. else if (document.mozFullScreen !== undefined) {
  4105. _this.isFullscreen = document.mozFullScreen;
  4106. }
  4107. else if (document.webkitIsFullScreen !== undefined) {
  4108. _this.isFullscreen = document.webkitIsFullScreen;
  4109. }
  4110. else if (document.msIsFullScreen !== undefined) {
  4111. _this.isFullscreen = document.msIsFullScreen;
  4112. }
  4113. // Pointer lock
  4114. if (_this.isFullscreen && _this._pointerLockRequested) {
  4115. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  4116. if (canvas.requestPointerLock) {
  4117. canvas.requestPointerLock();
  4118. }
  4119. }
  4120. };
  4121. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  4122. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  4123. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  4124. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  4125. // Pointer lock
  4126. this._onPointerLockChange = function () {
  4127. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  4128. };
  4129. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  4130. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  4131. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  4132. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  4133. if (!Engine.audioEngine) {
  4134. Engine.audioEngine = new BABYLON.AudioEngine();
  4135. }
  4136. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  4137. }
  4138. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  4139. get: function () {
  4140. return Engine._ALPHA_DISABLE;
  4141. },
  4142. enumerable: true,
  4143. configurable: true
  4144. });
  4145. Object.defineProperty(Engine, "ALPHA_ADD", {
  4146. get: function () {
  4147. return Engine._ALPHA_ADD;
  4148. },
  4149. enumerable: true,
  4150. configurable: true
  4151. });
  4152. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  4153. get: function () {
  4154. return Engine._ALPHA_COMBINE;
  4155. },
  4156. enumerable: true,
  4157. configurable: true
  4158. });
  4159. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  4160. get: function () {
  4161. return Engine._DELAYLOADSTATE_NONE;
  4162. },
  4163. enumerable: true,
  4164. configurable: true
  4165. });
  4166. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  4167. get: function () {
  4168. return Engine._DELAYLOADSTATE_LOADED;
  4169. },
  4170. enumerable: true,
  4171. configurable: true
  4172. });
  4173. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  4174. get: function () {
  4175. return Engine._DELAYLOADSTATE_LOADING;
  4176. },
  4177. enumerable: true,
  4178. configurable: true
  4179. });
  4180. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  4181. get: function () {
  4182. return Engine._DELAYLOADSTATE_NOTLOADED;
  4183. },
  4184. enumerable: true,
  4185. configurable: true
  4186. });
  4187. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  4188. get: function () {
  4189. return Engine._TEXTUREFORMAT_ALPHA;
  4190. },
  4191. enumerable: true,
  4192. configurable: true
  4193. });
  4194. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  4195. get: function () {
  4196. return Engine._TEXTUREFORMAT_LUMINANCE;
  4197. },
  4198. enumerable: true,
  4199. configurable: true
  4200. });
  4201. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  4202. get: function () {
  4203. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  4204. },
  4205. enumerable: true,
  4206. configurable: true
  4207. });
  4208. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  4209. get: function () {
  4210. return Engine._TEXTUREFORMAT_RGB;
  4211. },
  4212. enumerable: true,
  4213. configurable: true
  4214. });
  4215. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  4216. get: function () {
  4217. return Engine._TEXTUREFORMAT_RGBA;
  4218. },
  4219. enumerable: true,
  4220. configurable: true
  4221. });
  4222. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  4223. get: function () {
  4224. return Engine._TEXTURETYPE_UNSIGNED_INT;
  4225. },
  4226. enumerable: true,
  4227. configurable: true
  4228. });
  4229. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  4230. get: function () {
  4231. return Engine._TEXTURETYPE_FLOAT;
  4232. },
  4233. enumerable: true,
  4234. configurable: true
  4235. });
  4236. Object.defineProperty(Engine, "Version", {
  4237. get: function () {
  4238. return "2.1.0 alpha";
  4239. },
  4240. enumerable: true,
  4241. configurable: true
  4242. });
  4243. Engine.prototype._prepareWorkingCanvas = function () {
  4244. if (this._workingCanvas) {
  4245. return;
  4246. }
  4247. this._workingCanvas = document.createElement("canvas");
  4248. this._workingContext = this._workingCanvas.getContext("2d");
  4249. };
  4250. Engine.prototype.getGlInfo = function () {
  4251. return {
  4252. vendor: this._glVendor,
  4253. renderer: this._glRenderer,
  4254. version: this._glVersion
  4255. };
  4256. };
  4257. Engine.prototype.getAspectRatio = function (camera) {
  4258. var viewport = camera.viewport;
  4259. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  4260. };
  4261. Engine.prototype.getRenderWidth = function () {
  4262. if (this._currentRenderTarget) {
  4263. return this._currentRenderTarget._width;
  4264. }
  4265. return this._renderingCanvas.width;
  4266. };
  4267. Engine.prototype.getRenderHeight = function () {
  4268. if (this._currentRenderTarget) {
  4269. return this._currentRenderTarget._height;
  4270. }
  4271. return this._renderingCanvas.height;
  4272. };
  4273. Engine.prototype.getRenderingCanvas = function () {
  4274. return this._renderingCanvas;
  4275. };
  4276. Engine.prototype.getRenderingCanvasClientRect = function () {
  4277. return this._renderingCanvas.getBoundingClientRect();
  4278. };
  4279. Engine.prototype.setHardwareScalingLevel = function (level) {
  4280. this._hardwareScalingLevel = level;
  4281. this.resize();
  4282. };
  4283. Engine.prototype.getHardwareScalingLevel = function () {
  4284. return this._hardwareScalingLevel;
  4285. };
  4286. Engine.prototype.getLoadedTexturesCache = function () {
  4287. return this._loadedTexturesCache;
  4288. };
  4289. Engine.prototype.getCaps = function () {
  4290. return this._caps;
  4291. };
  4292. Object.defineProperty(Engine.prototype, "drawCalls", {
  4293. get: function () {
  4294. return this._drawCalls;
  4295. },
  4296. enumerable: true,
  4297. configurable: true
  4298. });
  4299. // Methods
  4300. Engine.prototype.resetDrawCalls = function () {
  4301. this._drawCalls = 0;
  4302. };
  4303. Engine.prototype.setDepthFunctionToGreater = function () {
  4304. this._depthCullingState.depthFunc = this._gl.GREATER;
  4305. };
  4306. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  4307. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  4308. };
  4309. Engine.prototype.setDepthFunctionToLess = function () {
  4310. this._depthCullingState.depthFunc = this._gl.LESS;
  4311. };
  4312. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  4313. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  4314. };
  4315. /**
  4316. * stop executing a render loop function and remove it from the execution array
  4317. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  4318. */
  4319. Engine.prototype.stopRenderLoop = function (renderFunction) {
  4320. if (!renderFunction) {
  4321. this._activeRenderLoops = [];
  4322. return;
  4323. }
  4324. var index = this._activeRenderLoops.indexOf(renderFunction);
  4325. if (index >= 0) {
  4326. this._activeRenderLoops.splice(index, 1);
  4327. }
  4328. };
  4329. Engine.prototype._renderLoop = function () {
  4330. var _this = this;
  4331. var shouldRender = true;
  4332. if (!this.renderEvenInBackground && this._windowIsBackground) {
  4333. shouldRender = false;
  4334. }
  4335. if (shouldRender) {
  4336. // Start new frame
  4337. this.beginFrame();
  4338. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  4339. var renderFunction = this._activeRenderLoops[index];
  4340. renderFunction();
  4341. }
  4342. // Present
  4343. this.endFrame();
  4344. }
  4345. if (this._activeRenderLoops.length > 0) {
  4346. // Register new frame
  4347. BABYLON.Tools.QueueNewFrame(function () {
  4348. _this._renderLoop();
  4349. });
  4350. }
  4351. else {
  4352. this._renderingQueueLaunched = false;
  4353. }
  4354. };
  4355. /**
  4356. * Register and execute a render loop. The engine can have more than one render function.
  4357. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  4358. * @example
  4359. * engine.runRenderLoop(function () {
  4360. * scene.render()
  4361. * })
  4362. */
  4363. Engine.prototype.runRenderLoop = function (renderFunction) {
  4364. var _this = this;
  4365. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  4366. return;
  4367. }
  4368. this._activeRenderLoops.push(renderFunction);
  4369. if (!this._renderingQueueLaunched) {
  4370. this._renderingQueueLaunched = true;
  4371. BABYLON.Tools.QueueNewFrame(function () {
  4372. _this._renderLoop();
  4373. });
  4374. }
  4375. };
  4376. /**
  4377. * Toggle full screen mode.
  4378. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  4379. */
  4380. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  4381. if (this.isFullscreen) {
  4382. BABYLON.Tools.ExitFullscreen();
  4383. }
  4384. else {
  4385. this._pointerLockRequested = requestPointerLock;
  4386. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  4387. }
  4388. };
  4389. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  4390. this.applyStates();
  4391. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  4392. if (this._depthCullingState.depthMask) {
  4393. this._gl.clearDepth(1.0);
  4394. }
  4395. var mode = 0;
  4396. if (backBuffer)
  4397. mode |= this._gl.COLOR_BUFFER_BIT;
  4398. if (depthStencil && this._depthCullingState.depthMask)
  4399. mode |= this._gl.DEPTH_BUFFER_BIT;
  4400. this._gl.clear(mode);
  4401. };
  4402. /**
  4403. * Set the WebGL's viewport
  4404. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  4405. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  4406. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  4407. */
  4408. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  4409. var width = requiredWidth || this._renderingCanvas.width;
  4410. var height = requiredHeight || this._renderingCanvas.height;
  4411. var x = viewport.x || 0;
  4412. var y = viewport.y || 0;
  4413. this._cachedViewport = viewport;
  4414. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  4415. };
  4416. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  4417. this._cachedViewport = null;
  4418. this._gl.viewport(x, y, width, height);
  4419. };
  4420. Engine.prototype.beginFrame = function () {
  4421. this._measureFps();
  4422. };
  4423. Engine.prototype.endFrame = function () {
  4424. //this.flushFramebuffer();
  4425. };
  4426. /**
  4427. * resize the view according to the canvas' size.
  4428. * @example
  4429. * window.addEventListener("resize", function () {
  4430. * engine.resize();
  4431. * });
  4432. */
  4433. Engine.prototype.resize = function () {
  4434. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  4435. };
  4436. /**
  4437. * force a specific size of the canvas
  4438. * @param {number} width - the new canvas' width
  4439. * @param {number} height - the new canvas' height
  4440. */
  4441. Engine.prototype.setSize = function (width, height) {
  4442. this._renderingCanvas.width = width;
  4443. this._renderingCanvas.height = height;
  4444. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4445. };
  4446. Engine.prototype.bindFramebuffer = function (texture) {
  4447. this._currentRenderTarget = texture;
  4448. var gl = this._gl;
  4449. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  4450. this._gl.viewport(0, 0, texture._width, texture._height);
  4451. this.wipeCaches();
  4452. };
  4453. Engine.prototype.unBindFramebuffer = function (texture) {
  4454. this._currentRenderTarget = null;
  4455. if (texture.generateMipMaps) {
  4456. var gl = this._gl;
  4457. gl.bindTexture(gl.TEXTURE_2D, texture);
  4458. gl.generateMipmap(gl.TEXTURE_2D);
  4459. gl.bindTexture(gl.TEXTURE_2D, null);
  4460. }
  4461. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4462. };
  4463. Engine.prototype.flushFramebuffer = function () {
  4464. this._gl.flush();
  4465. };
  4466. Engine.prototype.restoreDefaultFramebuffer = function () {
  4467. this._currentRenderTarget = null;
  4468. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4469. this.setViewport(this._cachedViewport);
  4470. this.wipeCaches();
  4471. };
  4472. // VBOs
  4473. Engine.prototype._resetVertexBufferBinding = function () {
  4474. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  4475. this._cachedVertexBuffers = null;
  4476. };
  4477. Engine.prototype.createVertexBuffer = function (vertices) {
  4478. var vbo = this._gl.createBuffer();
  4479. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4480. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  4481. this._resetVertexBufferBinding();
  4482. vbo.references = 1;
  4483. return vbo;
  4484. };
  4485. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  4486. var vbo = this._gl.createBuffer();
  4487. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4488. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4489. this._resetVertexBufferBinding();
  4490. vbo.references = 1;
  4491. return vbo;
  4492. };
  4493. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  4494. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4495. if (offset === undefined) {
  4496. offset = 0;
  4497. }
  4498. if (vertices instanceof Float32Array) {
  4499. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  4500. }
  4501. else {
  4502. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  4503. }
  4504. this._resetVertexBufferBinding();
  4505. };
  4506. Engine.prototype._resetIndexBufferBinding = function () {
  4507. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  4508. this._cachedIndexBuffer = null;
  4509. };
  4510. Engine.prototype.createIndexBuffer = function (indices) {
  4511. var vbo = this._gl.createBuffer();
  4512. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  4513. // Check for 32 bits indices
  4514. var arrayBuffer;
  4515. var need32Bits = false;
  4516. if (this._caps.uintIndices) {
  4517. for (var index = 0; index < indices.length; index++) {
  4518. if (indices[index] > 65535) {
  4519. need32Bits = true;
  4520. break;
  4521. }
  4522. }
  4523. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  4524. }
  4525. else {
  4526. arrayBuffer = new Uint16Array(indices);
  4527. }
  4528. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  4529. this._resetIndexBufferBinding();
  4530. vbo.references = 1;
  4531. vbo.is32Bits = need32Bits;
  4532. return vbo;
  4533. };
  4534. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  4535. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  4536. this._cachedVertexBuffers = vertexBuffer;
  4537. this._cachedEffectForVertexBuffers = effect;
  4538. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4539. var offset = 0;
  4540. for (var index = 0; index < vertexDeclaration.length; index++) {
  4541. var order = effect.getAttributeLocation(index);
  4542. if (order >= 0) {
  4543. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  4544. }
  4545. offset += vertexDeclaration[index] * 4;
  4546. }
  4547. }
  4548. if (this._cachedIndexBuffer !== indexBuffer) {
  4549. this._cachedIndexBuffer = indexBuffer;
  4550. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4551. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4552. }
  4553. };
  4554. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  4555. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  4556. this._cachedVertexBuffers = vertexBuffers;
  4557. this._cachedEffectForVertexBuffers = effect;
  4558. var attributes = effect.getAttributesNames();
  4559. for (var index = 0; index < attributes.length; index++) {
  4560. var order = effect.getAttributeLocation(index);
  4561. if (order >= 0) {
  4562. var vertexBuffer = vertexBuffers[attributes[index]];
  4563. if (!vertexBuffer) {
  4564. continue;
  4565. }
  4566. var stride = vertexBuffer.getStrideSize();
  4567. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  4568. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  4569. }
  4570. }
  4571. }
  4572. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  4573. this._cachedIndexBuffer = indexBuffer;
  4574. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4575. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4576. }
  4577. };
  4578. Engine.prototype._releaseBuffer = function (buffer) {
  4579. buffer.references--;
  4580. if (buffer.references === 0) {
  4581. this._gl.deleteBuffer(buffer);
  4582. return true;
  4583. }
  4584. return false;
  4585. };
  4586. Engine.prototype.createInstancesBuffer = function (capacity) {
  4587. var buffer = this._gl.createBuffer();
  4588. buffer.capacity = capacity;
  4589. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  4590. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4591. return buffer;
  4592. };
  4593. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  4594. this._gl.deleteBuffer(buffer);
  4595. };
  4596. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  4597. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4598. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  4599. for (var index = 0; index < 4; index++) {
  4600. var offsetLocation = offsetLocations[index];
  4601. this._gl.enableVertexAttribArray(offsetLocation);
  4602. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  4603. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  4604. }
  4605. };
  4606. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  4607. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4608. for (var index = 0; index < 4; index++) {
  4609. var offsetLocation = offsetLocations[index];
  4610. this._gl.disableVertexAttribArray(offsetLocation);
  4611. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4612. }
  4613. };
  4614. Engine.prototype.applyStates = function () {
  4615. this._depthCullingState.apply(this._gl);
  4616. this._alphaState.apply(this._gl);
  4617. };
  4618. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4619. // Apply states
  4620. this.applyStates();
  4621. this._drawCalls++;
  4622. // Render
  4623. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4624. if (instancesCount) {
  4625. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4626. return;
  4627. }
  4628. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4629. };
  4630. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4631. // Apply states
  4632. this.applyStates();
  4633. this._drawCalls++;
  4634. if (instancesCount) {
  4635. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4636. return;
  4637. }
  4638. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4639. };
  4640. // Shaders
  4641. Engine.prototype._releaseEffect = function (effect) {
  4642. if (this._compiledEffects[effect._key]) {
  4643. delete this._compiledEffects[effect._key];
  4644. if (effect.getProgram()) {
  4645. this._gl.deleteProgram(effect.getProgram());
  4646. }
  4647. }
  4648. };
  4649. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4650. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4651. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4652. var name = vertex + "+" + fragment + "@" + defines;
  4653. if (this._compiledEffects[name]) {
  4654. return this._compiledEffects[name];
  4655. }
  4656. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4657. effect._key = name;
  4658. this._compiledEffects[name] = effect;
  4659. return effect;
  4660. };
  4661. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4662. if (uniformsNames === void 0) { uniformsNames = []; }
  4663. if (samplers === void 0) { samplers = []; }
  4664. if (defines === void 0) { defines = ""; }
  4665. return this.createEffect({
  4666. vertex: "particles",
  4667. fragmentElement: fragmentName
  4668. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4669. };
  4670. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4671. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4672. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4673. var shaderProgram = this._gl.createProgram();
  4674. this._gl.attachShader(shaderProgram, vertexShader);
  4675. this._gl.attachShader(shaderProgram, fragmentShader);
  4676. this._gl.linkProgram(shaderProgram);
  4677. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4678. if (!linked) {
  4679. var error = this._gl.getProgramInfoLog(shaderProgram);
  4680. if (error) {
  4681. throw new Error(error);
  4682. }
  4683. }
  4684. this._gl.deleteShader(vertexShader);
  4685. this._gl.deleteShader(fragmentShader);
  4686. return shaderProgram;
  4687. };
  4688. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4689. var results = [];
  4690. for (var index = 0; index < uniformsNames.length; index++) {
  4691. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4692. }
  4693. return results;
  4694. };
  4695. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4696. var results = [];
  4697. for (var index = 0; index < attributesNames.length; index++) {
  4698. try {
  4699. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4700. }
  4701. catch (e) {
  4702. results.push(-1);
  4703. }
  4704. }
  4705. return results;
  4706. };
  4707. Engine.prototype.enableEffect = function (effect) {
  4708. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4709. if (effect && effect.onBind) {
  4710. effect.onBind(effect);
  4711. }
  4712. return;
  4713. }
  4714. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4715. // Use program
  4716. this._gl.useProgram(effect.getProgram());
  4717. for (var i in this._vertexAttribArrays) {
  4718. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4719. continue;
  4720. }
  4721. this._vertexAttribArrays[i] = false;
  4722. this._gl.disableVertexAttribArray(i);
  4723. }
  4724. var attributesCount = effect.getAttributesCount();
  4725. for (var index = 0; index < attributesCount; index++) {
  4726. // Attributes
  4727. var order = effect.getAttributeLocation(index);
  4728. if (order >= 0) {
  4729. this._vertexAttribArrays[order] = true;
  4730. this._gl.enableVertexAttribArray(order);
  4731. }
  4732. }
  4733. this._currentEffect = effect;
  4734. if (effect.onBind) {
  4735. effect.onBind(effect);
  4736. }
  4737. };
  4738. Engine.prototype.setArray = function (uniform, array) {
  4739. if (!uniform)
  4740. return;
  4741. this._gl.uniform1fv(uniform, array);
  4742. };
  4743. Engine.prototype.setArray2 = function (uniform, array) {
  4744. if (!uniform || array.length % 2 !== 0)
  4745. return;
  4746. this._gl.uniform2fv(uniform, array);
  4747. };
  4748. Engine.prototype.setArray3 = function (uniform, array) {
  4749. if (!uniform || array.length % 3 !== 0)
  4750. return;
  4751. this._gl.uniform3fv(uniform, array);
  4752. };
  4753. Engine.prototype.setArray4 = function (uniform, array) {
  4754. if (!uniform || array.length % 4 !== 0)
  4755. return;
  4756. this._gl.uniform4fv(uniform, array);
  4757. };
  4758. Engine.prototype.setMatrices = function (uniform, matrices) {
  4759. if (!uniform)
  4760. return;
  4761. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4762. };
  4763. Engine.prototype.setMatrix = function (uniform, matrix) {
  4764. if (!uniform)
  4765. return;
  4766. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4767. };
  4768. Engine.prototype.setFloat = function (uniform, value) {
  4769. if (!uniform)
  4770. return;
  4771. this._gl.uniform1f(uniform, value);
  4772. };
  4773. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4774. if (!uniform)
  4775. return;
  4776. this._gl.uniform2f(uniform, x, y);
  4777. };
  4778. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4779. if (!uniform)
  4780. return;
  4781. this._gl.uniform3f(uniform, x, y, z);
  4782. };
  4783. Engine.prototype.setBool = function (uniform, bool) {
  4784. if (!uniform)
  4785. return;
  4786. this._gl.uniform1i(uniform, bool);
  4787. };
  4788. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4789. if (!uniform)
  4790. return;
  4791. this._gl.uniform4f(uniform, x, y, z, w);
  4792. };
  4793. Engine.prototype.setColor3 = function (uniform, color3) {
  4794. if (!uniform)
  4795. return;
  4796. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4797. };
  4798. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4799. if (!uniform)
  4800. return;
  4801. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4802. };
  4803. // States
  4804. Engine.prototype.setState = function (culling, zOffset, force) {
  4805. if (zOffset === void 0) { zOffset = 0; }
  4806. // Culling
  4807. if (this._depthCullingState.cull !== culling || force) {
  4808. if (culling) {
  4809. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4810. this._depthCullingState.cull = true;
  4811. }
  4812. else {
  4813. this._depthCullingState.cull = false;
  4814. }
  4815. }
  4816. // Z offset
  4817. this._depthCullingState.zOffset = zOffset;
  4818. };
  4819. Engine.prototype.setDepthBuffer = function (enable) {
  4820. this._depthCullingState.depthTest = enable;
  4821. };
  4822. Engine.prototype.getDepthWrite = function () {
  4823. return this._depthCullingState.depthMask;
  4824. };
  4825. Engine.prototype.setDepthWrite = function (enable) {
  4826. this._depthCullingState.depthMask = enable;
  4827. };
  4828. Engine.prototype.setColorWrite = function (enable) {
  4829. this._gl.colorMask(enable, enable, enable, enable);
  4830. };
  4831. Engine.prototype.setAlphaMode = function (mode) {
  4832. switch (mode) {
  4833. case Engine.ALPHA_DISABLE:
  4834. this.setDepthWrite(true);
  4835. this._alphaState.alphaBlend = false;
  4836. break;
  4837. case Engine.ALPHA_COMBINE:
  4838. this.setDepthWrite(false);
  4839. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4840. this._alphaState.alphaBlend = true;
  4841. break;
  4842. case Engine.ALPHA_ADD:
  4843. this.setDepthWrite(false);
  4844. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4845. this._alphaState.alphaBlend = true;
  4846. break;
  4847. }
  4848. this._alphaMode = mode;
  4849. };
  4850. Engine.prototype.getAlphaMode = function () {
  4851. return this._alphaMode;
  4852. };
  4853. Engine.prototype.setAlphaTesting = function (enable) {
  4854. this._alphaTest = enable;
  4855. };
  4856. Engine.prototype.getAlphaTesting = function () {
  4857. return this._alphaTest;
  4858. };
  4859. // Textures
  4860. Engine.prototype.wipeCaches = function () {
  4861. this._activeTexturesCache = [];
  4862. this._currentEffect = null;
  4863. this._depthCullingState.reset();
  4864. this._alphaState.reset();
  4865. this._cachedVertexBuffers = null;
  4866. this._cachedIndexBuffer = null;
  4867. this._cachedEffectForVertexBuffers = null;
  4868. };
  4869. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4870. var gl = this._gl;
  4871. gl.bindTexture(gl.TEXTURE_2D, texture);
  4872. var magFilter = gl.NEAREST;
  4873. var minFilter = gl.NEAREST;
  4874. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4875. magFilter = gl.LINEAR;
  4876. minFilter = gl.LINEAR;
  4877. }
  4878. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4879. magFilter = gl.LINEAR;
  4880. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4881. }
  4882. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4883. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4884. gl.bindTexture(gl.TEXTURE_2D, null);
  4885. texture.samplingMode = samplingMode;
  4886. };
  4887. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4888. var _this = this;
  4889. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4890. if (onLoad === void 0) { onLoad = null; }
  4891. if (onError === void 0) { onError = null; }
  4892. if (buffer === void 0) { buffer = null; }
  4893. var texture = this._gl.createTexture();
  4894. var extension;
  4895. var fromData = false;
  4896. if (url.substr(0, 5) === "data:") {
  4897. fromData = true;
  4898. }
  4899. if (!fromData)
  4900. extension = url.substr(url.length - 4, 4).toLowerCase();
  4901. else {
  4902. var oldUrl = url;
  4903. fromData = oldUrl.split(':');
  4904. url = oldUrl;
  4905. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4906. }
  4907. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4908. var isTGA = (extension === ".tga");
  4909. scene._addPendingData(texture);
  4910. texture.url = url;
  4911. texture.noMipmap = noMipmap;
  4912. texture.references = 1;
  4913. this._loadedTexturesCache.push(texture);
  4914. var onerror = function () {
  4915. scene._removePendingData(texture);
  4916. if (onError) {
  4917. onError();
  4918. }
  4919. };
  4920. if (isTGA) {
  4921. var callback = function (arrayBuffer) {
  4922. var data = new Uint8Array(arrayBuffer);
  4923. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4924. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4925. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4926. if (onLoad) {
  4927. onLoad();
  4928. }
  4929. }, samplingMode);
  4930. };
  4931. if (!(fromData instanceof Array))
  4932. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4933. callback(arrayBuffer);
  4934. }, onerror, scene.database, true);
  4935. else
  4936. callback(buffer);
  4937. }
  4938. else if (isDDS) {
  4939. callback = function (data) {
  4940. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4941. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4942. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4943. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4944. if (onLoad) {
  4945. onLoad();
  4946. }
  4947. }, samplingMode);
  4948. };
  4949. if (!(fromData instanceof Array))
  4950. BABYLON.Tools.LoadFile(url, function (data) {
  4951. callback(data);
  4952. }, onerror, scene.database, true);
  4953. else
  4954. callback(buffer);
  4955. }
  4956. else {
  4957. var onload = function (img) {
  4958. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4959. var isPot = (img.width === potWidth && img.height === potHeight);
  4960. if (!isPot) {
  4961. _this._prepareWorkingCanvas();
  4962. _this._workingCanvas.width = potWidth;
  4963. _this._workingCanvas.height = potHeight;
  4964. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4965. _this._workingContext.imageSmoothingEnabled = false;
  4966. _this._workingContext.mozImageSmoothingEnabled = false;
  4967. _this._workingContext.oImageSmoothingEnabled = false;
  4968. _this._workingContext.webkitImageSmoothingEnabled = false;
  4969. _this._workingContext.msImageSmoothingEnabled = false;
  4970. }
  4971. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4972. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4973. _this._workingContext.imageSmoothingEnabled = true;
  4974. _this._workingContext.mozImageSmoothingEnabled = true;
  4975. _this._workingContext.oImageSmoothingEnabled = true;
  4976. _this._workingContext.webkitImageSmoothingEnabled = true;
  4977. _this._workingContext.msImageSmoothingEnabled = true;
  4978. }
  4979. }
  4980. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4981. if (onLoad) {
  4982. onLoad();
  4983. }
  4984. }, samplingMode);
  4985. };
  4986. if (!(fromData instanceof Array))
  4987. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4988. else
  4989. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4990. }
  4991. return texture;
  4992. };
  4993. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4994. var texture = this._gl.createTexture();
  4995. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4996. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4997. // Format
  4998. var internalFormat = this._gl.RGBA;
  4999. switch (format) {
  5000. case Engine.TEXTUREFORMAT_ALPHA:
  5001. internalFormat = this._gl.ALPHA;
  5002. break;
  5003. case Engine.TEXTUREFORMAT_LUMINANCE:
  5004. internalFormat = this._gl.LUMINANCE;
  5005. break;
  5006. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  5007. internalFormat = this._gl.LUMINANCE_ALPHA;
  5008. break;
  5009. case Engine.TEXTUREFORMAT_RGB:
  5010. internalFormat = this._gl.RGB;
  5011. break;
  5012. case Engine.TEXTUREFORMAT_RGBA:
  5013. internalFormat = this._gl.RGBA;
  5014. break;
  5015. }
  5016. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  5017. if (generateMipMaps) {
  5018. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  5019. }
  5020. // Filters
  5021. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  5022. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  5023. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  5024. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5025. this._activeTexturesCache = [];
  5026. texture._baseWidth = width;
  5027. texture._baseHeight = height;
  5028. texture._width = width;
  5029. texture._height = height;
  5030. texture.isReady = true;
  5031. texture.references = 1;
  5032. texture.samplingMode = samplingMode;
  5033. this._loadedTexturesCache.push(texture);
  5034. return texture;
  5035. };
  5036. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  5037. var texture = this._gl.createTexture();
  5038. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  5039. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  5040. this._activeTexturesCache = [];
  5041. texture._baseWidth = width;
  5042. texture._baseHeight = height;
  5043. texture._width = width;
  5044. texture._height = height;
  5045. texture.isReady = false;
  5046. texture.generateMipMaps = generateMipMaps;
  5047. texture.references = 1;
  5048. texture.samplingMode = samplingMode;
  5049. this.updateTextureSamplingMode(samplingMode, texture);
  5050. this._loadedTexturesCache.push(texture);
  5051. return texture;
  5052. };
  5053. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  5054. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  5055. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5056. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  5057. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  5058. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5059. };
  5060. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  5061. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5062. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  5063. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  5064. if (texture.generateMipMaps) {
  5065. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  5066. }
  5067. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5068. this._activeTexturesCache = [];
  5069. texture.isReady = true;
  5070. };
  5071. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  5072. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5073. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  5074. // Scale the video if it is a NPOT using the current working canvas
  5075. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  5076. if (!texture._workingCanvas) {
  5077. texture._workingCanvas = document.createElement("canvas");
  5078. texture._workingContext = texture._workingCanvas.getContext("2d");
  5079. texture._workingCanvas.width = texture._width;
  5080. texture._workingCanvas.height = texture._height;
  5081. }
  5082. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  5083. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  5084. }
  5085. else {
  5086. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  5087. }
  5088. if (texture.generateMipMaps) {
  5089. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  5090. }
  5091. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5092. this._activeTexturesCache = [];
  5093. texture.isReady = true;
  5094. };
  5095. Engine.prototype.createRenderTargetTexture = function (size, options) {
  5096. // old version had a "generateMipMaps" arg instead of options.
  5097. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  5098. // in the same way, generateDepthBuffer is defaulted to true
  5099. var generateMipMaps = false;
  5100. var generateDepthBuffer = true;
  5101. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  5102. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  5103. if (options !== undefined) {
  5104. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  5105. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  5106. type = options.type === undefined ? type : options.type;
  5107. if (options.samplingMode !== undefined) {
  5108. samplingMode = options.samplingMode;
  5109. }
  5110. if (type === Engine.TEXTURETYPE_FLOAT) {
  5111. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  5112. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  5113. }
  5114. }
  5115. var gl = this._gl;
  5116. var texture = gl.createTexture();
  5117. gl.bindTexture(gl.TEXTURE_2D, texture);
  5118. var width = size.width || size;
  5119. var height = size.height || size;
  5120. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  5121. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  5122. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  5123. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  5124. }
  5125. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5126. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5127. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5128. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5129. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  5130. var depthBuffer;
  5131. // Create the depth buffer
  5132. if (generateDepthBuffer) {
  5133. depthBuffer = gl.createRenderbuffer();
  5134. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  5135. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  5136. }
  5137. // Create the framebuffer
  5138. var framebuffer = gl.createFramebuffer();
  5139. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  5140. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5141. if (generateDepthBuffer) {
  5142. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  5143. }
  5144. // Unbind
  5145. gl.bindTexture(gl.TEXTURE_2D, null);
  5146. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  5147. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5148. texture._framebuffer = framebuffer;
  5149. if (generateDepthBuffer) {
  5150. texture._depthBuffer = depthBuffer;
  5151. }
  5152. texture._width = width;
  5153. texture._height = height;
  5154. texture.isReady = true;
  5155. texture.generateMipMaps = generateMipMaps;
  5156. texture.references = 1;
  5157. texture.samplingMode = samplingMode;
  5158. this._activeTexturesCache = [];
  5159. this._loadedTexturesCache.push(texture);
  5160. return texture;
  5161. };
  5162. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  5163. var _this = this;
  5164. var gl = this._gl;
  5165. var texture = gl.createTexture();
  5166. texture.isCube = true;
  5167. texture.url = rootUrl;
  5168. texture.references = 1;
  5169. this._loadedTexturesCache.push(texture);
  5170. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  5171. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  5172. if (isDDS) {
  5173. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  5174. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  5175. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  5176. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5177. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  5178. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  5179. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  5180. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5181. }
  5182. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  5183. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  5184. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5185. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5186. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5187. _this._activeTexturesCache = [];
  5188. texture._width = info.width;
  5189. texture._height = info.height;
  5190. texture.isReady = true;
  5191. }, null, null, true);
  5192. }
  5193. else {
  5194. cascadeLoad(rootUrl, scene, function (imgs) {
  5195. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  5196. var height = width;
  5197. _this._prepareWorkingCanvas();
  5198. _this._workingCanvas.width = width;
  5199. _this._workingCanvas.height = height;
  5200. var faces = [
  5201. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  5202. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  5203. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  5204. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  5205. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  5206. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  5207. ];
  5208. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5209. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  5210. for (var index = 0; index < faces.length; index++) {
  5211. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  5212. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  5213. }
  5214. if (!noMipmap) {
  5215. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5216. }
  5217. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  5218. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  5219. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5220. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5221. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5222. _this._activeTexturesCache = [];
  5223. texture._width = width;
  5224. texture._height = height;
  5225. texture.isReady = true;
  5226. }, extensions);
  5227. }
  5228. return texture;
  5229. };
  5230. Engine.prototype._releaseTexture = function (texture) {
  5231. var gl = this._gl;
  5232. if (texture._framebuffer) {
  5233. gl.deleteFramebuffer(texture._framebuffer);
  5234. }
  5235. if (texture._depthBuffer) {
  5236. gl.deleteRenderbuffer(texture._depthBuffer);
  5237. }
  5238. gl.deleteTexture(texture);
  5239. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  5240. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5241. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5242. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  5243. this._activeTexturesCache[channel] = null;
  5244. }
  5245. var index = this._loadedTexturesCache.indexOf(texture);
  5246. if (index !== -1) {
  5247. this._loadedTexturesCache.splice(index, 1);
  5248. }
  5249. };
  5250. Engine.prototype.bindSamplers = function (effect) {
  5251. this._gl.useProgram(effect.getProgram());
  5252. var samplers = effect.getSamplers();
  5253. for (var index = 0; index < samplers.length; index++) {
  5254. var uniform = effect.getUniform(samplers[index]);
  5255. this._gl.uniform1i(uniform, index);
  5256. }
  5257. this._currentEffect = null;
  5258. };
  5259. Engine.prototype._bindTexture = function (channel, texture) {
  5260. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5261. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5262. this._activeTexturesCache[channel] = null;
  5263. };
  5264. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  5265. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  5266. };
  5267. Engine.prototype.setTexture = function (channel, texture) {
  5268. if (channel < 0) {
  5269. return;
  5270. }
  5271. // Not ready?
  5272. if (!texture || !texture.isReady()) {
  5273. if (this._activeTexturesCache[channel] != null) {
  5274. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5275. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5276. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  5277. this._activeTexturesCache[channel] = null;
  5278. }
  5279. return;
  5280. }
  5281. // Video
  5282. if (texture instanceof BABYLON.VideoTexture) {
  5283. if (texture.update()) {
  5284. this._activeTexturesCache[channel] = null;
  5285. }
  5286. }
  5287. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  5288. texture.delayLoad();
  5289. return;
  5290. }
  5291. if (this._activeTexturesCache[channel] === texture) {
  5292. return;
  5293. }
  5294. this._activeTexturesCache[channel] = texture;
  5295. var internalTexture = texture.getInternalTexture();
  5296. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5297. if (internalTexture.isCube) {
  5298. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  5299. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  5300. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  5301. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  5302. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  5303. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  5304. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  5305. }
  5306. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  5307. }
  5308. else {
  5309. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  5310. if (internalTexture._cachedWrapU !== texture.wrapU) {
  5311. internalTexture._cachedWrapU = texture.wrapU;
  5312. switch (texture.wrapU) {
  5313. case BABYLON.Texture.WRAP_ADDRESSMODE:
  5314. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  5315. break;
  5316. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  5317. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  5318. break;
  5319. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  5320. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  5321. break;
  5322. }
  5323. }
  5324. if (internalTexture._cachedWrapV !== texture.wrapV) {
  5325. internalTexture._cachedWrapV = texture.wrapV;
  5326. switch (texture.wrapV) {
  5327. case BABYLON.Texture.WRAP_ADDRESSMODE:
  5328. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  5329. break;
  5330. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  5331. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  5332. break;
  5333. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  5334. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  5335. break;
  5336. }
  5337. }
  5338. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  5339. }
  5340. };
  5341. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  5342. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  5343. var value = texture.anisotropicFilteringLevel;
  5344. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5345. value = 1;
  5346. }
  5347. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  5348. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  5349. texture._cachedAnisotropicFilteringLevel = value;
  5350. }
  5351. };
  5352. Engine.prototype.readPixels = function (x, y, width, height) {
  5353. var data = new Uint8Array(height * width * 4);
  5354. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  5355. return data;
  5356. };
  5357. // Dispose
  5358. Engine.prototype.dispose = function () {
  5359. this.hideLoadingUI();
  5360. this.stopRenderLoop();
  5361. while (this.scenes.length) {
  5362. this.scenes[0].dispose();
  5363. }
  5364. // Release audio engine
  5365. Engine.audioEngine.dispose();
  5366. for (var name in this._compiledEffects) {
  5367. this._gl.deleteProgram(this._compiledEffects[name]._program);
  5368. }
  5369. for (var i in this._vertexAttribArrays) {
  5370. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5371. continue;
  5372. }
  5373. this._gl.disableVertexAttribArray(i);
  5374. }
  5375. // Events
  5376. window.removeEventListener("blur", this._onBlur);
  5377. window.removeEventListener("focus", this._onFocus);
  5378. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  5379. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  5380. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  5381. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  5382. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  5383. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  5384. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  5385. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  5386. };
  5387. // Loading screen
  5388. Engine.prototype.displayLoadingUI = function () {
  5389. var _this = this;
  5390. this._loadingDiv = document.createElement("div");
  5391. this._loadingDiv.style.opacity = "0";
  5392. this._loadingDiv.style.transition = "opacity 1.5s ease";
  5393. // Loading text
  5394. this._loadingTextDiv = document.createElement("div");
  5395. this._loadingTextDiv.style.position = "absolute";
  5396. this._loadingTextDiv.style.left = "0";
  5397. this._loadingTextDiv.style.top = "50%";
  5398. this._loadingTextDiv.style.marginTop = "80px";
  5399. this._loadingTextDiv.style.width = "100%";
  5400. this._loadingTextDiv.style.height = "20px";
  5401. this._loadingTextDiv.style.fontFamily = "Arial";
  5402. this._loadingTextDiv.style.fontSize = "14px";
  5403. this._loadingTextDiv.style.color = "white";
  5404. this._loadingTextDiv.style.textAlign = "center";
  5405. this._loadingTextDiv.innerHTML = "Loading";
  5406. this._loadingDiv.appendChild(this._loadingTextDiv);
  5407. // Loading img
  5408. var imgBack = new Image();
  5409. 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==";
  5410. imgBack.style.position = "absolute";
  5411. imgBack.style.left = "50%";
  5412. imgBack.style.top = "50%";
  5413. imgBack.style.marginLeft = "-50px";
  5414. imgBack.style.marginTop = "-50px";
  5415. imgBack.style.transition = "transform 1.0s ease";
  5416. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  5417. var deg = 360;
  5418. var onTransitionEnd = function () {
  5419. deg += 360;
  5420. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  5421. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  5422. };
  5423. imgBack.addEventListener("transitionend", onTransitionEnd);
  5424. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  5425. this._loadingDiv.appendChild(imgBack);
  5426. // front image
  5427. var imgFront = new Image();
  5428. 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=";
  5429. imgFront.style.position = "absolute";
  5430. imgFront.style.left = "50%";
  5431. imgFront.style.top = "50%";
  5432. imgFront.style.marginLeft = "-50px";
  5433. imgFront.style.marginTop = "-50px";
  5434. this._loadingDiv.appendChild(imgFront);
  5435. // Resize
  5436. this._resizeLoadingUI = function () {
  5437. var canvasRect = _this.getRenderingCanvasClientRect();
  5438. _this._loadingDiv.style.position = "absolute";
  5439. _this._loadingDiv.style.left = canvasRect.left + "px";
  5440. _this._loadingDiv.style.top = canvasRect.top + "px";
  5441. _this._loadingDiv.style.width = canvasRect.width + "px";
  5442. _this._loadingDiv.style.height = canvasRect.height + "px";
  5443. };
  5444. this._resizeLoadingUI();
  5445. window.addEventListener("resize", this._resizeLoadingUI);
  5446. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5447. document.body.appendChild(this._loadingDiv);
  5448. setTimeout(function () {
  5449. _this._loadingDiv.style.opacity = "1";
  5450. imgBack.style.transform = "rotateZ(360deg)";
  5451. imgBack.style.webkitTransform = "rotateZ(360deg)";
  5452. }, 0);
  5453. };
  5454. Object.defineProperty(Engine.prototype, "loadingUIText", {
  5455. set: function (text) {
  5456. if (!this._loadingDiv) {
  5457. return;
  5458. }
  5459. this._loadingTextDiv.innerHTML = text;
  5460. },
  5461. enumerable: true,
  5462. configurable: true
  5463. });
  5464. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  5465. get: function () {
  5466. return this._loadingDivBackgroundColor;
  5467. },
  5468. set: function (color) {
  5469. this._loadingDivBackgroundColor = color;
  5470. if (!this._loadingDiv) {
  5471. return;
  5472. }
  5473. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5474. },
  5475. enumerable: true,
  5476. configurable: true
  5477. });
  5478. Engine.prototype.hideLoadingUI = function () {
  5479. var _this = this;
  5480. if (!this._loadingDiv) {
  5481. return;
  5482. }
  5483. var onTransitionEnd = function () {
  5484. if (!_this._loadingDiv) {
  5485. return;
  5486. }
  5487. document.body.removeChild(_this._loadingDiv);
  5488. window.removeEventListener("resize", _this._resizeLoadingUI);
  5489. _this._loadingDiv = null;
  5490. };
  5491. this._loadingDiv.style.opacity = "0";
  5492. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  5493. };
  5494. // FPS
  5495. Engine.prototype.getFps = function () {
  5496. return this.fps;
  5497. };
  5498. Engine.prototype.getDeltaTime = function () {
  5499. return this.deltaTime;
  5500. };
  5501. Engine.prototype._measureFps = function () {
  5502. this.previousFramesDuration.push(BABYLON.Tools.Now);
  5503. var length = this.previousFramesDuration.length;
  5504. if (length >= 2) {
  5505. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  5506. }
  5507. if (length >= this.fpsRange) {
  5508. if (length > this.fpsRange) {
  5509. this.previousFramesDuration.splice(0, 1);
  5510. length = this.previousFramesDuration.length;
  5511. }
  5512. var sum = 0;
  5513. for (var id = 0; id < length - 1; id++) {
  5514. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  5515. }
  5516. this.fps = 1000.0 / (sum / (length - 1));
  5517. }
  5518. };
  5519. // Statics
  5520. Engine.isSupported = function () {
  5521. try {
  5522. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  5523. if (navigator.isCocoonJS) {
  5524. return true;
  5525. }
  5526. var tempcanvas = document.createElement("canvas");
  5527. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  5528. return gl != null && !!window.WebGLRenderingContext;
  5529. }
  5530. catch (e) {
  5531. return false;
  5532. }
  5533. };
  5534. // Const statics
  5535. Engine._ALPHA_DISABLE = 0;
  5536. Engine._ALPHA_ADD = 1;
  5537. Engine._ALPHA_COMBINE = 2;
  5538. Engine._DELAYLOADSTATE_NONE = 0;
  5539. Engine._DELAYLOADSTATE_LOADED = 1;
  5540. Engine._DELAYLOADSTATE_LOADING = 2;
  5541. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  5542. Engine._TEXTUREFORMAT_ALPHA = 0;
  5543. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  5544. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  5545. Engine._TEXTUREFORMAT_RGB = 4;
  5546. Engine._TEXTUREFORMAT_RGBA = 4;
  5547. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  5548. Engine._TEXTURETYPE_FLOAT = 1;
  5549. // Updatable statics so stick with vars here
  5550. Engine.Epsilon = 0.001;
  5551. Engine.CollisionsEpsilon = 0.001;
  5552. Engine.ShadersRepository = "Babylon/Shaders/";
  5553. return Engine;
  5554. })();
  5555. BABYLON.Engine = Engine;
  5556. })(BABYLON || (BABYLON = {}));
  5557. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  5558. (function (BABYLON) {
  5559. /**
  5560. * Node is the basic class for all scene objects (Mesh, Light Camera).
  5561. */
  5562. var Node = (function () {
  5563. /**
  5564. * @constructor
  5565. * @param {string} name - the name and id to be given to this node
  5566. * @param {BABYLON.Scene} the scene this node will be added to
  5567. */
  5568. function Node(name, scene) {
  5569. this.state = "";
  5570. this.animations = new Array();
  5571. this._childrenFlag = -1;
  5572. this._isEnabled = true;
  5573. this._isReady = true;
  5574. this._currentRenderId = -1;
  5575. this._parentRenderId = -1;
  5576. this.name = name;
  5577. this.id = name;
  5578. this._scene = scene;
  5579. this._initCache();
  5580. }
  5581. Node.prototype.getScene = function () {
  5582. return this._scene;
  5583. };
  5584. Node.prototype.getEngine = function () {
  5585. return this._scene.getEngine();
  5586. };
  5587. // override it in derived class
  5588. Node.prototype.getWorldMatrix = function () {
  5589. return BABYLON.Matrix.Identity();
  5590. };
  5591. // override it in derived class if you add new variables to the cache
  5592. // and call the parent class method
  5593. Node.prototype._initCache = function () {
  5594. this._cache = {};
  5595. this._cache.parent = undefined;
  5596. };
  5597. Node.prototype.updateCache = function (force) {
  5598. if (!force && this.isSynchronized())
  5599. return;
  5600. this._cache.parent = this.parent;
  5601. this._updateCache();
  5602. };
  5603. // override it in derived class if you add new variables to the cache
  5604. // and call the parent class method if !ignoreParentClass
  5605. Node.prototype._updateCache = function (ignoreParentClass) {
  5606. };
  5607. // override it in derived class if you add new variables to the cache
  5608. Node.prototype._isSynchronized = function () {
  5609. return true;
  5610. };
  5611. Node.prototype.isSynchronizedWithParent = function () {
  5612. if (!this.parent) {
  5613. return true;
  5614. }
  5615. if (this._parentRenderId !== this.parent._currentRenderId) {
  5616. this._parentRenderId = this.parent._currentRenderId;
  5617. return false;
  5618. }
  5619. return this.parent._currentRenderId <= this._currentRenderId && this.parent.isSynchronized();
  5620. };
  5621. Node.prototype.isSynchronized = function (updateCache) {
  5622. var check = this.hasNewParent();
  5623. check = check || !this.isSynchronizedWithParent();
  5624. check = check || !this._isSynchronized();
  5625. if (updateCache)
  5626. this.updateCache(true);
  5627. return !check;
  5628. };
  5629. Node.prototype.hasNewParent = function (update) {
  5630. if (this._cache.parent === this.parent)
  5631. return false;
  5632. if (update)
  5633. this._cache.parent = this.parent;
  5634. return true;
  5635. };
  5636. /**
  5637. * Is this node ready to be used/rendered
  5638. * @return {boolean} is it ready
  5639. */
  5640. Node.prototype.isReady = function () {
  5641. return this._isReady;
  5642. };
  5643. /**
  5644. * Is this node enabled.
  5645. * If the node has a parent and is enabled, the parent will be inspected as well.
  5646. * @return {boolean} whether this node (and its parent) is enabled.
  5647. * @see setEnabled
  5648. */
  5649. Node.prototype.isEnabled = function () {
  5650. if (!this._isEnabled) {
  5651. return false;
  5652. }
  5653. if (this.parent) {
  5654. return this.parent.isEnabled();
  5655. }
  5656. return true;
  5657. };
  5658. /**
  5659. * Set the enabled state of this node.
  5660. * @param {boolean} value - the new enabled state
  5661. * @see isEnabled
  5662. */
  5663. Node.prototype.setEnabled = function (value) {
  5664. this._isEnabled = value;
  5665. };
  5666. /**
  5667. * Is this node a descendant of the given node.
  5668. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5669. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5670. * @see parent
  5671. */
  5672. Node.prototype.isDescendantOf = function (ancestor) {
  5673. if (this.parent) {
  5674. if (this.parent === ancestor) {
  5675. return true;
  5676. }
  5677. return this.parent.isDescendantOf(ancestor);
  5678. }
  5679. return false;
  5680. };
  5681. Node.prototype._getDescendants = function (list, results) {
  5682. for (var index = 0; index < list.length; index++) {
  5683. var item = list[index];
  5684. if (item.isDescendantOf(this)) {
  5685. results.push(item);
  5686. }
  5687. }
  5688. };
  5689. /**
  5690. * Will return all nodes that have this node as parent.
  5691. * @return {BABYLON.Node[]} all children nodes of all types.
  5692. */
  5693. Node.prototype.getDescendants = function () {
  5694. var results = [];
  5695. this._getDescendants(this._scene.meshes, results);
  5696. this._getDescendants(this._scene.lights, results);
  5697. this._getDescendants(this._scene.cameras, results);
  5698. return results;
  5699. };
  5700. Node.prototype._setReady = function (state) {
  5701. if (state == this._isReady) {
  5702. return;
  5703. }
  5704. if (!state) {
  5705. this._isReady = false;
  5706. return;
  5707. }
  5708. this._isReady = true;
  5709. if (this.onReady) {
  5710. this.onReady(this);
  5711. }
  5712. };
  5713. return Node;
  5714. })();
  5715. BABYLON.Node = Node;
  5716. })(BABYLON || (BABYLON = {}));
  5717. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5718. (function (BABYLON) {
  5719. var BoundingSphere = (function () {
  5720. function BoundingSphere(minimum, maximum) {
  5721. this.minimum = minimum;
  5722. this.maximum = maximum;
  5723. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5724. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5725. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5726. this.radius = distance * 0.5;
  5727. this.centerWorld = BABYLON.Vector3.Zero();
  5728. this._update(BABYLON.Matrix.Identity());
  5729. }
  5730. // Methods
  5731. BoundingSphere.prototype._update = function (world) {
  5732. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5733. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5734. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5735. };
  5736. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5737. for (var i = 0; i < 6; i++) {
  5738. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5739. return false;
  5740. }
  5741. return true;
  5742. };
  5743. BoundingSphere.prototype.intersectsPoint = function (point) {
  5744. var x = this.centerWorld.x - point.x;
  5745. var y = this.centerWorld.y - point.y;
  5746. var z = this.centerWorld.z - point.z;
  5747. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5748. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5749. return false;
  5750. return true;
  5751. };
  5752. // Statics
  5753. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5754. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5755. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5756. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5757. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5758. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5759. return false;
  5760. return true;
  5761. };
  5762. return BoundingSphere;
  5763. })();
  5764. BABYLON.BoundingSphere = BoundingSphere;
  5765. })(BABYLON || (BABYLON = {}));
  5766. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5767. (function (BABYLON) {
  5768. var BoundingBox = (function () {
  5769. function BoundingBox(minimum, maximum) {
  5770. this.minimum = minimum;
  5771. this.maximum = maximum;
  5772. this.vectors = new Array();
  5773. this.vectorsWorld = new Array();
  5774. // Bounding vectors
  5775. this.vectors.push(this.minimum.clone());
  5776. this.vectors.push(this.maximum.clone());
  5777. this.vectors.push(this.minimum.clone());
  5778. this.vectors[2].x = this.maximum.x;
  5779. this.vectors.push(this.minimum.clone());
  5780. this.vectors[3].y = this.maximum.y;
  5781. this.vectors.push(this.minimum.clone());
  5782. this.vectors[4].z = this.maximum.z;
  5783. this.vectors.push(this.maximum.clone());
  5784. this.vectors[5].z = this.minimum.z;
  5785. this.vectors.push(this.maximum.clone());
  5786. this.vectors[6].x = this.minimum.x;
  5787. this.vectors.push(this.maximum.clone());
  5788. this.vectors[7].y = this.minimum.y;
  5789. // OBB
  5790. this.center = this.maximum.add(this.minimum).scale(0.5);
  5791. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5792. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5793. for (var index = 0; index < this.vectors.length; index++) {
  5794. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5795. }
  5796. this.minimumWorld = BABYLON.Vector3.Zero();
  5797. this.maximumWorld = BABYLON.Vector3.Zero();
  5798. this._update(BABYLON.Matrix.Identity());
  5799. }
  5800. // Methods
  5801. BoundingBox.prototype.getWorldMatrix = function () {
  5802. return this._worldMatrix;
  5803. };
  5804. BoundingBox.prototype._update = function (world) {
  5805. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5806. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5807. for (var index = 0; index < this.vectors.length; index++) {
  5808. var v = this.vectorsWorld[index];
  5809. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5810. if (v.x < this.minimumWorld.x)
  5811. this.minimumWorld.x = v.x;
  5812. if (v.y < this.minimumWorld.y)
  5813. this.minimumWorld.y = v.y;
  5814. if (v.z < this.minimumWorld.z)
  5815. this.minimumWorld.z = v.z;
  5816. if (v.x > this.maximumWorld.x)
  5817. this.maximumWorld.x = v.x;
  5818. if (v.y > this.maximumWorld.y)
  5819. this.maximumWorld.y = v.y;
  5820. if (v.z > this.maximumWorld.z)
  5821. this.maximumWorld.z = v.z;
  5822. }
  5823. // OBB
  5824. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5825. this.center.scaleInPlace(0.5);
  5826. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5827. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5828. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5829. this._worldMatrix = world;
  5830. };
  5831. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5832. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5833. };
  5834. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5835. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5836. };
  5837. BoundingBox.prototype.intersectsPoint = function (point) {
  5838. var delta = BABYLON.Engine.Epsilon;
  5839. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5840. return false;
  5841. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5842. return false;
  5843. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5844. return false;
  5845. return true;
  5846. };
  5847. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5848. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5849. };
  5850. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5851. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5852. return false;
  5853. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5854. return false;
  5855. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5856. return false;
  5857. return true;
  5858. };
  5859. // Statics
  5860. BoundingBox.Intersects = function (box0, box1) {
  5861. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5862. return false;
  5863. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5864. return false;
  5865. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5866. return false;
  5867. return true;
  5868. };
  5869. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5870. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5871. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5872. return (num <= (sphereRadius * sphereRadius));
  5873. };
  5874. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5875. for (var p = 0; p < 6; p++) {
  5876. for (var i = 0; i < 8; i++) {
  5877. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5878. return false;
  5879. }
  5880. }
  5881. }
  5882. return true;
  5883. };
  5884. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5885. for (var p = 0; p < 6; p++) {
  5886. var inCount = 8;
  5887. for (var i = 0; i < 8; i++) {
  5888. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5889. --inCount;
  5890. }
  5891. else {
  5892. break;
  5893. }
  5894. }
  5895. if (inCount === 0)
  5896. return false;
  5897. }
  5898. return true;
  5899. };
  5900. return BoundingBox;
  5901. })();
  5902. BABYLON.BoundingBox = BoundingBox;
  5903. })(BABYLON || (BABYLON = {}));
  5904. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5905. (function (BABYLON) {
  5906. var computeBoxExtents = function (axis, box) {
  5907. var p = BABYLON.Vector3.Dot(box.center, axis);
  5908. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5909. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5910. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5911. var r = r0 + r1 + r2;
  5912. return {
  5913. min: p - r,
  5914. max: p + r
  5915. };
  5916. };
  5917. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5918. var axisOverlap = function (axis, box0, box1) {
  5919. var result0 = computeBoxExtents(axis, box0);
  5920. var result1 = computeBoxExtents(axis, box1);
  5921. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5922. };
  5923. var BoundingInfo = (function () {
  5924. function BoundingInfo(minimum, maximum) {
  5925. this.minimum = minimum;
  5926. this.maximum = maximum;
  5927. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5928. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5929. }
  5930. // Methods
  5931. BoundingInfo.prototype._update = function (world) {
  5932. this.boundingBox._update(world);
  5933. this.boundingSphere._update(world);
  5934. };
  5935. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5936. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5937. return false;
  5938. return this.boundingBox.isInFrustum(frustumPlanes);
  5939. };
  5940. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5941. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5942. };
  5943. BoundingInfo.prototype._checkCollision = function (collider) {
  5944. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5945. };
  5946. BoundingInfo.prototype.intersectsPoint = function (point) {
  5947. if (!this.boundingSphere.centerWorld) {
  5948. return false;
  5949. }
  5950. if (!this.boundingSphere.intersectsPoint(point)) {
  5951. return false;
  5952. }
  5953. if (!this.boundingBox.intersectsPoint(point)) {
  5954. return false;
  5955. }
  5956. return true;
  5957. };
  5958. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5959. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5960. return false;
  5961. }
  5962. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5963. return false;
  5964. }
  5965. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5966. return false;
  5967. }
  5968. if (!precise) {
  5969. return true;
  5970. }
  5971. var box0 = this.boundingBox;
  5972. var box1 = boundingInfo.boundingBox;
  5973. if (!axisOverlap(box0.directions[0], box0, box1))
  5974. return false;
  5975. if (!axisOverlap(box0.directions[1], box0, box1))
  5976. return false;
  5977. if (!axisOverlap(box0.directions[2], box0, box1))
  5978. return false;
  5979. if (!axisOverlap(box1.directions[0], box0, box1))
  5980. return false;
  5981. if (!axisOverlap(box1.directions[1], box0, box1))
  5982. return false;
  5983. if (!axisOverlap(box1.directions[2], box0, box1))
  5984. return false;
  5985. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5986. return false;
  5987. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5988. return false;
  5989. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5990. return false;
  5991. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5992. return false;
  5993. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5994. return false;
  5995. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5996. return false;
  5997. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5998. return false;
  5999. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  6000. return false;
  6001. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  6002. return false;
  6003. return true;
  6004. };
  6005. return BoundingInfo;
  6006. })();
  6007. BABYLON.BoundingInfo = BoundingInfo;
  6008. })(BABYLON || (BABYLON = {}));
  6009. //# sourceMappingURL=babylon.boundingInfo.js.map
  6010. var BABYLON;
  6011. (function (BABYLON) {
  6012. var Light = (function (_super) {
  6013. __extends(Light, _super);
  6014. function Light(name, scene) {
  6015. _super.call(this, name, scene);
  6016. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  6017. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  6018. this.intensity = 1.0;
  6019. this.range = Number.MAX_VALUE;
  6020. this.includeOnlyWithLayerMask = 0;
  6021. this.includedOnlyMeshes = new Array();
  6022. this.excludedMeshes = new Array();
  6023. this.excludeWithLayerMask = 0;
  6024. this._excludedMeshesIds = new Array();
  6025. this._includedOnlyMeshesIds = new Array();
  6026. scene.addLight(this);
  6027. }
  6028. Light.prototype.getShadowGenerator = function () {
  6029. return this._shadowGenerator;
  6030. };
  6031. Light.prototype.getAbsolutePosition = function () {
  6032. return BABYLON.Vector3.Zero();
  6033. };
  6034. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  6035. };
  6036. Light.prototype._getWorldMatrix = function () {
  6037. return BABYLON.Matrix.Identity();
  6038. };
  6039. Light.prototype.canAffectMesh = function (mesh) {
  6040. if (!mesh) {
  6041. return true;
  6042. }
  6043. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  6044. return false;
  6045. }
  6046. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  6047. return false;
  6048. }
  6049. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  6050. return false;
  6051. }
  6052. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  6053. return false;
  6054. }
  6055. return true;
  6056. };
  6057. Light.prototype.getWorldMatrix = function () {
  6058. this._currentRenderId = this.getScene().getRenderId();
  6059. var worldMatrix = this._getWorldMatrix();
  6060. if (this.parent && this.parent.getWorldMatrix) {
  6061. if (!this._parentedWorldMatrix) {
  6062. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  6063. }
  6064. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  6065. return this._parentedWorldMatrix;
  6066. }
  6067. return worldMatrix;
  6068. };
  6069. Light.prototype.dispose = function () {
  6070. if (this._shadowGenerator) {
  6071. this._shadowGenerator.dispose();
  6072. this._shadowGenerator = null;
  6073. }
  6074. // Remove from scene
  6075. this.getScene().removeLight(this);
  6076. };
  6077. return Light;
  6078. })(BABYLON.Node);
  6079. BABYLON.Light = Light;
  6080. })(BABYLON || (BABYLON = {}));
  6081. //# sourceMappingURL=babylon.light.js.map
  6082. var BABYLON;
  6083. (function (BABYLON) {
  6084. var PointLight = (function (_super) {
  6085. __extends(PointLight, _super);
  6086. function PointLight(name, position, scene) {
  6087. _super.call(this, name, scene);
  6088. this.position = position;
  6089. }
  6090. PointLight.prototype.getAbsolutePosition = function () {
  6091. return this._transformedPosition ? this._transformedPosition : this.position;
  6092. };
  6093. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  6094. if (this.parent && this.parent.getWorldMatrix) {
  6095. if (!this._transformedPosition) {
  6096. this._transformedPosition = BABYLON.Vector3.Zero();
  6097. }
  6098. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  6099. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  6100. return;
  6101. }
  6102. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  6103. };
  6104. PointLight.prototype.getShadowGenerator = function () {
  6105. return null;
  6106. };
  6107. PointLight.prototype._getWorldMatrix = function () {
  6108. if (!this._worldMatrix) {
  6109. this._worldMatrix = BABYLON.Matrix.Identity();
  6110. }
  6111. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6112. return this._worldMatrix;
  6113. };
  6114. return PointLight;
  6115. })(BABYLON.Light);
  6116. BABYLON.PointLight = PointLight;
  6117. })(BABYLON || (BABYLON = {}));
  6118. //# sourceMappingURL=babylon.pointLight.js.map
  6119. var BABYLON;
  6120. (function (BABYLON) {
  6121. var SpotLight = (function (_super) {
  6122. __extends(SpotLight, _super);
  6123. function SpotLight(name, position, direction, angle, exponent, scene) {
  6124. _super.call(this, name, scene);
  6125. this.position = position;
  6126. this.direction = direction;
  6127. this.angle = angle;
  6128. this.exponent = exponent;
  6129. }
  6130. SpotLight.prototype.getAbsolutePosition = function () {
  6131. return this.transformedPosition ? this.transformedPosition : this.position;
  6132. };
  6133. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  6134. var activeCamera = this.getScene().activeCamera;
  6135. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  6136. };
  6137. SpotLight.prototype.supportsVSM = function () {
  6138. return true;
  6139. };
  6140. SpotLight.prototype.needRefreshPerFrame = function () {
  6141. return false;
  6142. };
  6143. SpotLight.prototype.setDirectionToTarget = function (target) {
  6144. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  6145. return this.direction;
  6146. };
  6147. SpotLight.prototype.computeTransformedPosition = function () {
  6148. if (this.parent && this.parent.getWorldMatrix) {
  6149. if (!this.transformedPosition) {
  6150. this.transformedPosition = BABYLON.Vector3.Zero();
  6151. }
  6152. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  6153. return true;
  6154. }
  6155. return false;
  6156. };
  6157. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  6158. var normalizeDirection;
  6159. if (this.parent && this.parent.getWorldMatrix) {
  6160. if (!this._transformedDirection) {
  6161. this._transformedDirection = BABYLON.Vector3.Zero();
  6162. }
  6163. this.computeTransformedPosition();
  6164. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  6165. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  6166. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  6167. }
  6168. else {
  6169. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  6170. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6171. }
  6172. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  6173. };
  6174. SpotLight.prototype._getWorldMatrix = function () {
  6175. if (!this._worldMatrix) {
  6176. this._worldMatrix = BABYLON.Matrix.Identity();
  6177. }
  6178. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6179. return this._worldMatrix;
  6180. };
  6181. return SpotLight;
  6182. })(BABYLON.Light);
  6183. BABYLON.SpotLight = SpotLight;
  6184. })(BABYLON || (BABYLON = {}));
  6185. //# sourceMappingURL=babylon.spotLight.js.map
  6186. var BABYLON;
  6187. (function (BABYLON) {
  6188. var DirectionalLight = (function (_super) {
  6189. __extends(DirectionalLight, _super);
  6190. function DirectionalLight(name, direction, scene) {
  6191. _super.call(this, name, scene);
  6192. this.direction = direction;
  6193. this.shadowOrthoScale = 0.5;
  6194. this.position = direction.scale(-1);
  6195. }
  6196. DirectionalLight.prototype.getAbsolutePosition = function () {
  6197. return this.transformedPosition ? this.transformedPosition : this.position;
  6198. };
  6199. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  6200. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  6201. return this.direction;
  6202. };
  6203. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  6204. var orthoLeft = Number.MAX_VALUE;
  6205. var orthoRight = Number.MIN_VALUE;
  6206. var orthoTop = Number.MIN_VALUE;
  6207. var orthoBottom = Number.MAX_VALUE;
  6208. var tempVector3 = BABYLON.Vector3.Zero();
  6209. var activeCamera = this.getScene().activeCamera;
  6210. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  6211. var mesh = renderList[meshIndex];
  6212. if (!mesh) {
  6213. continue;
  6214. }
  6215. var boundingInfo = mesh.getBoundingInfo();
  6216. if (!boundingInfo) {
  6217. continue;
  6218. }
  6219. var boundingBox = boundingInfo.boundingBox;
  6220. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  6221. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  6222. if (tempVector3.x < orthoLeft)
  6223. orthoLeft = tempVector3.x;
  6224. if (tempVector3.y < orthoBottom)
  6225. orthoBottom = tempVector3.y;
  6226. if (tempVector3.x > orthoRight)
  6227. orthoRight = tempVector3.x;
  6228. if (tempVector3.y > orthoTop)
  6229. orthoTop = tempVector3.y;
  6230. }
  6231. }
  6232. var xOffset = orthoRight - orthoLeft;
  6233. var yOffset = orthoTop - orthoBottom;
  6234. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  6235. };
  6236. DirectionalLight.prototype.supportsVSM = function () {
  6237. return true;
  6238. };
  6239. DirectionalLight.prototype.needRefreshPerFrame = function () {
  6240. return true;
  6241. };
  6242. DirectionalLight.prototype.computeTransformedPosition = function () {
  6243. if (this.parent && this.parent.getWorldMatrix) {
  6244. if (!this.transformedPosition) {
  6245. this.transformedPosition = BABYLON.Vector3.Zero();
  6246. }
  6247. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  6248. return true;
  6249. }
  6250. return false;
  6251. };
  6252. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  6253. if (this.parent && this.parent.getWorldMatrix) {
  6254. if (!this._transformedDirection) {
  6255. this._transformedDirection = BABYLON.Vector3.Zero();
  6256. }
  6257. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  6258. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  6259. return;
  6260. }
  6261. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  6262. };
  6263. DirectionalLight.prototype._getWorldMatrix = function () {
  6264. if (!this._worldMatrix) {
  6265. this._worldMatrix = BABYLON.Matrix.Identity();
  6266. }
  6267. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6268. return this._worldMatrix;
  6269. };
  6270. return DirectionalLight;
  6271. })(BABYLON.Light);
  6272. BABYLON.DirectionalLight = DirectionalLight;
  6273. })(BABYLON || (BABYLON = {}));
  6274. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  6275. (function (BABYLON) {
  6276. var ShadowGenerator = (function () {
  6277. function ShadowGenerator(mapSize, light) {
  6278. var _this = this;
  6279. // Members
  6280. this._filter = ShadowGenerator.FILTER_NONE;
  6281. this.blurScale = 2;
  6282. this._blurBoxOffset = 0;
  6283. this._bias = 0.00005;
  6284. this._darkness = 0;
  6285. this._transparencyShadow = false;
  6286. this._viewMatrix = BABYLON.Matrix.Zero();
  6287. this._projectionMatrix = BABYLON.Matrix.Zero();
  6288. this._transformMatrix = BABYLON.Matrix.Zero();
  6289. this._worldViewProjection = BABYLON.Matrix.Zero();
  6290. this._light = light;
  6291. this._scene = light.getScene();
  6292. this._mapSize = mapSize;
  6293. light._shadowGenerator = this;
  6294. // Render target
  6295. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  6296. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6297. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6298. this._shadowMap.anisotropicFilteringLevel = 1;
  6299. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6300. this._shadowMap.renderParticles = false;
  6301. this._shadowMap.onAfterUnbind = function () {
  6302. if (!_this.useBlurVarianceShadowMap) {
  6303. return;
  6304. }
  6305. if (!_this._shadowMap2) {
  6306. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  6307. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6308. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6309. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  6310. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  6311. _this._downSamplePostprocess.onApply = function (effect) {
  6312. effect.setTexture("textureSampler", _this._shadowMap);
  6313. };
  6314. _this.blurBoxOffset = 1;
  6315. }
  6316. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  6317. };
  6318. // Custom render function
  6319. var renderSubMesh = function (subMesh) {
  6320. var mesh = subMesh.getRenderingMesh();
  6321. var scene = _this._scene;
  6322. var engine = scene.getEngine();
  6323. // Culling
  6324. engine.setState(subMesh.getMaterial().backFaceCulling);
  6325. // Managing instances
  6326. var batch = mesh._getInstancesRenderList(subMesh._id);
  6327. if (batch.mustReturn) {
  6328. return;
  6329. }
  6330. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  6331. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  6332. engine.enableEffect(_this._effect);
  6333. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  6334. var material = subMesh.getMaterial();
  6335. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  6336. // Alpha test
  6337. if (material && material.needAlphaTesting()) {
  6338. var alphaTexture = material.getAlphaTestTexture();
  6339. _this._effect.setTexture("diffuseSampler", alphaTexture);
  6340. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  6341. }
  6342. // Bones
  6343. if (mesh.useBones) {
  6344. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  6345. }
  6346. // Draw
  6347. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  6348. }
  6349. else {
  6350. // Need to reset refresh rate of the shadowMap
  6351. _this._shadowMap.resetRefreshCounter();
  6352. }
  6353. };
  6354. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  6355. var index;
  6356. for (index = 0; index < opaqueSubMeshes.length; index++) {
  6357. renderSubMesh(opaqueSubMeshes.data[index]);
  6358. }
  6359. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  6360. renderSubMesh(alphaTestSubMeshes.data[index]);
  6361. }
  6362. if (_this._transparencyShadow) {
  6363. for (index = 0; index < transparentSubMeshes.length; index++) {
  6364. renderSubMesh(transparentSubMeshes.data[index]);
  6365. }
  6366. }
  6367. };
  6368. this._shadowMap.onClear = function (engine) {
  6369. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  6370. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  6371. }
  6372. else {
  6373. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  6374. }
  6375. };
  6376. }
  6377. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  6378. // Static
  6379. get: function () {
  6380. return ShadowGenerator._FILTER_NONE;
  6381. },
  6382. enumerable: true,
  6383. configurable: true
  6384. });
  6385. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  6386. get: function () {
  6387. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  6388. },
  6389. enumerable: true,
  6390. configurable: true
  6391. });
  6392. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  6393. get: function () {
  6394. return ShadowGenerator._FILTER_POISSONSAMPLING;
  6395. },
  6396. enumerable: true,
  6397. configurable: true
  6398. });
  6399. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  6400. get: function () {
  6401. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  6402. },
  6403. enumerable: true,
  6404. configurable: true
  6405. });
  6406. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  6407. get: function () {
  6408. return this._bias;
  6409. },
  6410. set: function (bias) {
  6411. this._bias = bias;
  6412. },
  6413. enumerable: true,
  6414. configurable: true
  6415. });
  6416. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  6417. get: function () {
  6418. return this._blurBoxOffset;
  6419. },
  6420. set: function (value) {
  6421. var _this = this;
  6422. if (this._blurBoxOffset === value) {
  6423. return;
  6424. }
  6425. this._blurBoxOffset = value;
  6426. if (this._boxBlurPostprocess) {
  6427. this._boxBlurPostprocess.dispose();
  6428. }
  6429. this._boxBlurPostprocess = new BABYLON.PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
  6430. this._boxBlurPostprocess.onApply = function (effect) {
  6431. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  6432. };
  6433. },
  6434. enumerable: true,
  6435. configurable: true
  6436. });
  6437. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  6438. get: function () {
  6439. return this._filter;
  6440. },
  6441. set: function (value) {
  6442. if (this._filter === value) {
  6443. return;
  6444. }
  6445. this._filter = value;
  6446. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6447. this._shadowMap.anisotropicFilteringLevel = 16;
  6448. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  6449. }
  6450. else {
  6451. this._shadowMap.anisotropicFilteringLevel = 1;
  6452. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6453. }
  6454. },
  6455. enumerable: true,
  6456. configurable: true
  6457. });
  6458. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  6459. get: function () {
  6460. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  6461. },
  6462. set: function (value) {
  6463. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6464. },
  6465. enumerable: true,
  6466. configurable: true
  6467. });
  6468. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  6469. get: function () {
  6470. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING || (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP || this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  6471. },
  6472. set: function (value) {
  6473. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  6474. },
  6475. enumerable: true,
  6476. configurable: true
  6477. });
  6478. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  6479. get: function () {
  6480. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  6481. },
  6482. set: function (value) {
  6483. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6484. },
  6485. enumerable: true,
  6486. configurable: true
  6487. });
  6488. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  6489. var defines = [];
  6490. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6491. defines.push("#define VSM");
  6492. }
  6493. var attribs = [BABYLON.VertexBuffer.PositionKind];
  6494. var mesh = subMesh.getMesh();
  6495. var material = subMesh.getMaterial();
  6496. // Alpha test
  6497. if (material && material.needAlphaTesting()) {
  6498. defines.push("#define ALPHATEST");
  6499. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  6500. attribs.push(BABYLON.VertexBuffer.UVKind);
  6501. defines.push("#define UV1");
  6502. }
  6503. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  6504. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  6505. defines.push("#define UV2");
  6506. }
  6507. }
  6508. // Bones
  6509. if (mesh.useBones) {
  6510. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  6511. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  6512. defines.push("#define BONES");
  6513. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  6514. }
  6515. // Instances
  6516. if (useInstances) {
  6517. defines.push("#define INSTANCES");
  6518. attribs.push("world0");
  6519. attribs.push("world1");
  6520. attribs.push("world2");
  6521. attribs.push("world3");
  6522. }
  6523. // Get correct effect
  6524. var join = defines.join("\n");
  6525. if (this._cachedDefines !== join) {
  6526. this._cachedDefines = join;
  6527. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  6528. }
  6529. return this._effect.isReady();
  6530. };
  6531. ShadowGenerator.prototype.getShadowMap = function () {
  6532. return this._shadowMap;
  6533. };
  6534. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  6535. if (this._shadowMap2) {
  6536. return this._shadowMap2;
  6537. }
  6538. return this._shadowMap;
  6539. };
  6540. ShadowGenerator.prototype.getLight = function () {
  6541. return this._light;
  6542. };
  6543. // Methods
  6544. ShadowGenerator.prototype.getTransformMatrix = function () {
  6545. var scene = this._scene;
  6546. if (this._currentRenderID === scene.getRenderId()) {
  6547. return this._transformMatrix;
  6548. }
  6549. this._currentRenderID = scene.getRenderId();
  6550. var lightPosition = this._light.position;
  6551. var lightDirection = this._light.direction;
  6552. if (this._light.computeTransformedPosition()) {
  6553. lightPosition = this._light.transformedPosition;
  6554. }
  6555. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  6556. this._cachedPosition = lightPosition.clone();
  6557. this._cachedDirection = lightDirection.clone();
  6558. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  6559. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  6560. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6561. }
  6562. return this._transformMatrix;
  6563. };
  6564. ShadowGenerator.prototype.getDarkness = function () {
  6565. return this._darkness;
  6566. };
  6567. ShadowGenerator.prototype.setDarkness = function (darkness) {
  6568. if (darkness >= 1.0)
  6569. this._darkness = 1.0;
  6570. else if (darkness <= 0.0)
  6571. this._darkness = 0.0;
  6572. else
  6573. this._darkness = darkness;
  6574. };
  6575. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  6576. this._transparencyShadow = hasShadow;
  6577. };
  6578. ShadowGenerator.prototype._packHalf = function (depth) {
  6579. var scale = depth * 255.0;
  6580. var fract = scale - Math.floor(scale);
  6581. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  6582. };
  6583. ShadowGenerator.prototype.dispose = function () {
  6584. this._shadowMap.dispose();
  6585. if (this._shadowMap2) {
  6586. this._shadowMap2.dispose();
  6587. }
  6588. if (this._downSamplePostprocess) {
  6589. this._downSamplePostprocess.dispose();
  6590. }
  6591. if (this._boxBlurPostprocess) {
  6592. this._boxBlurPostprocess.dispose();
  6593. }
  6594. };
  6595. ShadowGenerator._FILTER_NONE = 0;
  6596. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  6597. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  6598. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  6599. return ShadowGenerator;
  6600. })();
  6601. BABYLON.ShadowGenerator = ShadowGenerator;
  6602. })(BABYLON || (BABYLON = {}));
  6603. //# sourceMappingURL=babylon.shadowGenerator.js.map
  6604. var BABYLON;
  6605. (function (BABYLON) {
  6606. var HemisphericLight = (function (_super) {
  6607. __extends(HemisphericLight, _super);
  6608. function HemisphericLight(name, direction, scene) {
  6609. _super.call(this, name, scene);
  6610. this.direction = direction;
  6611. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  6612. }
  6613. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  6614. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  6615. return this.direction;
  6616. };
  6617. HemisphericLight.prototype.getShadowGenerator = function () {
  6618. return null;
  6619. };
  6620. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  6621. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6622. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  6623. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  6624. };
  6625. HemisphericLight.prototype._getWorldMatrix = function () {
  6626. if (!this._worldMatrix) {
  6627. this._worldMatrix = BABYLON.Matrix.Identity();
  6628. }
  6629. return this._worldMatrix;
  6630. };
  6631. return HemisphericLight;
  6632. })(BABYLON.Light);
  6633. BABYLON.HemisphericLight = HemisphericLight;
  6634. })(BABYLON || (BABYLON = {}));
  6635. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  6636. (function (BABYLON) {
  6637. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  6638. if (boxMin.x > sphereCenter.x + sphereRadius)
  6639. return false;
  6640. if (sphereCenter.x - sphereRadius > boxMax.x)
  6641. return false;
  6642. if (boxMin.y > sphereCenter.y + sphereRadius)
  6643. return false;
  6644. if (sphereCenter.y - sphereRadius > boxMax.y)
  6645. return false;
  6646. if (boxMin.z > sphereCenter.z + sphereRadius)
  6647. return false;
  6648. if (sphereCenter.z - sphereRadius > boxMax.z)
  6649. return false;
  6650. return true;
  6651. };
  6652. var getLowestRoot = function (a, b, c, maxR) {
  6653. var determinant = b * b - 4.0 * a * c;
  6654. var result = { root: 0, found: false };
  6655. if (determinant < 0)
  6656. return result;
  6657. var sqrtD = Math.sqrt(determinant);
  6658. var r1 = (-b - sqrtD) / (2.0 * a);
  6659. var r2 = (-b + sqrtD) / (2.0 * a);
  6660. if (r1 > r2) {
  6661. var temp = r2;
  6662. r2 = r1;
  6663. r1 = temp;
  6664. }
  6665. if (r1 > 0 && r1 < maxR) {
  6666. result.root = r1;
  6667. result.found = true;
  6668. return result;
  6669. }
  6670. if (r2 > 0 && r2 < maxR) {
  6671. result.root = r2;
  6672. result.found = true;
  6673. return result;
  6674. }
  6675. return result;
  6676. };
  6677. var Collider = (function () {
  6678. function Collider() {
  6679. this.radius = new BABYLON.Vector3(1, 1, 1);
  6680. this.retry = 0;
  6681. this.basePointWorld = BABYLON.Vector3.Zero();
  6682. this.velocityWorld = BABYLON.Vector3.Zero();
  6683. this.normalizedVelocity = BABYLON.Vector3.Zero();
  6684. this._collisionPoint = BABYLON.Vector3.Zero();
  6685. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  6686. this._tempVector = BABYLON.Vector3.Zero();
  6687. this._tempVector2 = BABYLON.Vector3.Zero();
  6688. this._tempVector3 = BABYLON.Vector3.Zero();
  6689. this._tempVector4 = BABYLON.Vector3.Zero();
  6690. this._edge = BABYLON.Vector3.Zero();
  6691. this._baseToVertex = BABYLON.Vector3.Zero();
  6692. this._destinationPoint = BABYLON.Vector3.Zero();
  6693. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  6694. this._displacementVector = BABYLON.Vector3.Zero();
  6695. }
  6696. // Methods
  6697. Collider.prototype._initialize = function (source, dir, e) {
  6698. this.velocity = dir;
  6699. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  6700. this.basePoint = source;
  6701. source.multiplyToRef(this.radius, this.basePointWorld);
  6702. dir.multiplyToRef(this.radius, this.velocityWorld);
  6703. this.velocityWorldLength = this.velocityWorld.length();
  6704. this.epsilon = e;
  6705. this.collisionFound = false;
  6706. };
  6707. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  6708. pa.subtractToRef(point, this._tempVector);
  6709. pb.subtractToRef(point, this._tempVector2);
  6710. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  6711. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6712. if (d < 0)
  6713. return false;
  6714. pc.subtractToRef(point, this._tempVector3);
  6715. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  6716. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6717. if (d < 0)
  6718. return false;
  6719. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  6720. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6721. return d >= 0;
  6722. };
  6723. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  6724. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  6725. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  6726. if (distance > this.velocityWorldLength + max + sphereRadius) {
  6727. return false;
  6728. }
  6729. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  6730. return false;
  6731. return true;
  6732. };
  6733. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  6734. var t0;
  6735. var embeddedInPlane = false;
  6736. if (!subMesh._trianglePlanes) {
  6737. subMesh._trianglePlanes = [];
  6738. }
  6739. if (!subMesh._trianglePlanes[faceIndex]) {
  6740. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  6741. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  6742. }
  6743. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  6744. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  6745. return;
  6746. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  6747. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  6748. if (normalDotVelocity == 0) {
  6749. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  6750. return;
  6751. embeddedInPlane = true;
  6752. t0 = 0;
  6753. }
  6754. else {
  6755. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6756. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6757. if (t0 > t1) {
  6758. var temp = t1;
  6759. t1 = t0;
  6760. t0 = temp;
  6761. }
  6762. if (t0 > 1.0 || t1 < 0.0)
  6763. return;
  6764. if (t0 < 0)
  6765. t0 = 0;
  6766. if (t0 > 1.0)
  6767. t0 = 1.0;
  6768. }
  6769. this._collisionPoint.copyFromFloats(0, 0, 0);
  6770. var found = false;
  6771. var t = 1.0;
  6772. if (!embeddedInPlane) {
  6773. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  6774. this.velocity.scaleToRef(t0, this._tempVector);
  6775. this._planeIntersectionPoint.addInPlace(this._tempVector);
  6776. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  6777. found = true;
  6778. t = t0;
  6779. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  6780. }
  6781. }
  6782. if (!found) {
  6783. var velocitySquaredLength = this.velocity.lengthSquared();
  6784. var a = velocitySquaredLength;
  6785. this.basePoint.subtractToRef(p1, this._tempVector);
  6786. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6787. var c = this._tempVector.lengthSquared() - 1.0;
  6788. var lowestRoot = getLowestRoot(a, b, c, t);
  6789. if (lowestRoot.found) {
  6790. t = lowestRoot.root;
  6791. found = true;
  6792. this._collisionPoint.copyFrom(p1);
  6793. }
  6794. this.basePoint.subtractToRef(p2, this._tempVector);
  6795. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6796. c = this._tempVector.lengthSquared() - 1.0;
  6797. lowestRoot = getLowestRoot(a, b, c, t);
  6798. if (lowestRoot.found) {
  6799. t = lowestRoot.root;
  6800. found = true;
  6801. this._collisionPoint.copyFrom(p2);
  6802. }
  6803. this.basePoint.subtractToRef(p3, this._tempVector);
  6804. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6805. c = this._tempVector.lengthSquared() - 1.0;
  6806. lowestRoot = getLowestRoot(a, b, c, t);
  6807. if (lowestRoot.found) {
  6808. t = lowestRoot.root;
  6809. found = true;
  6810. this._collisionPoint.copyFrom(p3);
  6811. }
  6812. p2.subtractToRef(p1, this._edge);
  6813. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6814. var edgeSquaredLength = this._edge.lengthSquared();
  6815. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6816. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6817. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6818. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6819. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6820. lowestRoot = getLowestRoot(a, b, c, t);
  6821. if (lowestRoot.found) {
  6822. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6823. if (f >= 0.0 && f <= 1.0) {
  6824. t = lowestRoot.root;
  6825. found = true;
  6826. this._edge.scaleInPlace(f);
  6827. p1.addToRef(this._edge, this._collisionPoint);
  6828. }
  6829. }
  6830. p3.subtractToRef(p2, this._edge);
  6831. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6832. edgeSquaredLength = this._edge.lengthSquared();
  6833. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6834. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6835. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6836. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6837. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6838. lowestRoot = getLowestRoot(a, b, c, t);
  6839. if (lowestRoot.found) {
  6840. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6841. if (f >= 0.0 && f <= 1.0) {
  6842. t = lowestRoot.root;
  6843. found = true;
  6844. this._edge.scaleInPlace(f);
  6845. p2.addToRef(this._edge, this._collisionPoint);
  6846. }
  6847. }
  6848. p1.subtractToRef(p3, this._edge);
  6849. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6850. edgeSquaredLength = this._edge.lengthSquared();
  6851. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6852. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6853. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6854. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6855. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6856. lowestRoot = getLowestRoot(a, b, c, t);
  6857. if (lowestRoot.found) {
  6858. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6859. if (f >= 0.0 && f <= 1.0) {
  6860. t = lowestRoot.root;
  6861. found = true;
  6862. this._edge.scaleInPlace(f);
  6863. p3.addToRef(this._edge, this._collisionPoint);
  6864. }
  6865. }
  6866. }
  6867. if (found) {
  6868. var distToCollision = t * this.velocity.length();
  6869. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6870. if (!this.intersectionPoint) {
  6871. this.intersectionPoint = this._collisionPoint.clone();
  6872. }
  6873. else {
  6874. this.intersectionPoint.copyFrom(this._collisionPoint);
  6875. }
  6876. this.nearestDistance = distToCollision;
  6877. this.collisionFound = true;
  6878. this.collidedMesh = subMesh.getMesh();
  6879. }
  6880. }
  6881. };
  6882. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6883. for (var i = indexStart; i < indexEnd; i += 3) {
  6884. var p1 = pts[indices[i] - decal];
  6885. var p2 = pts[indices[i + 1] - decal];
  6886. var p3 = pts[indices[i + 2] - decal];
  6887. this._testTriangle(i, subMesh, p3, p2, p1);
  6888. }
  6889. };
  6890. Collider.prototype._getResponse = function (pos, vel) {
  6891. pos.addToRef(vel, this._destinationPoint);
  6892. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6893. this.basePoint.addToRef(vel, pos);
  6894. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6895. this._slidePlaneNormal.normalize();
  6896. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6897. pos.addInPlace(this._displacementVector);
  6898. this.intersectionPoint.addInPlace(this._displacementVector);
  6899. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6900. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6901. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6902. };
  6903. return Collider;
  6904. })();
  6905. BABYLON.Collider = Collider;
  6906. })(BABYLON || (BABYLON = {}));
  6907. //# sourceMappingURL=babylon.collider.js.map
  6908. var BABYLON;
  6909. (function (BABYLON) {
  6910. var Camera = (function (_super) {
  6911. __extends(Camera, _super);
  6912. function Camera(name, position, scene) {
  6913. _super.call(this, name, scene);
  6914. this.position = position;
  6915. // Members
  6916. this.upVector = BABYLON.Vector3.Up();
  6917. this.orthoLeft = null;
  6918. this.orthoRight = null;
  6919. this.orthoBottom = null;
  6920. this.orthoTop = null;
  6921. this.fov = 0.8;
  6922. this.minZ = 1.0;
  6923. this.maxZ = 10000.0;
  6924. this.inertia = 0.9;
  6925. this.mode = Camera.PERSPECTIVE_CAMERA;
  6926. this.isIntermediate = false;
  6927. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6928. this.subCameras = [];
  6929. this.layerMask = 0xFFFFFFFF;
  6930. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  6931. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6932. this._projectionMatrix = new BABYLON.Matrix();
  6933. this._postProcesses = new Array();
  6934. this._postProcessesTakenIndices = [];
  6935. this._activeMeshes = new BABYLON.SmartArray(256);
  6936. this._globalPosition = BABYLON.Vector3.Zero();
  6937. scene.addCamera(this);
  6938. if (!scene.activeCamera) {
  6939. scene.activeCamera = this;
  6940. }
  6941. }
  6942. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  6943. get: function () {
  6944. return Camera._PERSPECTIVE_CAMERA;
  6945. },
  6946. enumerable: true,
  6947. configurable: true
  6948. });
  6949. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  6950. get: function () {
  6951. return Camera._ORTHOGRAPHIC_CAMERA;
  6952. },
  6953. enumerable: true,
  6954. configurable: true
  6955. });
  6956. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  6957. get: function () {
  6958. return Camera._FOVMODE_VERTICAL_FIXED;
  6959. },
  6960. enumerable: true,
  6961. configurable: true
  6962. });
  6963. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  6964. get: function () {
  6965. return Camera._FOVMODE_HORIZONTAL_FIXED;
  6966. },
  6967. enumerable: true,
  6968. configurable: true
  6969. });
  6970. Object.defineProperty(Camera.prototype, "globalPosition", {
  6971. get: function () {
  6972. return this._globalPosition;
  6973. },
  6974. enumerable: true,
  6975. configurable: true
  6976. });
  6977. Camera.prototype.getActiveMeshes = function () {
  6978. return this._activeMeshes;
  6979. };
  6980. Camera.prototype.isActiveMesh = function (mesh) {
  6981. return (this._activeMeshes.indexOf(mesh) !== -1);
  6982. };
  6983. //Cache
  6984. Camera.prototype._initCache = function () {
  6985. _super.prototype._initCache.call(this);
  6986. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6987. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6988. this._cache.mode = undefined;
  6989. this._cache.minZ = undefined;
  6990. this._cache.maxZ = undefined;
  6991. this._cache.fov = undefined;
  6992. this._cache.aspectRatio = undefined;
  6993. this._cache.orthoLeft = undefined;
  6994. this._cache.orthoRight = undefined;
  6995. this._cache.orthoBottom = undefined;
  6996. this._cache.orthoTop = undefined;
  6997. this._cache.renderWidth = undefined;
  6998. this._cache.renderHeight = undefined;
  6999. };
  7000. Camera.prototype._updateCache = function (ignoreParentClass) {
  7001. if (!ignoreParentClass) {
  7002. _super.prototype._updateCache.call(this);
  7003. }
  7004. var engine = this.getEngine();
  7005. this._cache.position.copyFrom(this.position);
  7006. this._cache.upVector.copyFrom(this.upVector);
  7007. this._cache.mode = this.mode;
  7008. this._cache.minZ = this.minZ;
  7009. this._cache.maxZ = this.maxZ;
  7010. this._cache.fov = this.fov;
  7011. this._cache.aspectRatio = engine.getAspectRatio(this);
  7012. this._cache.orthoLeft = this.orthoLeft;
  7013. this._cache.orthoRight = this.orthoRight;
  7014. this._cache.orthoBottom = this.orthoBottom;
  7015. this._cache.orthoTop = this.orthoTop;
  7016. this._cache.renderWidth = engine.getRenderWidth();
  7017. this._cache.renderHeight = engine.getRenderHeight();
  7018. };
  7019. Camera.prototype._updateFromScene = function () {
  7020. this.updateCache();
  7021. this._update();
  7022. };
  7023. // Synchronized
  7024. Camera.prototype.isSynchronizedWithParent = function () {
  7025. return false;
  7026. };
  7027. Camera.prototype._isSynchronized = function () {
  7028. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  7029. };
  7030. Camera.prototype._isSynchronizedViewMatrix = function () {
  7031. if (!_super.prototype._isSynchronized.call(this))
  7032. return false;
  7033. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  7034. };
  7035. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  7036. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  7037. if (!check) {
  7038. return false;
  7039. }
  7040. var engine = this.getEngine();
  7041. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  7042. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  7043. }
  7044. else {
  7045. 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();
  7046. }
  7047. return check;
  7048. };
  7049. // Controls
  7050. Camera.prototype.attachControl = function (element) {
  7051. };
  7052. Camera.prototype.detachControl = function (element) {
  7053. };
  7054. Camera.prototype._update = function () {
  7055. };
  7056. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  7057. if (insertAt === void 0) { insertAt = null; }
  7058. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  7059. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  7060. return 0;
  7061. }
  7062. if (insertAt == null || insertAt < 0) {
  7063. this._postProcesses.push(postProcess);
  7064. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  7065. return this._postProcesses.length - 1;
  7066. }
  7067. var add = 0;
  7068. if (this._postProcesses[insertAt]) {
  7069. var start = this._postProcesses.length - 1;
  7070. for (var i = start; i >= insertAt + 1; --i) {
  7071. this._postProcesses[i + 1] = this._postProcesses[i];
  7072. }
  7073. add = 1;
  7074. }
  7075. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  7076. if (this._postProcessesTakenIndices[i] < insertAt) {
  7077. continue;
  7078. }
  7079. start = this._postProcessesTakenIndices.length - 1;
  7080. for (var j = start; j >= i; --j) {
  7081. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  7082. }
  7083. this._postProcessesTakenIndices[i] = insertAt;
  7084. break;
  7085. }
  7086. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  7087. this._postProcessesTakenIndices.push(insertAt);
  7088. }
  7089. var result = insertAt + add;
  7090. this._postProcesses[result] = postProcess;
  7091. return result;
  7092. };
  7093. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  7094. if (atIndices === void 0) { atIndices = null; }
  7095. var result = [];
  7096. if (!atIndices) {
  7097. var length = this._postProcesses.length;
  7098. for (var i = 0; i < length; i++) {
  7099. if (this._postProcesses[i] !== postProcess) {
  7100. continue;
  7101. }
  7102. delete this._postProcesses[i];
  7103. var index = this._postProcessesTakenIndices.indexOf(i);
  7104. this._postProcessesTakenIndices.splice(index, 1);
  7105. }
  7106. }
  7107. else {
  7108. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  7109. for (i = 0; i < atIndices.length; i++) {
  7110. var foundPostProcess = this._postProcesses[atIndices[i]];
  7111. if (foundPostProcess !== postProcess) {
  7112. result.push(i);
  7113. continue;
  7114. }
  7115. delete this._postProcesses[atIndices[i]];
  7116. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  7117. this._postProcessesTakenIndices.splice(index, 1);
  7118. }
  7119. }
  7120. return result;
  7121. };
  7122. Camera.prototype.getWorldMatrix = function () {
  7123. if (!this._worldMatrix) {
  7124. this._worldMatrix = BABYLON.Matrix.Identity();
  7125. }
  7126. var viewMatrix = this.getViewMatrix();
  7127. viewMatrix.invertToRef(this._worldMatrix);
  7128. return this._worldMatrix;
  7129. };
  7130. Camera.prototype._getViewMatrix = function () {
  7131. return BABYLON.Matrix.Identity();
  7132. };
  7133. Camera.prototype.getViewMatrix = function () {
  7134. this._computedViewMatrix = this._computeViewMatrix();
  7135. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  7136. this._globalPosition.copyFrom(this.position);
  7137. return this._computedViewMatrix;
  7138. }
  7139. if (!this._worldMatrix) {
  7140. this._worldMatrix = BABYLON.Matrix.Identity();
  7141. }
  7142. this._computedViewMatrix.invertToRef(this._worldMatrix);
  7143. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  7144. this._computedViewMatrix.invert();
  7145. this._currentRenderId = this.getScene().getRenderId();
  7146. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  7147. return this._computedViewMatrix;
  7148. };
  7149. Camera.prototype._computeViewMatrix = function (force) {
  7150. if (!force && this._isSynchronizedViewMatrix()) {
  7151. return this._computedViewMatrix;
  7152. }
  7153. this._computedViewMatrix = this._getViewMatrix();
  7154. if (!this.parent || !this.parent.getWorldMatrix) {
  7155. this._currentRenderId = this.getScene().getRenderId();
  7156. }
  7157. return this._computedViewMatrix;
  7158. };
  7159. Camera.prototype.getProjectionMatrix = function (force) {
  7160. if (!force && this._isSynchronizedProjectionMatrix()) {
  7161. return this._projectionMatrix;
  7162. }
  7163. var engine = this.getEngine();
  7164. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  7165. if (this.minZ <= 0) {
  7166. this.minZ = 0.1;
  7167. }
  7168. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  7169. return this._projectionMatrix;
  7170. }
  7171. var halfWidth = engine.getRenderWidth() / 2.0;
  7172. var halfHeight = engine.getRenderHeight() / 2.0;
  7173. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  7174. return this._projectionMatrix;
  7175. };
  7176. Camera.prototype.dispose = function () {
  7177. // Remove from scene
  7178. this.getScene().removeCamera(this);
  7179. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  7180. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  7181. }
  7182. };
  7183. // Statics
  7184. Camera._PERSPECTIVE_CAMERA = 0;
  7185. Camera._ORTHOGRAPHIC_CAMERA = 1;
  7186. Camera._FOVMODE_VERTICAL_FIXED = 0;
  7187. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  7188. return Camera;
  7189. })(BABYLON.Node);
  7190. BABYLON.Camera = Camera;
  7191. })(BABYLON || (BABYLON = {}));
  7192. //# sourceMappingURL=babylon.camera.js.map
  7193. var BABYLON;
  7194. (function (BABYLON) {
  7195. var TargetCamera = (function (_super) {
  7196. __extends(TargetCamera, _super);
  7197. function TargetCamera(name, position, scene) {
  7198. _super.call(this, name, position, scene);
  7199. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7200. this.cameraRotation = new BABYLON.Vector2(0, 0);
  7201. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7202. this.speed = 2.0;
  7203. this.noRotationConstraint = false;
  7204. this.lockedTarget = null;
  7205. this._currentTarget = BABYLON.Vector3.Zero();
  7206. this._viewMatrix = BABYLON.Matrix.Zero();
  7207. this._camMatrix = BABYLON.Matrix.Zero();
  7208. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  7209. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  7210. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  7211. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  7212. this._lookAtTemp = BABYLON.Matrix.Zero();
  7213. this._tempMatrix = BABYLON.Matrix.Zero();
  7214. }
  7215. TargetCamera.prototype._getLockedTargetPosition = function () {
  7216. if (!this.lockedTarget) {
  7217. return null;
  7218. }
  7219. return this.lockedTarget.position || this.lockedTarget;
  7220. };
  7221. // Cache
  7222. TargetCamera.prototype._initCache = function () {
  7223. _super.prototype._initCache.call(this);
  7224. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7225. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7226. };
  7227. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  7228. if (!ignoreParentClass) {
  7229. _super.prototype._updateCache.call(this);
  7230. }
  7231. var lockedTargetPosition = this._getLockedTargetPosition();
  7232. if (!lockedTargetPosition) {
  7233. this._cache.lockedTarget = null;
  7234. }
  7235. else {
  7236. if (!this._cache.lockedTarget) {
  7237. this._cache.lockedTarget = lockedTargetPosition.clone();
  7238. }
  7239. else {
  7240. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  7241. }
  7242. }
  7243. this._cache.rotation.copyFrom(this.rotation);
  7244. };
  7245. // Synchronized
  7246. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  7247. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  7248. return false;
  7249. }
  7250. var lockedTargetPosition = this._getLockedTargetPosition();
  7251. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  7252. };
  7253. // Methods
  7254. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  7255. var engine = this.getEngine();
  7256. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  7257. };
  7258. // Target
  7259. TargetCamera.prototype.setTarget = function (target) {
  7260. this.upVector.normalize();
  7261. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  7262. this._camMatrix.invert();
  7263. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  7264. var vDir = target.subtract(this.position);
  7265. if (vDir.x >= 0.0) {
  7266. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  7267. }
  7268. else {
  7269. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  7270. }
  7271. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  7272. if (isNaN(this.rotation.x)) {
  7273. this.rotation.x = 0;
  7274. }
  7275. if (isNaN(this.rotation.y)) {
  7276. this.rotation.y = 0;
  7277. }
  7278. if (isNaN(this.rotation.z)) {
  7279. this.rotation.z = 0;
  7280. }
  7281. };
  7282. TargetCamera.prototype.getTarget = function () {
  7283. return this._currentTarget;
  7284. };
  7285. TargetCamera.prototype._decideIfNeedsToMove = function () {
  7286. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7287. };
  7288. TargetCamera.prototype._updatePosition = function () {
  7289. this.position.addInPlace(this.cameraDirection);
  7290. };
  7291. TargetCamera.prototype._update = function () {
  7292. var needToMove = this._decideIfNeedsToMove();
  7293. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  7294. // Move
  7295. if (needToMove) {
  7296. this._updatePosition();
  7297. }
  7298. // Rotate
  7299. if (needToRotate) {
  7300. this.rotation.x += this.cameraRotation.x;
  7301. this.rotation.y += this.cameraRotation.y;
  7302. if (!this.noRotationConstraint) {
  7303. var limit = (Math.PI / 2) * 0.95;
  7304. if (this.rotation.x > limit)
  7305. this.rotation.x = limit;
  7306. if (this.rotation.x < -limit)
  7307. this.rotation.x = -limit;
  7308. }
  7309. }
  7310. // Inertia
  7311. if (needToMove) {
  7312. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  7313. this.cameraDirection.x = 0;
  7314. }
  7315. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  7316. this.cameraDirection.y = 0;
  7317. }
  7318. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  7319. this.cameraDirection.z = 0;
  7320. }
  7321. this.cameraDirection.scaleInPlace(this.inertia);
  7322. }
  7323. if (needToRotate) {
  7324. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  7325. this.cameraRotation.x = 0;
  7326. }
  7327. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  7328. this.cameraRotation.y = 0;
  7329. }
  7330. this.cameraRotation.scaleInPlace(this.inertia);
  7331. }
  7332. };
  7333. TargetCamera.prototype._getViewMatrix = function () {
  7334. if (!this.lockedTarget) {
  7335. // Compute
  7336. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  7337. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  7338. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  7339. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  7340. this._lookAtTemp.invert();
  7341. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  7342. }
  7343. else {
  7344. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  7345. }
  7346. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  7347. // Computing target and final matrix
  7348. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  7349. }
  7350. else {
  7351. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  7352. }
  7353. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  7354. return this._viewMatrix;
  7355. };
  7356. return TargetCamera;
  7357. })(BABYLON.Camera);
  7358. BABYLON.TargetCamera = TargetCamera;
  7359. })(BABYLON || (BABYLON = {}));
  7360. //# sourceMappingURL=babylon.targetCamera.js.map
  7361. var BABYLON;
  7362. (function (BABYLON) {
  7363. var FollowCamera = (function (_super) {
  7364. __extends(FollowCamera, _super);
  7365. function FollowCamera(name, position, scene) {
  7366. _super.call(this, name, position, scene);
  7367. this.radius = 12;
  7368. this.rotationOffset = 0;
  7369. this.heightOffset = 4;
  7370. this.cameraAcceleration = 0.05;
  7371. this.maxCameraSpeed = 20;
  7372. }
  7373. FollowCamera.prototype.getRadians = function (degrees) {
  7374. return degrees * Math.PI / 180;
  7375. };
  7376. FollowCamera.prototype.follow = function (cameraTarget) {
  7377. if (!cameraTarget)
  7378. return;
  7379. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  7380. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  7381. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  7382. var dx = targetX - this.position.x;
  7383. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  7384. var dz = (targetZ) - this.position.z;
  7385. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  7386. var vy = dy * this.cameraAcceleration;
  7387. var vz = dz * this.cameraAcceleration * 2;
  7388. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  7389. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7390. }
  7391. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  7392. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7393. }
  7394. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  7395. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7396. }
  7397. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  7398. this.setTarget(cameraTarget.position);
  7399. };
  7400. FollowCamera.prototype._update = function () {
  7401. _super.prototype._update.call(this);
  7402. this.follow(this.target);
  7403. };
  7404. return FollowCamera;
  7405. })(BABYLON.TargetCamera);
  7406. BABYLON.FollowCamera = FollowCamera;
  7407. })(BABYLON || (BABYLON = {}));
  7408. //# sourceMappingURL=babylon.followCamera.js.map
  7409. var BABYLON;
  7410. (function (BABYLON) {
  7411. var FreeCamera = (function (_super) {
  7412. __extends(FreeCamera, _super);
  7413. function FreeCamera(name, position, scene) {
  7414. _super.call(this, name, position, scene);
  7415. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7416. this.keysUp = [38];
  7417. this.keysDown = [40];
  7418. this.keysLeft = [37];
  7419. this.keysRight = [39];
  7420. this.checkCollisions = false;
  7421. this.applyGravity = false;
  7422. this.angularSensibility = 2000.0;
  7423. this._keys = [];
  7424. this._collider = new BABYLON.Collider();
  7425. this._needMoveForGravity = true;
  7426. this._oldPosition = BABYLON.Vector3.Zero();
  7427. this._diffPosition = BABYLON.Vector3.Zero();
  7428. this._newPosition = BABYLON.Vector3.Zero();
  7429. }
  7430. // Controls
  7431. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  7432. var _this = this;
  7433. var previousPosition;
  7434. var engine = this.getEngine();
  7435. if (this._attachedElement) {
  7436. return;
  7437. }
  7438. this._attachedElement = element;
  7439. if (this._onMouseDown === undefined) {
  7440. this._onMouseDown = function (evt) {
  7441. previousPosition = {
  7442. x: evt.clientX,
  7443. y: evt.clientY
  7444. };
  7445. if (!noPreventDefault) {
  7446. evt.preventDefault();
  7447. }
  7448. };
  7449. this._onMouseUp = function (evt) {
  7450. previousPosition = null;
  7451. if (!noPreventDefault) {
  7452. evt.preventDefault();
  7453. }
  7454. };
  7455. this._onMouseOut = function (evt) {
  7456. previousPosition = null;
  7457. _this._keys = [];
  7458. if (!noPreventDefault) {
  7459. evt.preventDefault();
  7460. }
  7461. };
  7462. this._onMouseMove = function (evt) {
  7463. if (!previousPosition && !engine.isPointerLock) {
  7464. return;
  7465. }
  7466. var offsetX;
  7467. var offsetY;
  7468. if (!engine.isPointerLock) {
  7469. offsetX = evt.clientX - previousPosition.x;
  7470. offsetY = evt.clientY - previousPosition.y;
  7471. }
  7472. else {
  7473. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7474. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7475. }
  7476. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  7477. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  7478. previousPosition = {
  7479. x: evt.clientX,
  7480. y: evt.clientY
  7481. };
  7482. if (!noPreventDefault) {
  7483. evt.preventDefault();
  7484. }
  7485. };
  7486. this._onKeyDown = function (evt) {
  7487. 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) {
  7488. var index = _this._keys.indexOf(evt.keyCode);
  7489. if (index === -1) {
  7490. _this._keys.push(evt.keyCode);
  7491. }
  7492. if (!noPreventDefault) {
  7493. evt.preventDefault();
  7494. }
  7495. }
  7496. };
  7497. this._onKeyUp = function (evt) {
  7498. 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) {
  7499. var index = _this._keys.indexOf(evt.keyCode);
  7500. if (index >= 0) {
  7501. _this._keys.splice(index, 1);
  7502. }
  7503. if (!noPreventDefault) {
  7504. evt.preventDefault();
  7505. }
  7506. }
  7507. };
  7508. this._onLostFocus = function () {
  7509. _this._keys = [];
  7510. };
  7511. this._reset = function () {
  7512. _this._keys = [];
  7513. previousPosition = null;
  7514. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7515. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  7516. };
  7517. }
  7518. element.addEventListener("mousedown", this._onMouseDown, false);
  7519. element.addEventListener("mouseup", this._onMouseUp, false);
  7520. element.addEventListener("mouseout", this._onMouseOut, false);
  7521. element.addEventListener("mousemove", this._onMouseMove, 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. FreeCamera.prototype.detachControl = function (element) {
  7529. if (this._attachedElement != element) {
  7530. return;
  7531. }
  7532. element.removeEventListener("mousedown", this._onMouseDown);
  7533. element.removeEventListener("mouseup", this._onMouseUp);
  7534. element.removeEventListener("mouseout", this._onMouseOut);
  7535. element.removeEventListener("mousemove", this._onMouseMove);
  7536. BABYLON.Tools.UnregisterTopRootEvents([
  7537. { name: "keydown", handler: this._onKeyDown },
  7538. { name: "keyup", handler: this._onKeyUp },
  7539. { name: "blur", handler: this._onLostFocus }
  7540. ]);
  7541. this._attachedElement = null;
  7542. if (this._reset) {
  7543. this._reset();
  7544. }
  7545. };
  7546. FreeCamera.prototype._collideWithWorld = function (velocity) {
  7547. var globalPosition;
  7548. if (this.parent) {
  7549. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  7550. }
  7551. else {
  7552. globalPosition = this.position;
  7553. }
  7554. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  7555. this._collider.radius = this.ellipsoid;
  7556. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  7557. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  7558. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  7559. this.position.addInPlace(this._diffPosition);
  7560. if (this.onCollide) {
  7561. this.onCollide(this._collider.collidedMesh);
  7562. }
  7563. }
  7564. };
  7565. FreeCamera.prototype._checkInputs = function () {
  7566. if (!this._localDirection) {
  7567. this._localDirection = BABYLON.Vector3.Zero();
  7568. this._transformedDirection = BABYLON.Vector3.Zero();
  7569. }
  7570. for (var index = 0; index < this._keys.length; index++) {
  7571. var keyCode = this._keys[index];
  7572. var speed = this._computeLocalCameraSpeed();
  7573. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7574. this._localDirection.copyFromFloats(-speed, 0, 0);
  7575. }
  7576. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7577. this._localDirection.copyFromFloats(0, 0, speed);
  7578. }
  7579. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7580. this._localDirection.copyFromFloats(speed, 0, 0);
  7581. }
  7582. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7583. this._localDirection.copyFromFloats(0, 0, -speed);
  7584. }
  7585. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  7586. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  7587. this.cameraDirection.addInPlace(this._transformedDirection);
  7588. }
  7589. };
  7590. FreeCamera.prototype._decideIfNeedsToMove = function () {
  7591. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7592. };
  7593. FreeCamera.prototype._updatePosition = function () {
  7594. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  7595. this._collideWithWorld(this.cameraDirection);
  7596. if (this.applyGravity) {
  7597. var oldPosition = this.position;
  7598. this._collideWithWorld(this.getScene().gravity);
  7599. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  7600. }
  7601. }
  7602. else {
  7603. this.position.addInPlace(this.cameraDirection);
  7604. }
  7605. };
  7606. FreeCamera.prototype._update = function () {
  7607. this._checkInputs();
  7608. _super.prototype._update.call(this);
  7609. };
  7610. return FreeCamera;
  7611. })(BABYLON.TargetCamera);
  7612. BABYLON.FreeCamera = FreeCamera;
  7613. })(BABYLON || (BABYLON = {}));
  7614. //# sourceMappingURL=babylon.freeCamera.js.map
  7615. var BABYLON;
  7616. (function (BABYLON) {
  7617. // We're mainly based on the logic defined into the FreeCamera code
  7618. var TouchCamera = (function (_super) {
  7619. __extends(TouchCamera, _super);
  7620. function TouchCamera(name, position, scene) {
  7621. _super.call(this, name, position, scene);
  7622. this._offsetX = null;
  7623. this._offsetY = null;
  7624. this._pointerCount = 0;
  7625. this._pointerPressed = [];
  7626. this.angularSensibility = 200000.0;
  7627. this.moveSensibility = 500.0;
  7628. }
  7629. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7630. var _this = this;
  7631. var previousPosition;
  7632. if (this._attachedCanvas) {
  7633. return;
  7634. }
  7635. this._attachedCanvas = canvas;
  7636. if (this._onPointerDown === undefined) {
  7637. this._onPointerDown = function (evt) {
  7638. if (!noPreventDefault) {
  7639. evt.preventDefault();
  7640. }
  7641. _this._pointerPressed.push(evt.pointerId);
  7642. if (_this._pointerPressed.length !== 1) {
  7643. return;
  7644. }
  7645. previousPosition = {
  7646. x: evt.clientX,
  7647. y: evt.clientY
  7648. };
  7649. };
  7650. this._onPointerUp = function (evt) {
  7651. if (!noPreventDefault) {
  7652. evt.preventDefault();
  7653. }
  7654. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7655. if (index === -1) {
  7656. return;
  7657. }
  7658. _this._pointerPressed.splice(index, 1);
  7659. if (index != 0) {
  7660. return;
  7661. }
  7662. previousPosition = null;
  7663. _this._offsetX = null;
  7664. _this._offsetY = null;
  7665. };
  7666. this._onPointerMove = function (evt) {
  7667. if (!noPreventDefault) {
  7668. evt.preventDefault();
  7669. }
  7670. if (!previousPosition) {
  7671. return;
  7672. }
  7673. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7674. if (index != 0) {
  7675. return;
  7676. }
  7677. _this._offsetX = evt.clientX - previousPosition.x;
  7678. _this._offsetY = -(evt.clientY - previousPosition.y);
  7679. };
  7680. this._onLostFocus = function () {
  7681. _this._offsetX = null;
  7682. _this._offsetY = null;
  7683. };
  7684. }
  7685. canvas.addEventListener("pointerdown", this._onPointerDown);
  7686. canvas.addEventListener("pointerup", this._onPointerUp);
  7687. canvas.addEventListener("pointerout", this._onPointerUp);
  7688. canvas.addEventListener("pointermove", this._onPointerMove);
  7689. BABYLON.Tools.RegisterTopRootEvents([
  7690. { name: "blur", handler: this._onLostFocus }
  7691. ]);
  7692. };
  7693. TouchCamera.prototype.detachControl = function (canvas) {
  7694. if (this._attachedCanvas != canvas) {
  7695. return;
  7696. }
  7697. canvas.removeEventListener("pointerdown", this._onPointerDown);
  7698. canvas.removeEventListener("pointerup", this._onPointerUp);
  7699. canvas.removeEventListener("pointerout", this._onPointerUp);
  7700. canvas.removeEventListener("pointermove", this._onPointerMove);
  7701. BABYLON.Tools.UnregisterTopRootEvents([
  7702. { name: "blur", handler: this._onLostFocus }
  7703. ]);
  7704. this._attachedCanvas = null;
  7705. };
  7706. TouchCamera.prototype._checkInputs = function () {
  7707. if (!this._offsetX) {
  7708. return;
  7709. }
  7710. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  7711. if (this._pointerPressed.length > 1) {
  7712. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  7713. }
  7714. else {
  7715. var speed = this._computeLocalCameraSpeed();
  7716. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7717. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7718. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7719. }
  7720. };
  7721. return TouchCamera;
  7722. })(BABYLON.FreeCamera);
  7723. BABYLON.TouchCamera = TouchCamera;
  7724. })(BABYLON || (BABYLON = {}));
  7725. //# sourceMappingURL=babylon.touchCamera.js.map
  7726. var BABYLON;
  7727. (function (BABYLON) {
  7728. // We're mainly based on the logic defined into the FreeCamera code
  7729. var DeviceOrientationCamera = (function (_super) {
  7730. __extends(DeviceOrientationCamera, _super);
  7731. function DeviceOrientationCamera(name, position, scene) {
  7732. var _this = this;
  7733. _super.call(this, name, position, scene);
  7734. this._offsetX = null;
  7735. this._offsetY = null;
  7736. this._orientationGamma = 0;
  7737. this._orientationBeta = 0;
  7738. this._initialOrientationGamma = 0;
  7739. this._initialOrientationBeta = 0;
  7740. this.angularSensibility = 10000.0;
  7741. this.moveSensibility = 50.0;
  7742. window.addEventListener("resize", function () {
  7743. _this._initialOrientationGamma = null;
  7744. }, false);
  7745. }
  7746. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7747. var _this = this;
  7748. if (this._attachedCanvas) {
  7749. return;
  7750. }
  7751. this._attachedCanvas = canvas;
  7752. if (!this._orientationChanged) {
  7753. this._orientationChanged = function (evt) {
  7754. if (!_this._initialOrientationGamma) {
  7755. _this._initialOrientationGamma = evt.gamma;
  7756. _this._initialOrientationBeta = evt.beta;
  7757. }
  7758. _this._orientationGamma = evt.gamma;
  7759. _this._orientationBeta = evt.beta;
  7760. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  7761. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  7762. };
  7763. }
  7764. window.addEventListener("deviceorientation", this._orientationChanged);
  7765. };
  7766. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  7767. if (this._attachedCanvas != canvas) {
  7768. return;
  7769. }
  7770. window.removeEventListener("deviceorientation", this._orientationChanged);
  7771. this._attachedCanvas = null;
  7772. this._orientationGamma = 0;
  7773. this._orientationBeta = 0;
  7774. this._initialOrientationGamma = 0;
  7775. this._initialOrientationBeta = 0;
  7776. };
  7777. DeviceOrientationCamera.prototype._checkInputs = function () {
  7778. if (!this._offsetX) {
  7779. return;
  7780. }
  7781. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  7782. var speed = this._computeLocalCameraSpeed();
  7783. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7784. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7785. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7786. };
  7787. return DeviceOrientationCamera;
  7788. })(BABYLON.FreeCamera);
  7789. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  7790. })(BABYLON || (BABYLON = {}));
  7791. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  7792. var BABYLON;
  7793. (function (BABYLON) {
  7794. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7795. var ArcRotateCamera = (function (_super) {
  7796. __extends(ArcRotateCamera, _super);
  7797. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  7798. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  7799. this.alpha = alpha;
  7800. this.beta = beta;
  7801. this.radius = radius;
  7802. this.target = target;
  7803. this.inertialAlphaOffset = 0;
  7804. this.inertialBetaOffset = 0;
  7805. this.inertialRadiusOffset = 0;
  7806. this.lowerAlphaLimit = null;
  7807. this.upperAlphaLimit = null;
  7808. this.lowerBetaLimit = 0.01;
  7809. this.upperBetaLimit = Math.PI;
  7810. this.lowerRadiusLimit = null;
  7811. this.upperRadiusLimit = null;
  7812. this.angularSensibility = 1000.0;
  7813. this.wheelPrecision = 3.0;
  7814. this.pinchPrecision = 2.0;
  7815. this.keysUp = [38];
  7816. this.keysDown = [40];
  7817. this.keysLeft = [37];
  7818. this.keysRight = [39];
  7819. this.zoomOnFactor = 1;
  7820. this.targetScreenOffset = BABYLON.Vector2.Zero();
  7821. this._keys = [];
  7822. this._viewMatrix = new BABYLON.Matrix();
  7823. this.checkCollisions = false;
  7824. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  7825. this._collider = new BABYLON.Collider();
  7826. this._previousPosition = BABYLON.Vector3.Zero();
  7827. this._collisionVelocity = BABYLON.Vector3.Zero();
  7828. this._newPosition = BABYLON.Vector3.Zero();
  7829. if (!this.target) {
  7830. this.target = BABYLON.Vector3.Zero();
  7831. }
  7832. this.getViewMatrix();
  7833. }
  7834. ArcRotateCamera.prototype._getTargetPosition = function () {
  7835. return this.target.position || this.target;
  7836. };
  7837. // Cache
  7838. ArcRotateCamera.prototype._initCache = function () {
  7839. _super.prototype._initCache.call(this);
  7840. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7841. this._cache.alpha = undefined;
  7842. this._cache.beta = undefined;
  7843. this._cache.radius = undefined;
  7844. this._cache.targetScreenOffset = undefined;
  7845. };
  7846. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  7847. if (!ignoreParentClass) {
  7848. _super.prototype._updateCache.call(this);
  7849. }
  7850. this._cache.target.copyFrom(this._getTargetPosition());
  7851. this._cache.alpha = this.alpha;
  7852. this._cache.beta = this.beta;
  7853. this._cache.radius = this.radius;
  7854. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7855. };
  7856. // Synchronized
  7857. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7858. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7859. return false;
  7860. 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);
  7861. };
  7862. // Methods
  7863. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7864. var _this = this;
  7865. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  7866. var previousPinchDistance = 0;
  7867. var pointers = new BABYLON.SmartCollection();
  7868. if (this._attachedElement) {
  7869. return;
  7870. }
  7871. this._attachedElement = element;
  7872. var engine = this.getEngine();
  7873. if (this._onPointerDown === undefined) {
  7874. this._onPointerDown = function (evt) {
  7875. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  7876. cacheSoloPointer = pointers.item(evt.pointerId);
  7877. if (!noPreventDefault) {
  7878. evt.preventDefault();
  7879. }
  7880. };
  7881. this._onPointerUp = function (evt) {
  7882. cacheSoloPointer = null;
  7883. previousPinchDistance = 0;
  7884. pointers.remove(evt.pointerId);
  7885. if (!noPreventDefault) {
  7886. evt.preventDefault();
  7887. }
  7888. };
  7889. this._onPointerMove = function (evt) {
  7890. if (!noPreventDefault) {
  7891. evt.preventDefault();
  7892. }
  7893. switch (pointers.count) {
  7894. case 1:
  7895. //var offsetX = evt.clientX - pointers.item(evt.pointerId).x;
  7896. //var offsetY = evt.clientY - pointers.item(evt.pointerId).y;
  7897. var offsetX = evt.clientX - cacheSoloPointer.x;
  7898. var offsetY = evt.clientY - cacheSoloPointer.y;
  7899. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7900. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7901. //pointers.item(evt.pointerId).x = evt.clientX;
  7902. //pointers.item(evt.pointerId).y = evt.clientY;
  7903. cacheSoloPointer.x = evt.clientX;
  7904. cacheSoloPointer.y = evt.clientY;
  7905. break;
  7906. case 2:
  7907. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  7908. pointers.item(evt.pointerId).x = evt.clientX;
  7909. pointers.item(evt.pointerId).y = evt.clientY;
  7910. var direction = 1;
  7911. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  7912. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  7913. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  7914. if (previousPinchDistance === 0) {
  7915. previousPinchDistance = pinchSquaredDistance;
  7916. return;
  7917. }
  7918. if (pinchSquaredDistance !== previousPinchDistance) {
  7919. if (pinchSquaredDistance > previousPinchDistance) {
  7920. direction = -1;
  7921. }
  7922. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * _this.angularSensibility);
  7923. previousPinchDistance = pinchSquaredDistance;
  7924. }
  7925. break;
  7926. default:
  7927. if (pointers.item(evt.pointerId)) {
  7928. pointers.item(evt.pointerId).x = evt.clientX;
  7929. pointers.item(evt.pointerId).y = evt.clientY;
  7930. }
  7931. }
  7932. };
  7933. this._onMouseMove = function (evt) {
  7934. if (!engine.isPointerLock) {
  7935. return;
  7936. }
  7937. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7938. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7939. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7940. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7941. if (!noPreventDefault) {
  7942. evt.preventDefault();
  7943. }
  7944. };
  7945. this._wheel = function (event) {
  7946. var delta = 0;
  7947. if (event.wheelDelta) {
  7948. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7949. }
  7950. else if (event.detail) {
  7951. delta = -event.detail / _this.wheelPrecision;
  7952. }
  7953. if (delta)
  7954. _this.inertialRadiusOffset += delta;
  7955. if (event.preventDefault) {
  7956. if (!noPreventDefault) {
  7957. event.preventDefault();
  7958. }
  7959. }
  7960. };
  7961. this._onKeyDown = function (evt) {
  7962. 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) {
  7963. var index = _this._keys.indexOf(evt.keyCode);
  7964. if (index === -1) {
  7965. _this._keys.push(evt.keyCode);
  7966. }
  7967. if (evt.preventDefault) {
  7968. if (!noPreventDefault) {
  7969. evt.preventDefault();
  7970. }
  7971. }
  7972. }
  7973. };
  7974. this._onKeyUp = function (evt) {
  7975. 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) {
  7976. var index = _this._keys.indexOf(evt.keyCode);
  7977. if (index >= 0) {
  7978. _this._keys.splice(index, 1);
  7979. }
  7980. if (evt.preventDefault) {
  7981. if (!noPreventDefault) {
  7982. evt.preventDefault();
  7983. }
  7984. }
  7985. }
  7986. };
  7987. this._onLostFocus = function () {
  7988. _this._keys = [];
  7989. pointers.empty();
  7990. previousPinchDistance = 0;
  7991. cacheSoloPointer = null;
  7992. };
  7993. this._onGestureStart = function (e) {
  7994. if (window.MSGesture === undefined) {
  7995. return;
  7996. }
  7997. if (!_this._MSGestureHandler) {
  7998. _this._MSGestureHandler = new MSGesture();
  7999. _this._MSGestureHandler.target = element;
  8000. }
  8001. _this._MSGestureHandler.addPointer(e.pointerId);
  8002. };
  8003. this._onGesture = function (e) {
  8004. _this.radius *= e.scale;
  8005. if (e.preventDefault) {
  8006. if (!noPreventDefault) {
  8007. e.stopPropagation();
  8008. e.preventDefault();
  8009. }
  8010. }
  8011. };
  8012. this._reset = function () {
  8013. _this._keys = [];
  8014. _this.inertialAlphaOffset = 0;
  8015. _this.inertialBetaOffset = 0;
  8016. _this.inertialRadiusOffset = 0;
  8017. pointers.empty();
  8018. previousPinchDistance = 0;
  8019. cacheSoloPointer = null;
  8020. };
  8021. }
  8022. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  8023. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  8024. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  8025. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  8026. element.addEventListener("mousemove", this._onMouseMove, false);
  8027. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  8028. element.addEventListener("MSGestureChange", this._onGesture, false);
  8029. element.addEventListener('mousewheel', this._wheel, false);
  8030. element.addEventListener('DOMMouseScroll', this._wheel, false);
  8031. BABYLON.Tools.RegisterTopRootEvents([
  8032. { name: "keydown", handler: this._onKeyDown },
  8033. { name: "keyup", handler: this._onKeyUp },
  8034. { name: "blur", handler: this._onLostFocus }
  8035. ]);
  8036. };
  8037. ArcRotateCamera.prototype.detachControl = function (element) {
  8038. if (this._attachedElement !== element) {
  8039. return;
  8040. }
  8041. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  8042. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  8043. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  8044. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  8045. element.removeEventListener("mousemove", this._onMouseMove);
  8046. element.removeEventListener("MSPointerDown", this._onGestureStart);
  8047. element.removeEventListener("MSGestureChange", this._onGesture);
  8048. element.removeEventListener('mousewheel', this._wheel);
  8049. element.removeEventListener('DOMMouseScroll', this._wheel);
  8050. BABYLON.Tools.UnregisterTopRootEvents([
  8051. { name: "keydown", handler: this._onKeyDown },
  8052. { name: "keyup", handler: this._onKeyUp },
  8053. { name: "blur", handler: this._onLostFocus }
  8054. ]);
  8055. this._MSGestureHandler = null;
  8056. this._attachedElement = null;
  8057. if (this._reset) {
  8058. this._reset();
  8059. }
  8060. };
  8061. ArcRotateCamera.prototype._update = function () {
  8062. for (var index = 0; index < this._keys.length; index++) {
  8063. var keyCode = this._keys[index];
  8064. if (this.keysLeft.indexOf(keyCode) !== -1) {
  8065. this.inertialAlphaOffset -= 0.01;
  8066. }
  8067. else if (this.keysUp.indexOf(keyCode) !== -1) {
  8068. this.inertialBetaOffset -= 0.01;
  8069. }
  8070. else if (this.keysRight.indexOf(keyCode) !== -1) {
  8071. this.inertialAlphaOffset += 0.01;
  8072. }
  8073. else if (this.keysDown.indexOf(keyCode) !== -1) {
  8074. this.inertialBetaOffset += 0.01;
  8075. }
  8076. }
  8077. // Inertia
  8078. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  8079. this.alpha += this.inertialAlphaOffset;
  8080. this.beta += this.inertialBetaOffset;
  8081. this.radius -= this.inertialRadiusOffset;
  8082. this.inertialAlphaOffset *= this.inertia;
  8083. this.inertialBetaOffset *= this.inertia;
  8084. this.inertialRadiusOffset *= this.inertia;
  8085. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  8086. this.inertialAlphaOffset = 0;
  8087. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  8088. this.inertialBetaOffset = 0;
  8089. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  8090. this.inertialRadiusOffset = 0;
  8091. }
  8092. // Limits
  8093. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  8094. this.alpha = this.lowerAlphaLimit;
  8095. }
  8096. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  8097. this.alpha = this.upperAlphaLimit;
  8098. }
  8099. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  8100. this.beta = this.lowerBetaLimit;
  8101. }
  8102. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  8103. this.beta = this.upperBetaLimit;
  8104. }
  8105. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  8106. this.radius = this.lowerRadiusLimit;
  8107. }
  8108. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  8109. this.radius = this.upperRadiusLimit;
  8110. }
  8111. };
  8112. ArcRotateCamera.prototype.setPosition = function (position) {
  8113. var radiusv3 = position.subtract(this._getTargetPosition());
  8114. this.radius = radiusv3.length();
  8115. // Alpha
  8116. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  8117. if (radiusv3.z < 0) {
  8118. this.alpha = 2 * Math.PI - this.alpha;
  8119. }
  8120. // Beta
  8121. this.beta = Math.acos(radiusv3.y / this.radius);
  8122. };
  8123. ArcRotateCamera.prototype._getViewMatrix = function () {
  8124. // Compute
  8125. var cosa = Math.cos(this.alpha);
  8126. var sina = Math.sin(this.alpha);
  8127. var cosb = Math.cos(this.beta);
  8128. var sinb = Math.sin(this.beta);
  8129. var target = this._getTargetPosition();
  8130. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  8131. if (this.checkCollisions) {
  8132. this._collider.radius = this.collisionRadius;
  8133. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  8134. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  8135. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  8136. this.position.copyFrom(this._previousPosition);
  8137. this.alpha = this._previousAlpha;
  8138. this.beta = this._previousBeta;
  8139. this.radius = this._previousRadius;
  8140. if (this.onCollide) {
  8141. this.onCollide(this._collider.collidedMesh);
  8142. }
  8143. }
  8144. }
  8145. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  8146. this._previousAlpha = this.alpha;
  8147. this._previousBeta = this.beta;
  8148. this._previousRadius = this.radius;
  8149. this._previousPosition.copyFrom(this.position);
  8150. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  8151. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  8152. return this._viewMatrix;
  8153. };
  8154. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  8155. meshes = meshes || this.getScene().meshes;
  8156. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  8157. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  8158. this.radius = distance * this.zoomOnFactor;
  8159. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  8160. };
  8161. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  8162. var meshesOrMinMaxVector;
  8163. var distance;
  8164. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  8165. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  8166. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  8167. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  8168. }
  8169. else {
  8170. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  8171. distance = meshesOrMinMaxVectorAndDistance.distance;
  8172. }
  8173. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  8174. this.maxZ = distance * 2;
  8175. };
  8176. return ArcRotateCamera;
  8177. })(BABYLON.Camera);
  8178. BABYLON.ArcRotateCamera = ArcRotateCamera;
  8179. })(BABYLON || (BABYLON = {}));
  8180. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  8181. (function (BABYLON) {
  8182. /**
  8183. * Represents a scene to be rendered by the engine.
  8184. * @see http://doc.babylonjs.com/page.php?p=21911
  8185. */
  8186. var Scene = (function () {
  8187. /**
  8188. * @constructor
  8189. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  8190. */
  8191. function Scene(engine) {
  8192. // Members
  8193. this.autoClear = true;
  8194. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  8195. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  8196. this.forceWireframe = false;
  8197. this.forcePointsCloud = false;
  8198. this.forceShowBoundingBoxes = false;
  8199. this.animationsEnabled = true;
  8200. 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
  8201. // Fog
  8202. /**
  8203. * is fog enabled on this scene.
  8204. * @type {boolean}
  8205. */
  8206. this.fogEnabled = true;
  8207. this.fogMode = Scene.FOGMODE_NONE;
  8208. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  8209. this.fogDensity = 0.1;
  8210. this.fogStart = 0;
  8211. this.fogEnd = 1000.0;
  8212. // Lights
  8213. /**
  8214. * is shadow enabled on this scene.
  8215. * @type {boolean}
  8216. */
  8217. this.shadowsEnabled = true;
  8218. /**
  8219. * is light enabled on this scene.
  8220. * @type {boolean}
  8221. */
  8222. this.lightsEnabled = true;
  8223. /**
  8224. * All of the lights added to this scene.
  8225. * @see BABYLON.Light
  8226. * @type {BABYLON.Light[]}
  8227. */
  8228. this.lights = new Array();
  8229. // Cameras
  8230. /**
  8231. * All of the cameras added to this scene.
  8232. * @see BABYLON.Camera
  8233. * @type {BABYLON.Camera[]}
  8234. */
  8235. this.cameras = new Array();
  8236. this.activeCameras = new Array();
  8237. // Meshes
  8238. /**
  8239. * All of the (abstract) meshes added to this scene.
  8240. * @see BABYLON.AbstractMesh
  8241. * @type {BABYLON.AbstractMesh[]}
  8242. */
  8243. this.meshes = new Array();
  8244. // Geometries
  8245. this._geometries = new Array();
  8246. this.materials = new Array();
  8247. this.multiMaterials = new Array();
  8248. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  8249. // Textures
  8250. this.texturesEnabled = true;
  8251. this.textures = new Array();
  8252. // Particles
  8253. this.particlesEnabled = true;
  8254. this.particleSystems = new Array();
  8255. // Sprites
  8256. this.spritesEnabled = true;
  8257. this.spriteManagers = new Array();
  8258. // Layers
  8259. this.layers = new Array();
  8260. // Skeletons
  8261. this.skeletonsEnabled = true;
  8262. this.skeletons = new Array();
  8263. // Lens flares
  8264. this.lensFlaresEnabled = true;
  8265. this.lensFlareSystems = new Array();
  8266. // Collisions
  8267. this.collisionsEnabled = true;
  8268. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  8269. // Postprocesses
  8270. this.postProcessesEnabled = true;
  8271. // Customs render targets
  8272. this.renderTargetsEnabled = true;
  8273. this.dumpNextRenderTargets = false;
  8274. this.customRenderTargets = new Array();
  8275. // Imported meshes
  8276. this.importedMeshesFiles = new Array();
  8277. this._actionManagers = new Array();
  8278. this._meshesForIntersections = new BABYLON.SmartArray(256);
  8279. // Procedural textures
  8280. this.proceduralTexturesEnabled = true;
  8281. this._proceduralTextures = new Array();
  8282. this.soundTracks = new Array();
  8283. this._audioEnabled = true;
  8284. this._headphone = false;
  8285. this._totalVertices = 0;
  8286. this._activeVertices = 0;
  8287. this._activeParticles = 0;
  8288. this._lastFrameDuration = 0;
  8289. this._evaluateActiveMeshesDuration = 0;
  8290. this._renderTargetsDuration = 0;
  8291. this._particlesDuration = 0;
  8292. this._renderDuration = 0;
  8293. this._spritesDuration = 0;
  8294. this._animationRatio = 0;
  8295. this._renderId = 0;
  8296. this._executeWhenReadyTimeoutId = -1;
  8297. this._toBeDisposed = new BABYLON.SmartArray(256);
  8298. this._onReadyCallbacks = new Array();
  8299. this._pendingData = []; //ANY
  8300. this._onBeforeRenderCallbacks = new Array();
  8301. this._onAfterRenderCallbacks = new Array();
  8302. this._activeMeshes = new BABYLON.SmartArray(256);
  8303. this._processedMaterials = new BABYLON.SmartArray(256);
  8304. this._renderTargets = new BABYLON.SmartArray(256);
  8305. this._activeParticleSystems = new BABYLON.SmartArray(256);
  8306. this._activeSkeletons = new BABYLON.SmartArray(32);
  8307. this._activeBones = 0;
  8308. this._activeAnimatables = new Array();
  8309. this._transformMatrix = BABYLON.Matrix.Zero();
  8310. this._scaledPosition = BABYLON.Vector3.Zero();
  8311. this._scaledVelocity = BABYLON.Vector3.Zero();
  8312. this._uniqueIdCounter = 0;
  8313. this._engine = engine;
  8314. engine.scenes.push(this);
  8315. this._renderingManager = new BABYLON.RenderingManager(this);
  8316. this.postProcessManager = new BABYLON.PostProcessManager(this);
  8317. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  8318. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  8319. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  8320. this.attachControl();
  8321. this._debugLayer = new BABYLON.DebugLayer(this);
  8322. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  8323. //simplification queue
  8324. this.simplificationQueue = new BABYLON.SimplificationQueue();
  8325. }
  8326. Object.defineProperty(Scene, "FOGMODE_NONE", {
  8327. get: function () {
  8328. return Scene._FOGMODE_NONE;
  8329. },
  8330. enumerable: true,
  8331. configurable: true
  8332. });
  8333. Object.defineProperty(Scene, "FOGMODE_EXP", {
  8334. get: function () {
  8335. return Scene._FOGMODE_EXP;
  8336. },
  8337. enumerable: true,
  8338. configurable: true
  8339. });
  8340. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  8341. get: function () {
  8342. return Scene._FOGMODE_EXP2;
  8343. },
  8344. enumerable: true,
  8345. configurable: true
  8346. });
  8347. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  8348. get: function () {
  8349. return Scene._FOGMODE_LINEAR;
  8350. },
  8351. enumerable: true,
  8352. configurable: true
  8353. });
  8354. Object.defineProperty(Scene.prototype, "debugLayer", {
  8355. // Properties
  8356. get: function () {
  8357. return this._debugLayer;
  8358. },
  8359. enumerable: true,
  8360. configurable: true
  8361. });
  8362. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  8363. /**
  8364. * The mesh that is currently under the pointer.
  8365. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  8366. */
  8367. get: function () {
  8368. return this._meshUnderPointer;
  8369. },
  8370. enumerable: true,
  8371. configurable: true
  8372. });
  8373. Object.defineProperty(Scene.prototype, "pointerX", {
  8374. /**
  8375. * Current on-screen X position of the pointer
  8376. * @return {number} X position of the pointer
  8377. */
  8378. get: function () {
  8379. return this._pointerX;
  8380. },
  8381. enumerable: true,
  8382. configurable: true
  8383. });
  8384. Object.defineProperty(Scene.prototype, "pointerY", {
  8385. /**
  8386. * Current on-screen Y position of the pointer
  8387. * @return {number} Y position of the pointer
  8388. */
  8389. get: function () {
  8390. return this._pointerY;
  8391. },
  8392. enumerable: true,
  8393. configurable: true
  8394. });
  8395. Scene.prototype.getCachedMaterial = function () {
  8396. return this._cachedMaterial;
  8397. };
  8398. Scene.prototype.getBoundingBoxRenderer = function () {
  8399. return this._boundingBoxRenderer;
  8400. };
  8401. Scene.prototype.getOutlineRenderer = function () {
  8402. return this._outlineRenderer;
  8403. };
  8404. Scene.prototype.getEngine = function () {
  8405. return this._engine;
  8406. };
  8407. Scene.prototype.getTotalVertices = function () {
  8408. return this._totalVertices;
  8409. };
  8410. Scene.prototype.getActiveVertices = function () {
  8411. return this._activeVertices;
  8412. };
  8413. Scene.prototype.getActiveParticles = function () {
  8414. return this._activeParticles;
  8415. };
  8416. Scene.prototype.getActiveBones = function () {
  8417. return this._activeBones;
  8418. };
  8419. // Stats
  8420. Scene.prototype.getLastFrameDuration = function () {
  8421. return this._lastFrameDuration;
  8422. };
  8423. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  8424. return this._evaluateActiveMeshesDuration;
  8425. };
  8426. Scene.prototype.getActiveMeshes = function () {
  8427. return this._activeMeshes;
  8428. };
  8429. Scene.prototype.getRenderTargetsDuration = function () {
  8430. return this._renderTargetsDuration;
  8431. };
  8432. Scene.prototype.getRenderDuration = function () {
  8433. return this._renderDuration;
  8434. };
  8435. Scene.prototype.getParticlesDuration = function () {
  8436. return this._particlesDuration;
  8437. };
  8438. Scene.prototype.getSpritesDuration = function () {
  8439. return this._spritesDuration;
  8440. };
  8441. Scene.prototype.getAnimationRatio = function () {
  8442. return this._animationRatio;
  8443. };
  8444. Scene.prototype.getRenderId = function () {
  8445. return this._renderId;
  8446. };
  8447. Scene.prototype.incrementRenderId = function () {
  8448. this._renderId++;
  8449. };
  8450. Scene.prototype._updatePointerPosition = function (evt) {
  8451. var canvasRect = this._engine.getRenderingCanvasClientRect();
  8452. this._pointerX = evt.clientX - canvasRect.left;
  8453. this._pointerY = evt.clientY - canvasRect.top;
  8454. if (this.cameraToUseForPointers) {
  8455. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  8456. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  8457. }
  8458. };
  8459. // Pointers handling
  8460. Scene.prototype.attachControl = function () {
  8461. var _this = this;
  8462. this._onPointerMove = function (evt) {
  8463. var canvas = _this._engine.getRenderingCanvas();
  8464. _this._updatePointerPosition(evt);
  8465. 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);
  8466. if (pickResult.hit) {
  8467. _this._meshUnderPointer = pickResult.pickedMesh;
  8468. _this.setPointerOverMesh(pickResult.pickedMesh);
  8469. canvas.style.cursor = "pointer";
  8470. }
  8471. else {
  8472. _this.setPointerOverMesh(null);
  8473. canvas.style.cursor = "";
  8474. _this._meshUnderPointer = null;
  8475. }
  8476. };
  8477. this._onPointerDown = function (evt) {
  8478. var predicate = null;
  8479. if (!_this.onPointerDown) {
  8480. predicate = function (mesh) {
  8481. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  8482. };
  8483. }
  8484. _this._updatePointerPosition(evt);
  8485. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  8486. if (pickResult.hit) {
  8487. if (pickResult.pickedMesh.actionManager) {
  8488. switch (evt.button) {
  8489. case 0:
  8490. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8491. break;
  8492. case 1:
  8493. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8494. break;
  8495. case 2:
  8496. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8497. break;
  8498. }
  8499. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8500. }
  8501. }
  8502. if (_this.onPointerDown) {
  8503. _this.onPointerDown(evt, pickResult);
  8504. }
  8505. };
  8506. this._onKeyDown = function (evt) {
  8507. if (_this.actionManager) {
  8508. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8509. }
  8510. };
  8511. this._onKeyUp = function (evt) {
  8512. if (_this.actionManager) {
  8513. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8514. }
  8515. };
  8516. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8517. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  8518. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  8519. BABYLON.Tools.RegisterTopRootEvents([
  8520. { name: "keydown", handler: this._onKeyDown },
  8521. { name: "keyup", handler: this._onKeyUp }
  8522. ]);
  8523. };
  8524. Scene.prototype.detachControl = function () {
  8525. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8526. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  8527. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  8528. BABYLON.Tools.UnregisterTopRootEvents([
  8529. { name: "keydown", handler: this._onKeyDown },
  8530. { name: "keyup", handler: this._onKeyUp }
  8531. ]);
  8532. };
  8533. // Ready
  8534. Scene.prototype.isReady = function () {
  8535. if (this._pendingData.length > 0) {
  8536. return false;
  8537. }
  8538. for (var index = 0; index < this._geometries.length; index++) {
  8539. var geometry = this._geometries[index];
  8540. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8541. return false;
  8542. }
  8543. }
  8544. for (index = 0; index < this.meshes.length; index++) {
  8545. var mesh = this.meshes[index];
  8546. if (!mesh.isReady()) {
  8547. return false;
  8548. }
  8549. var mat = mesh.material;
  8550. if (mat) {
  8551. if (!mat.isReady(mesh)) {
  8552. return false;
  8553. }
  8554. }
  8555. }
  8556. return true;
  8557. };
  8558. Scene.prototype.resetCachedMaterial = function () {
  8559. this._cachedMaterial = null;
  8560. };
  8561. Scene.prototype.registerBeforeRender = function (func) {
  8562. this._onBeforeRenderCallbacks.push(func);
  8563. };
  8564. Scene.prototype.unregisterBeforeRender = function (func) {
  8565. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8566. if (index > -1) {
  8567. this._onBeforeRenderCallbacks.splice(index, 1);
  8568. }
  8569. };
  8570. Scene.prototype.registerAfterRender = function (func) {
  8571. this._onAfterRenderCallbacks.push(func);
  8572. };
  8573. Scene.prototype.unregisterAfterRender = function (func) {
  8574. var index = this._onAfterRenderCallbacks.indexOf(func);
  8575. if (index > -1) {
  8576. this._onAfterRenderCallbacks.splice(index, 1);
  8577. }
  8578. };
  8579. Scene.prototype._addPendingData = function (data) {
  8580. this._pendingData.push(data);
  8581. };
  8582. Scene.prototype._removePendingData = function (data) {
  8583. var index = this._pendingData.indexOf(data);
  8584. if (index !== -1) {
  8585. this._pendingData.splice(index, 1);
  8586. }
  8587. };
  8588. Scene.prototype.getWaitingItemsCount = function () {
  8589. return this._pendingData.length;
  8590. };
  8591. /**
  8592. * Registers a function to be executed when the scene is ready.
  8593. * @param {Function} func - the function to be executed.
  8594. */
  8595. Scene.prototype.executeWhenReady = function (func) {
  8596. var _this = this;
  8597. this._onReadyCallbacks.push(func);
  8598. if (this._executeWhenReadyTimeoutId !== -1) {
  8599. return;
  8600. }
  8601. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8602. _this._checkIsReady();
  8603. }, 150);
  8604. };
  8605. Scene.prototype._checkIsReady = function () {
  8606. var _this = this;
  8607. if (this.isReady()) {
  8608. this._onReadyCallbacks.forEach(function (func) {
  8609. func();
  8610. });
  8611. this._onReadyCallbacks = [];
  8612. this._executeWhenReadyTimeoutId = -1;
  8613. return;
  8614. }
  8615. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8616. _this._checkIsReady();
  8617. }, 150);
  8618. };
  8619. // Animations
  8620. /**
  8621. * Will start the animation sequence of a given target
  8622. * @param target - the target
  8623. * @param {number} from - from which frame should animation start
  8624. * @param {number} to - till which frame should animation run.
  8625. * @param {boolean} [loop] - should the animation loop
  8626. * @param {number} [speedRatio] - the speed in which to run the animation
  8627. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  8628. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  8629. * @return {BABYLON.Animatable} the animatable object created for this animation
  8630. * @see BABYLON.Animatable
  8631. * @see http://doc.babylonjs.com/page.php?p=22081
  8632. */
  8633. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  8634. if (speedRatio === undefined) {
  8635. speedRatio = 1.0;
  8636. }
  8637. this.stopAnimation(target);
  8638. if (!animatable) {
  8639. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  8640. }
  8641. // Local animations
  8642. if (target.animations) {
  8643. animatable.appendAnimations(target, target.animations);
  8644. }
  8645. // Children animations
  8646. if (target.getAnimatables) {
  8647. var animatables = target.getAnimatables();
  8648. for (var index = 0; index < animatables.length; index++) {
  8649. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  8650. }
  8651. }
  8652. return animatable;
  8653. };
  8654. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  8655. if (speedRatio === undefined) {
  8656. speedRatio = 1.0;
  8657. }
  8658. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  8659. return animatable;
  8660. };
  8661. Scene.prototype.getAnimatableByTarget = function (target) {
  8662. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8663. if (this._activeAnimatables[index].target === target) {
  8664. return this._activeAnimatables[index];
  8665. }
  8666. }
  8667. return null;
  8668. };
  8669. /**
  8670. * Will stop the animation of the given target
  8671. * @param target - the target
  8672. * @see beginAnimation
  8673. */
  8674. Scene.prototype.stopAnimation = function (target) {
  8675. var animatable = this.getAnimatableByTarget(target);
  8676. if (animatable) {
  8677. animatable.stop();
  8678. }
  8679. };
  8680. Scene.prototype._animate = function () {
  8681. if (!this.animationsEnabled) {
  8682. return;
  8683. }
  8684. if (!this._animationStartDate) {
  8685. this._animationStartDate = BABYLON.Tools.Now;
  8686. }
  8687. // Getting time
  8688. var now = BABYLON.Tools.Now;
  8689. var delay = now - this._animationStartDate;
  8690. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8691. this._activeAnimatables[index]._animate(delay);
  8692. }
  8693. };
  8694. // Matrix
  8695. Scene.prototype.getViewMatrix = function () {
  8696. return this._viewMatrix;
  8697. };
  8698. Scene.prototype.getProjectionMatrix = function () {
  8699. return this._projectionMatrix;
  8700. };
  8701. Scene.prototype.getTransformMatrix = function () {
  8702. return this._transformMatrix;
  8703. };
  8704. Scene.prototype.setTransformMatrix = function (view, projection) {
  8705. this._viewMatrix = view;
  8706. this._projectionMatrix = projection;
  8707. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8708. };
  8709. // Methods
  8710. Scene.prototype.addMesh = function (newMesh) {
  8711. newMesh.uniqueId = this._uniqueIdCounter++;
  8712. var position = this.meshes.push(newMesh);
  8713. if (this.onNewMeshAdded) {
  8714. this.onNewMeshAdded(newMesh, position, this);
  8715. }
  8716. };
  8717. Scene.prototype.removeMesh = function (toRemove) {
  8718. var index = this.meshes.indexOf(toRemove);
  8719. if (index !== -1) {
  8720. // Remove from the scene if mesh found
  8721. this.meshes.splice(index, 1);
  8722. }
  8723. if (this.onMeshRemoved) {
  8724. this.onMeshRemoved(toRemove);
  8725. }
  8726. return index;
  8727. };
  8728. Scene.prototype.removeLight = function (toRemove) {
  8729. var index = this.lights.indexOf(toRemove);
  8730. if (index !== -1) {
  8731. // Remove from the scene if mesh found
  8732. this.lights.splice(index, 1);
  8733. }
  8734. if (this.onLightRemoved) {
  8735. this.onLightRemoved(toRemove);
  8736. }
  8737. return index;
  8738. };
  8739. Scene.prototype.removeCamera = function (toRemove) {
  8740. var index = this.cameras.indexOf(toRemove);
  8741. if (index !== -1) {
  8742. // Remove from the scene if mesh found
  8743. this.cameras.splice(index, 1);
  8744. }
  8745. if (this.onCameraRemoved) {
  8746. this.onCameraRemoved(toRemove);
  8747. }
  8748. return index;
  8749. };
  8750. Scene.prototype.addLight = function (newLight) {
  8751. newLight.uniqueId = this._uniqueIdCounter++;
  8752. var position = this.lights.push(newLight);
  8753. if (this.onNewLightAdded) {
  8754. this.onNewLightAdded(newLight, position, this);
  8755. }
  8756. };
  8757. Scene.prototype.addCamera = function (newCamera) {
  8758. newCamera.uniqueId = this._uniqueIdCounter++;
  8759. var position = this.cameras.push(newCamera);
  8760. if (this.onNewCameraAdded) {
  8761. this.onNewCameraAdded(newCamera, position, this);
  8762. }
  8763. };
  8764. /**
  8765. * sets the active camera of the scene using its ID
  8766. * @param {string} id - the camera's ID
  8767. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8768. * @see activeCamera
  8769. */
  8770. Scene.prototype.setActiveCameraByID = function (id) {
  8771. var camera = this.getCameraByID(id);
  8772. if (camera) {
  8773. this.activeCamera = camera;
  8774. return camera;
  8775. }
  8776. return null;
  8777. };
  8778. /**
  8779. * sets the active camera of the scene using its name
  8780. * @param {string} name - the camera's name
  8781. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8782. * @see activeCamera
  8783. */
  8784. Scene.prototype.setActiveCameraByName = function (name) {
  8785. var camera = this.getCameraByName(name);
  8786. if (camera) {
  8787. this.activeCamera = camera;
  8788. return camera;
  8789. }
  8790. return null;
  8791. };
  8792. /**
  8793. * get a material using its id
  8794. * @param {string} the material's ID
  8795. * @return {BABYLON.Material|null} the material or null if none found.
  8796. */
  8797. Scene.prototype.getMaterialByID = function (id) {
  8798. for (var index = 0; index < this.materials.length; index++) {
  8799. if (this.materials[index].id === id) {
  8800. return this.materials[index];
  8801. }
  8802. }
  8803. return null;
  8804. };
  8805. /**
  8806. * get a material using its name
  8807. * @param {string} the material's name
  8808. * @return {BABYLON.Material|null} the material or null if none found.
  8809. */
  8810. Scene.prototype.getMaterialByName = function (name) {
  8811. for (var index = 0; index < this.materials.length; index++) {
  8812. if (this.materials[index].name === name) {
  8813. return this.materials[index];
  8814. }
  8815. }
  8816. return null;
  8817. };
  8818. Scene.prototype.getCameraByID = function (id) {
  8819. for (var index = 0; index < this.cameras.length; index++) {
  8820. if (this.cameras[index].id === id) {
  8821. return this.cameras[index];
  8822. }
  8823. }
  8824. return null;
  8825. };
  8826. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  8827. for (var index = 0; index < this.cameras.length; index++) {
  8828. if (this.cameras[index].uniqueId === uniqueId) {
  8829. return this.cameras[index];
  8830. }
  8831. }
  8832. return null;
  8833. };
  8834. /**
  8835. * get a camera using its name
  8836. * @param {string} the camera's name
  8837. * @return {BABYLON.Camera|null} the camera or null if none found.
  8838. */
  8839. Scene.prototype.getCameraByName = function (name) {
  8840. for (var index = 0; index < this.cameras.length; index++) {
  8841. if (this.cameras[index].name === name) {
  8842. return this.cameras[index];
  8843. }
  8844. }
  8845. return null;
  8846. };
  8847. /**
  8848. * get a light node using its name
  8849. * @param {string} the light's name
  8850. * @return {BABYLON.Light|null} the light or null if none found.
  8851. */
  8852. Scene.prototype.getLightByName = function (name) {
  8853. for (var index = 0; index < this.lights.length; index++) {
  8854. if (this.lights[index].name === name) {
  8855. return this.lights[index];
  8856. }
  8857. }
  8858. return null;
  8859. };
  8860. /**
  8861. * get a light node using its ID
  8862. * @param {string} the light's id
  8863. * @return {BABYLON.Light|null} the light or null if none found.
  8864. */
  8865. Scene.prototype.getLightByID = function (id) {
  8866. for (var index = 0; index < this.lights.length; index++) {
  8867. if (this.lights[index].id === id) {
  8868. return this.lights[index];
  8869. }
  8870. }
  8871. return null;
  8872. };
  8873. /**
  8874. * get a light node using its scene-generated unique ID
  8875. * @param {number} the light's unique id
  8876. * @return {BABYLON.Light|null} the light or null if none found.
  8877. */
  8878. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  8879. for (var index = 0; index < this.lights.length; index++) {
  8880. if (this.lights[index].uniqueId === uniqueId) {
  8881. return this.lights[index];
  8882. }
  8883. }
  8884. return null;
  8885. };
  8886. /**
  8887. * get a geometry using its ID
  8888. * @param {string} the geometry's id
  8889. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  8890. */
  8891. Scene.prototype.getGeometryByID = function (id) {
  8892. for (var index = 0; index < this._geometries.length; index++) {
  8893. if (this._geometries[index].id === id) {
  8894. return this._geometries[index];
  8895. }
  8896. }
  8897. return null;
  8898. };
  8899. /**
  8900. * add a new geometry to this scene.
  8901. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  8902. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  8903. * @return {boolean} was the geometry added or not
  8904. */
  8905. Scene.prototype.pushGeometry = function (geometry, force) {
  8906. if (!force && this.getGeometryByID(geometry.id)) {
  8907. return false;
  8908. }
  8909. this._geometries.push(geometry);
  8910. if (this.onGeometryAdded) {
  8911. this.onGeometryAdded(geometry);
  8912. }
  8913. return true;
  8914. };
  8915. /**
  8916. * Removes an existing geometry
  8917. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  8918. * @return {boolean} was the geometry removed or not
  8919. */
  8920. Scene.prototype.removeGeometry = function (geometry) {
  8921. var index = this._geometries.indexOf(geometry);
  8922. if (index > -1) {
  8923. this._geometries.splice(index, 1);
  8924. if (this.onGeometryRemoved) {
  8925. this.onGeometryRemoved(geometry);
  8926. }
  8927. return true;
  8928. }
  8929. return false;
  8930. };
  8931. Scene.prototype.getGeometries = function () {
  8932. return this._geometries;
  8933. };
  8934. /**
  8935. * Get the first added mesh found of a given ID
  8936. * @param {string} id - the id to search for
  8937. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8938. */
  8939. Scene.prototype.getMeshByID = function (id) {
  8940. for (var index = 0; index < this.meshes.length; index++) {
  8941. if (this.meshes[index].id === id) {
  8942. return this.meshes[index];
  8943. }
  8944. }
  8945. return null;
  8946. };
  8947. /**
  8948. * Get a mesh with its auto-generated unique id
  8949. * @param {number} uniqueId - the unique id to search for
  8950. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8951. */
  8952. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  8953. for (var index = 0; index < this.meshes.length; index++) {
  8954. if (this.meshes[index].uniqueId === uniqueId) {
  8955. return this.meshes[index];
  8956. }
  8957. }
  8958. return null;
  8959. };
  8960. /**
  8961. * Get a the last added mesh found of a given ID
  8962. * @param {string} id - the id to search for
  8963. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8964. */
  8965. Scene.prototype.getLastMeshByID = function (id) {
  8966. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8967. if (this.meshes[index].id === id) {
  8968. return this.meshes[index];
  8969. }
  8970. }
  8971. return null;
  8972. };
  8973. /**
  8974. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  8975. * @param {string} id - the id to search for
  8976. * @return {BABYLON.Node|null} the node found or null if not found at all.
  8977. */
  8978. Scene.prototype.getLastEntryByID = function (id) {
  8979. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8980. if (this.meshes[index].id === id) {
  8981. return this.meshes[index];
  8982. }
  8983. }
  8984. for (index = this.cameras.length - 1; index >= 0; index--) {
  8985. if (this.cameras[index].id === id) {
  8986. return this.cameras[index];
  8987. }
  8988. }
  8989. for (index = this.lights.length - 1; index >= 0; index--) {
  8990. if (this.lights[index].id === id) {
  8991. return this.lights[index];
  8992. }
  8993. }
  8994. return null;
  8995. };
  8996. Scene.prototype.getNodeByName = function (name) {
  8997. var mesh = this.getMeshByName(name);
  8998. if (mesh) {
  8999. return mesh;
  9000. }
  9001. var light = this.getLightByName(name);
  9002. if (light) {
  9003. return light;
  9004. }
  9005. return this.getCameraByName(name);
  9006. };
  9007. Scene.prototype.getMeshByName = function (name) {
  9008. for (var index = 0; index < this.meshes.length; index++) {
  9009. if (this.meshes[index].name === name) {
  9010. return this.meshes[index];
  9011. }
  9012. }
  9013. return null;
  9014. };
  9015. Scene.prototype.getSoundByName = function (name) {
  9016. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  9017. if (this.mainSoundTrack.soundCollection[index].name === name) {
  9018. return this.mainSoundTrack.soundCollection[index];
  9019. }
  9020. }
  9021. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  9022. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  9023. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  9024. return this.soundTracks[sdIndex].soundCollection[index];
  9025. }
  9026. }
  9027. }
  9028. return null;
  9029. };
  9030. Scene.prototype.getLastSkeletonByID = function (id) {
  9031. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  9032. if (this.skeletons[index].id === id) {
  9033. return this.skeletons[index];
  9034. }
  9035. }
  9036. return null;
  9037. };
  9038. Scene.prototype.getSkeletonById = function (id) {
  9039. for (var index = 0; index < this.skeletons.length; index++) {
  9040. if (this.skeletons[index].id === id) {
  9041. return this.skeletons[index];
  9042. }
  9043. }
  9044. return null;
  9045. };
  9046. Scene.prototype.getSkeletonByName = function (name) {
  9047. for (var index = 0; index < this.skeletons.length; index++) {
  9048. if (this.skeletons[index].name === name) {
  9049. return this.skeletons[index];
  9050. }
  9051. }
  9052. return null;
  9053. };
  9054. Scene.prototype.isActiveMesh = function (mesh) {
  9055. return (this._activeMeshes.indexOf(mesh) !== -1);
  9056. };
  9057. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  9058. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  9059. var material = subMesh.getMaterial();
  9060. if (mesh.showSubMeshesBoundingBox) {
  9061. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  9062. }
  9063. if (material) {
  9064. // Render targets
  9065. if (material.getRenderTargetTextures) {
  9066. if (this._processedMaterials.indexOf(material) === -1) {
  9067. this._processedMaterials.push(material);
  9068. this._renderTargets.concat(material.getRenderTargetTextures());
  9069. }
  9070. }
  9071. // Dispatch
  9072. this._activeVertices += subMesh.indexCount;
  9073. this._renderingManager.dispatch(subMesh);
  9074. }
  9075. }
  9076. };
  9077. Scene.prototype._evaluateActiveMeshes = function () {
  9078. this.activeCamera._activeMeshes.reset();
  9079. this._activeMeshes.reset();
  9080. this._renderingManager.reset();
  9081. this._processedMaterials.reset();
  9082. this._activeParticleSystems.reset();
  9083. this._activeSkeletons.reset();
  9084. this._boundingBoxRenderer.reset();
  9085. if (!this._frustumPlanes) {
  9086. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  9087. }
  9088. else {
  9089. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  9090. }
  9091. // Meshes
  9092. var meshes;
  9093. var len;
  9094. if (this._selectionOctree) {
  9095. var selection = this._selectionOctree.select(this._frustumPlanes);
  9096. meshes = selection.data;
  9097. len = selection.length;
  9098. }
  9099. else {
  9100. len = this.meshes.length;
  9101. meshes = this.meshes;
  9102. }
  9103. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  9104. var mesh = meshes[meshIndex];
  9105. if (mesh.isBlocked) {
  9106. continue;
  9107. }
  9108. this._totalVertices += mesh.getTotalVertices();
  9109. if (!mesh.isReady()) {
  9110. continue;
  9111. }
  9112. mesh.computeWorldMatrix();
  9113. // Intersections
  9114. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  9115. this._meshesForIntersections.pushNoDuplicate(mesh);
  9116. }
  9117. // Switch to current LOD
  9118. var meshLOD = mesh.getLOD(this.activeCamera);
  9119. if (!meshLOD) {
  9120. continue;
  9121. }
  9122. mesh._preActivate();
  9123. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  9124. this._activeMeshes.push(mesh);
  9125. this.activeCamera._activeMeshes.push(mesh);
  9126. mesh._activate(this._renderId);
  9127. this._activeMesh(meshLOD);
  9128. }
  9129. }
  9130. // Particle systems
  9131. var beforeParticlesDate = BABYLON.Tools.Now;
  9132. if (this.particlesEnabled) {
  9133. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  9134. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  9135. var particleSystem = this.particleSystems[particleIndex];
  9136. if (!particleSystem.isStarted()) {
  9137. continue;
  9138. }
  9139. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  9140. this._activeParticleSystems.push(particleSystem);
  9141. particleSystem.animate();
  9142. }
  9143. }
  9144. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  9145. }
  9146. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  9147. };
  9148. Scene.prototype._activeMesh = function (mesh) {
  9149. if (mesh.skeleton && this.skeletonsEnabled) {
  9150. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  9151. }
  9152. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  9153. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  9154. }
  9155. if (mesh && mesh.subMeshes) {
  9156. // Submeshes Octrees
  9157. var len;
  9158. var subMeshes;
  9159. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  9160. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  9161. len = intersections.length;
  9162. subMeshes = intersections.data;
  9163. }
  9164. else {
  9165. subMeshes = mesh.subMeshes;
  9166. len = subMeshes.length;
  9167. }
  9168. for (var subIndex = 0; subIndex < len; subIndex++) {
  9169. var subMesh = subMeshes[subIndex];
  9170. this._evaluateSubMesh(subMesh, mesh);
  9171. }
  9172. }
  9173. };
  9174. Scene.prototype.updateTransformMatrix = function (force) {
  9175. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  9176. };
  9177. Scene.prototype._renderForCamera = function (camera) {
  9178. var engine = this._engine;
  9179. this.activeCamera = camera;
  9180. if (!this.activeCamera)
  9181. throw new Error("Active camera not set");
  9182. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  9183. // Viewport
  9184. engine.setViewport(this.activeCamera.viewport);
  9185. // Camera
  9186. this._renderId++;
  9187. this.updateTransformMatrix();
  9188. if (this.beforeCameraRender) {
  9189. this.beforeCameraRender(this.activeCamera);
  9190. }
  9191. // Meshes
  9192. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  9193. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  9194. this._evaluateActiveMeshes();
  9195. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  9196. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  9197. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  9198. var skeleton = this._activeSkeletons.data[skeletonIndex];
  9199. skeleton.prepare();
  9200. }
  9201. // Render targets
  9202. var beforeRenderTargetDate = BABYLON.Tools.Now;
  9203. if (this.renderTargetsEnabled) {
  9204. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  9205. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  9206. var renderTarget = this._renderTargets.data[renderIndex];
  9207. if (renderTarget._shouldRender()) {
  9208. this._renderId++;
  9209. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  9210. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  9211. }
  9212. }
  9213. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  9214. this._renderId++;
  9215. }
  9216. if (this._renderTargets.length > 0) {
  9217. engine.restoreDefaultFramebuffer();
  9218. }
  9219. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  9220. // Prepare Frame
  9221. this.postProcessManager._prepareFrame();
  9222. var beforeRenderDate = BABYLON.Tools.Now;
  9223. // Backgrounds
  9224. if (this.layers.length) {
  9225. engine.setDepthBuffer(false);
  9226. var layerIndex;
  9227. var layer;
  9228. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  9229. layer = this.layers[layerIndex];
  9230. if (layer.isBackground) {
  9231. layer.render();
  9232. }
  9233. }
  9234. engine.setDepthBuffer(true);
  9235. }
  9236. // Render
  9237. BABYLON.Tools.StartPerformanceCounter("Main render");
  9238. this._renderingManager.render(null, null, true, true);
  9239. BABYLON.Tools.EndPerformanceCounter("Main render");
  9240. // Bounding boxes
  9241. this._boundingBoxRenderer.render();
  9242. // Lens flares
  9243. if (this.lensFlaresEnabled) {
  9244. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  9245. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  9246. this.lensFlareSystems[lensFlareSystemIndex].render();
  9247. }
  9248. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  9249. }
  9250. // Foregrounds
  9251. if (this.layers.length) {
  9252. engine.setDepthBuffer(false);
  9253. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  9254. layer = this.layers[layerIndex];
  9255. if (!layer.isBackground) {
  9256. layer.render();
  9257. }
  9258. }
  9259. engine.setDepthBuffer(true);
  9260. }
  9261. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  9262. // Finalize frame
  9263. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  9264. // Update camera
  9265. this.activeCamera._updateFromScene();
  9266. // Reset some special arrays
  9267. this._renderTargets.reset();
  9268. if (this.afterCameraRender) {
  9269. this.afterCameraRender(this.activeCamera);
  9270. }
  9271. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  9272. };
  9273. Scene.prototype._processSubCameras = function (camera) {
  9274. if (camera.subCameras.length === 0) {
  9275. this._renderForCamera(camera);
  9276. return;
  9277. }
  9278. for (var index = 0; index < camera.subCameras.length; index++) {
  9279. this._renderForCamera(camera.subCameras[index]);
  9280. }
  9281. this.activeCamera = camera;
  9282. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  9283. // Update camera
  9284. this.activeCamera._updateFromScene();
  9285. };
  9286. Scene.prototype._checkIntersections = function () {
  9287. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  9288. var sourceMesh = this._meshesForIntersections.data[index];
  9289. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  9290. var action = sourceMesh.actionManager.actions[actionIndex];
  9291. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9292. var parameters = action.getTriggerParameter();
  9293. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  9294. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  9295. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  9296. if (areIntersecting && currentIntersectionInProgress === -1) {
  9297. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  9298. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  9299. sourceMesh._intersectionsInProgress.push(otherMesh);
  9300. }
  9301. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9302. sourceMesh._intersectionsInProgress.push(otherMesh);
  9303. }
  9304. }
  9305. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9306. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  9307. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  9308. if (indexOfOther > -1) {
  9309. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  9310. }
  9311. }
  9312. }
  9313. }
  9314. }
  9315. };
  9316. Scene.prototype.render = function () {
  9317. var startDate = BABYLON.Tools.Now;
  9318. this._particlesDuration = 0;
  9319. this._spritesDuration = 0;
  9320. this._activeParticles = 0;
  9321. this._renderDuration = 0;
  9322. this._renderTargetsDuration = 0;
  9323. this._evaluateActiveMeshesDuration = 0;
  9324. this._totalVertices = 0;
  9325. this._activeVertices = 0;
  9326. this._activeBones = 0;
  9327. this.getEngine().resetDrawCalls();
  9328. this._meshesForIntersections.reset();
  9329. this.resetCachedMaterial();
  9330. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  9331. // Actions
  9332. if (this.actionManager) {
  9333. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  9334. }
  9335. //Simplification Queue
  9336. if (!this.simplificationQueue.running) {
  9337. this.simplificationQueue.executeNext();
  9338. }
  9339. // Before render
  9340. if (this.beforeRender) {
  9341. this.beforeRender();
  9342. }
  9343. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  9344. this._onBeforeRenderCallbacks[callbackIndex]();
  9345. }
  9346. // Animations
  9347. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  9348. this._animationRatio = deltaTime * (60.0 / 1000.0);
  9349. this._animate();
  9350. // Physics
  9351. if (this._physicsEngine) {
  9352. BABYLON.Tools.StartPerformanceCounter("Physics");
  9353. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  9354. BABYLON.Tools.EndPerformanceCounter("Physics");
  9355. }
  9356. // Customs render targets
  9357. var beforeRenderTargetDate = BABYLON.Tools.Now;
  9358. var engine = this.getEngine();
  9359. var currentActiveCamera = this.activeCamera;
  9360. if (this.renderTargetsEnabled) {
  9361. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  9362. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  9363. var renderTarget = this.customRenderTargets[customIndex];
  9364. if (renderTarget._shouldRender()) {
  9365. this._renderId++;
  9366. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  9367. if (!this.activeCamera)
  9368. throw new Error("Active camera not set");
  9369. // Viewport
  9370. engine.setViewport(this.activeCamera.viewport);
  9371. // Camera
  9372. this.updateTransformMatrix();
  9373. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  9374. }
  9375. }
  9376. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  9377. this._renderId++;
  9378. }
  9379. if (this.customRenderTargets.length > 0) {
  9380. engine.restoreDefaultFramebuffer();
  9381. }
  9382. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  9383. this.activeCamera = currentActiveCamera;
  9384. // Procedural textures
  9385. if (this.proceduralTexturesEnabled) {
  9386. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  9387. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  9388. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  9389. if (proceduralTexture._shouldRender()) {
  9390. proceduralTexture.render();
  9391. }
  9392. }
  9393. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  9394. }
  9395. // Clear
  9396. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  9397. // Shadows
  9398. if (this.shadowsEnabled) {
  9399. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  9400. var light = this.lights[lightIndex];
  9401. var shadowGenerator = light.getShadowGenerator();
  9402. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  9403. this._renderTargets.push(shadowGenerator.getShadowMap());
  9404. }
  9405. }
  9406. }
  9407. // Depth renderer
  9408. if (this._depthRenderer) {
  9409. this._renderTargets.push(this._depthRenderer.getDepthMap());
  9410. }
  9411. // RenderPipeline
  9412. this.postProcessRenderPipelineManager.update();
  9413. // Multi-cameras?
  9414. if (this.activeCameras.length > 0) {
  9415. var currentRenderId = this._renderId;
  9416. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  9417. this._renderId = currentRenderId;
  9418. this._processSubCameras(this.activeCameras[cameraIndex]);
  9419. }
  9420. }
  9421. else {
  9422. if (!this.activeCamera) {
  9423. throw new Error("No camera defined");
  9424. }
  9425. this._processSubCameras(this.activeCamera);
  9426. }
  9427. // Intersection checks
  9428. this._checkIntersections();
  9429. // Update the audio listener attached to the camera
  9430. this._updateAudioParameters();
  9431. // After render
  9432. if (this.afterRender) {
  9433. this.afterRender();
  9434. }
  9435. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  9436. this._onAfterRenderCallbacks[callbackIndex]();
  9437. }
  9438. for (var index = 0; index < this._toBeDisposed.length; index++) {
  9439. this._toBeDisposed.data[index].dispose();
  9440. this._toBeDisposed[index] = null;
  9441. }
  9442. this._toBeDisposed.reset();
  9443. if (this.dumpNextRenderTargets) {
  9444. this.dumpNextRenderTargets = false;
  9445. }
  9446. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  9447. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  9448. };
  9449. Scene.prototype._updateAudioParameters = function () {
  9450. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  9451. return;
  9452. }
  9453. var listeningCamera;
  9454. var audioEngine = BABYLON.Engine.audioEngine;
  9455. if (this.activeCameras.length > 0) {
  9456. listeningCamera = this.activeCameras[0];
  9457. }
  9458. else {
  9459. listeningCamera = this.activeCamera;
  9460. }
  9461. if (listeningCamera && audioEngine.canUseWebAudio) {
  9462. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  9463. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  9464. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  9465. cameraDirection.normalize();
  9466. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  9467. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9468. var sound = this.mainSoundTrack.soundCollection[i];
  9469. if (sound.useCustomAttenuation) {
  9470. sound.updateDistanceFromListener();
  9471. }
  9472. }
  9473. for (i = 0; i < this.soundTracks.length; i++) {
  9474. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9475. sound = this.soundTracks[i].soundCollection[j];
  9476. if (sound.useCustomAttenuation) {
  9477. sound.updateDistanceFromListener();
  9478. }
  9479. }
  9480. }
  9481. }
  9482. };
  9483. Object.defineProperty(Scene.prototype, "audioEnabled", {
  9484. // Audio
  9485. get: function () {
  9486. return this._audioEnabled;
  9487. },
  9488. set: function (value) {
  9489. this._audioEnabled = value;
  9490. if (this._audioEnabled) {
  9491. this._enableAudio();
  9492. }
  9493. else {
  9494. this._disableAudio();
  9495. }
  9496. },
  9497. enumerable: true,
  9498. configurable: true
  9499. });
  9500. Scene.prototype._disableAudio = function () {
  9501. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9502. this.mainSoundTrack.soundCollection[i].pause();
  9503. }
  9504. for (i = 0; i < this.soundTracks.length; i++) {
  9505. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9506. this.soundTracks[i].soundCollection[j].pause();
  9507. }
  9508. }
  9509. };
  9510. Scene.prototype._enableAudio = function () {
  9511. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9512. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  9513. this.mainSoundTrack.soundCollection[i].play();
  9514. }
  9515. }
  9516. for (i = 0; i < this.soundTracks.length; i++) {
  9517. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9518. if (this.soundTracks[i].soundCollection[j].isPaused) {
  9519. this.soundTracks[i].soundCollection[j].play();
  9520. }
  9521. }
  9522. }
  9523. };
  9524. Object.defineProperty(Scene.prototype, "headphone", {
  9525. get: function () {
  9526. return this._headphone;
  9527. },
  9528. set: function (value) {
  9529. this._headphone = value;
  9530. if (this._headphone) {
  9531. this._switchAudioModeForHeadphones();
  9532. }
  9533. else {
  9534. this._switchAudioModeForNormalSpeakers();
  9535. }
  9536. },
  9537. enumerable: true,
  9538. configurable: true
  9539. });
  9540. Scene.prototype._switchAudioModeForHeadphones = function () {
  9541. this.mainSoundTrack.switchPanningModelToHRTF();
  9542. for (var i = 0; i < this.soundTracks.length; i++) {
  9543. this.soundTracks[i].switchPanningModelToHRTF();
  9544. }
  9545. };
  9546. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  9547. this.mainSoundTrack.switchPanningModelToEqualPower();
  9548. for (var i = 0; i < this.soundTracks.length; i++) {
  9549. this.soundTracks[i].switchPanningModelToEqualPower();
  9550. }
  9551. };
  9552. Scene.prototype.enableDepthRenderer = function () {
  9553. if (this._depthRenderer) {
  9554. return this._depthRenderer;
  9555. }
  9556. this._depthRenderer = new BABYLON.DepthRenderer(this);
  9557. return this._depthRenderer;
  9558. };
  9559. Scene.prototype.disableDepthRenderer = function () {
  9560. if (!this._depthRenderer) {
  9561. return;
  9562. }
  9563. this._depthRenderer.dispose();
  9564. this._depthRenderer = null;
  9565. };
  9566. Scene.prototype.dispose = function () {
  9567. this.beforeRender = null;
  9568. this.afterRender = null;
  9569. this.skeletons = [];
  9570. this._boundingBoxRenderer.dispose();
  9571. if (this._depthRenderer) {
  9572. this._depthRenderer.dispose();
  9573. }
  9574. // Debug layer
  9575. this.debugLayer.hide();
  9576. // Events
  9577. if (this.onDispose) {
  9578. this.onDispose();
  9579. }
  9580. this._onBeforeRenderCallbacks = [];
  9581. this._onAfterRenderCallbacks = [];
  9582. this.detachControl();
  9583. // Release sounds & sounds tracks
  9584. this.disposeSounds();
  9585. // Detach cameras
  9586. var canvas = this._engine.getRenderingCanvas();
  9587. var index;
  9588. for (index = 0; index < this.cameras.length; index++) {
  9589. this.cameras[index].detachControl(canvas);
  9590. }
  9591. while (this.lights.length) {
  9592. this.lights[0].dispose();
  9593. }
  9594. while (this.meshes.length) {
  9595. this.meshes[0].dispose(true);
  9596. }
  9597. while (this.cameras.length) {
  9598. this.cameras[0].dispose();
  9599. }
  9600. while (this.materials.length) {
  9601. this.materials[0].dispose();
  9602. }
  9603. while (this.particleSystems.length) {
  9604. this.particleSystems[0].dispose();
  9605. }
  9606. while (this.spriteManagers.length) {
  9607. this.spriteManagers[0].dispose();
  9608. }
  9609. while (this.layers.length) {
  9610. this.layers[0].dispose();
  9611. }
  9612. while (this.textures.length) {
  9613. this.textures[0].dispose();
  9614. }
  9615. // Post-processes
  9616. this.postProcessManager.dispose();
  9617. // Physics
  9618. if (this._physicsEngine) {
  9619. this.disablePhysicsEngine();
  9620. }
  9621. // Remove from engine
  9622. index = this._engine.scenes.indexOf(this);
  9623. if (index > -1) {
  9624. this._engine.scenes.splice(index, 1);
  9625. }
  9626. this._engine.wipeCaches();
  9627. };
  9628. // Release sounds & sounds tracks
  9629. Scene.prototype.disposeSounds = function () {
  9630. this.mainSoundTrack.dispose();
  9631. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  9632. this.soundTracks[scIndex].dispose();
  9633. }
  9634. };
  9635. // Collisions
  9636. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9637. if (excludedMesh === void 0) { excludedMesh = null; }
  9638. position.divideToRef(collider.radius, this._scaledPosition);
  9639. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9640. collider.retry = 0;
  9641. collider.initialVelocity = this._scaledVelocity;
  9642. collider.initialPosition = this._scaledPosition;
  9643. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  9644. finalPosition.multiplyInPlace(collider.radius);
  9645. };
  9646. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9647. if (excludedMesh === void 0) { excludedMesh = null; }
  9648. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9649. if (collider.retry >= maximumRetry) {
  9650. finalPosition.copyFrom(position);
  9651. return;
  9652. }
  9653. collider._initialize(position, velocity, closeDistance);
  9654. for (var index = 0; index < this.meshes.length; index++) {
  9655. var mesh = this.meshes[index];
  9656. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9657. mesh._checkCollision(collider);
  9658. }
  9659. }
  9660. if (!collider.collisionFound) {
  9661. position.addToRef(velocity, finalPosition);
  9662. return;
  9663. }
  9664. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9665. collider._getResponse(position, velocity);
  9666. }
  9667. if (velocity.length() <= closeDistance) {
  9668. finalPosition.copyFrom(position);
  9669. return;
  9670. }
  9671. collider.retry++;
  9672. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9673. };
  9674. // Octrees
  9675. Scene.prototype.getWorldExtends = function () {
  9676. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9677. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9678. for (var index = 0; index < this.meshes.length; index++) {
  9679. var mesh = this.meshes[index];
  9680. mesh.computeWorldMatrix(true);
  9681. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  9682. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  9683. BABYLON.Tools.CheckExtends(minBox, min, max);
  9684. BABYLON.Tools.CheckExtends(maxBox, min, max);
  9685. }
  9686. return {
  9687. min: min,
  9688. max: max
  9689. };
  9690. };
  9691. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  9692. if (maxCapacity === void 0) { maxCapacity = 64; }
  9693. if (maxDepth === void 0) { maxDepth = 2; }
  9694. if (!this._selectionOctree) {
  9695. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  9696. }
  9697. var worldExtends = this.getWorldExtends();
  9698. // Update octree
  9699. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  9700. return this._selectionOctree;
  9701. };
  9702. // Picking
  9703. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  9704. var engine = this._engine;
  9705. if (!camera) {
  9706. if (!this.activeCamera)
  9707. throw new Error("Active camera not set");
  9708. camera = this.activeCamera;
  9709. }
  9710. var cameraViewport = camera.viewport;
  9711. var viewport = cameraViewport.toGlobal(engine);
  9712. // Moving coordinates to local viewport world
  9713. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  9714. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  9715. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9716. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9717. };
  9718. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  9719. var pickingInfo = null;
  9720. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  9721. var mesh = this.meshes[meshIndex];
  9722. if (predicate) {
  9723. if (!predicate(mesh)) {
  9724. continue;
  9725. }
  9726. }
  9727. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  9728. continue;
  9729. }
  9730. var world = mesh.getWorldMatrix();
  9731. var ray = rayFunction(world);
  9732. var result = mesh.intersects(ray, fastCheck);
  9733. if (!result || !result.hit)
  9734. continue;
  9735. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  9736. continue;
  9737. pickingInfo = result;
  9738. if (fastCheck) {
  9739. break;
  9740. }
  9741. }
  9742. return pickingInfo || new BABYLON.PickingInfo();
  9743. };
  9744. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  9745. var _this = this;
  9746. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  9747. /// <param name="x">X position on screen</param>
  9748. /// <param name="y">Y position on screen</param>
  9749. /// <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>
  9750. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  9751. /// <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>
  9752. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  9753. };
  9754. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  9755. var _this = this;
  9756. return this._internalPick(function (world) {
  9757. if (!_this._pickWithRayInverseMatrix) {
  9758. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  9759. }
  9760. world.invertToRef(_this._pickWithRayInverseMatrix);
  9761. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  9762. }, predicate, fastCheck);
  9763. };
  9764. Scene.prototype.setPointerOverMesh = function (mesh) {
  9765. if (this._pointerOverMesh === mesh) {
  9766. return;
  9767. }
  9768. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9769. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9770. }
  9771. this._pointerOverMesh = mesh;
  9772. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9773. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9774. }
  9775. };
  9776. Scene.prototype.getPointerOverMesh = function () {
  9777. return this._pointerOverMesh;
  9778. };
  9779. // Physics
  9780. Scene.prototype.getPhysicsEngine = function () {
  9781. return this._physicsEngine;
  9782. };
  9783. Scene.prototype.enablePhysics = function (gravity, plugin) {
  9784. if (this._physicsEngine) {
  9785. return true;
  9786. }
  9787. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  9788. if (!this._physicsEngine.isSupported()) {
  9789. this._physicsEngine = null;
  9790. return false;
  9791. }
  9792. this._physicsEngine._initialize(gravity);
  9793. return true;
  9794. };
  9795. Scene.prototype.disablePhysicsEngine = function () {
  9796. if (!this._physicsEngine) {
  9797. return;
  9798. }
  9799. this._physicsEngine.dispose();
  9800. this._physicsEngine = undefined;
  9801. };
  9802. Scene.prototype.isPhysicsEnabled = function () {
  9803. return this._physicsEngine !== undefined;
  9804. };
  9805. Scene.prototype.setGravity = function (gravity) {
  9806. if (!this._physicsEngine) {
  9807. return;
  9808. }
  9809. this._physicsEngine._setGravity(gravity);
  9810. };
  9811. Scene.prototype.createCompoundImpostor = function (parts, options) {
  9812. if (parts.parts) {
  9813. options = parts;
  9814. parts = parts.parts;
  9815. }
  9816. if (!this._physicsEngine) {
  9817. return null;
  9818. }
  9819. for (var index = 0; index < parts.length; index++) {
  9820. var mesh = parts[index].mesh;
  9821. mesh._physicImpostor = parts[index].impostor;
  9822. mesh._physicsMass = options.mass / parts.length;
  9823. mesh._physicsFriction = options.friction;
  9824. mesh._physicRestitution = options.restitution;
  9825. }
  9826. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  9827. };
  9828. Scene.prototype.deleteCompoundImpostor = function (compound) {
  9829. for (var index = 0; index < compound.parts.length; index++) {
  9830. var mesh = compound.parts[index].mesh;
  9831. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9832. this._physicsEngine._unregisterMesh(mesh);
  9833. }
  9834. };
  9835. // Misc.
  9836. Scene.prototype.createDefaultCameraOrLight = function () {
  9837. // Light
  9838. if (this.lights.length === 0) {
  9839. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  9840. }
  9841. // Camera
  9842. if (!this.activeCamera) {
  9843. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  9844. // Compute position
  9845. var worldExtends = this.getWorldExtends();
  9846. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  9847. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  9848. camera.setTarget(worldCenter);
  9849. this.activeCamera = camera;
  9850. }
  9851. };
  9852. // Tags
  9853. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  9854. if (tagsQuery === undefined) {
  9855. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  9856. return list;
  9857. }
  9858. var listByTags = [];
  9859. forEach = forEach || (function (item) {
  9860. return;
  9861. });
  9862. for (var i in list) {
  9863. var item = list[i];
  9864. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  9865. listByTags.push(item);
  9866. forEach(item);
  9867. }
  9868. }
  9869. return listByTags;
  9870. };
  9871. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  9872. return this._getByTags(this.meshes, tagsQuery, forEach);
  9873. };
  9874. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  9875. return this._getByTags(this.cameras, tagsQuery, forEach);
  9876. };
  9877. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  9878. return this._getByTags(this.lights, tagsQuery, forEach);
  9879. };
  9880. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  9881. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  9882. };
  9883. // Statics
  9884. Scene._FOGMODE_NONE = 0;
  9885. Scene._FOGMODE_EXP = 1;
  9886. Scene._FOGMODE_EXP2 = 2;
  9887. Scene._FOGMODE_LINEAR = 3;
  9888. Scene.MinDeltaTime = 1.0;
  9889. Scene.MaxDeltaTime = 1000.0;
  9890. return Scene;
  9891. })();
  9892. BABYLON.Scene = Scene;
  9893. })(BABYLON || (BABYLON = {}));
  9894. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  9895. (function (BABYLON) {
  9896. var VertexBuffer = (function () {
  9897. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  9898. if (engine instanceof BABYLON.Mesh) {
  9899. this._engine = engine.getScene().getEngine();
  9900. }
  9901. else {
  9902. this._engine = engine;
  9903. }
  9904. this._updatable = updatable;
  9905. this._data = data;
  9906. if (!postponeInternalCreation) {
  9907. this.create();
  9908. }
  9909. this._kind = kind;
  9910. if (stride) {
  9911. this._strideSize = stride;
  9912. return;
  9913. }
  9914. switch (kind) {
  9915. case VertexBuffer.PositionKind:
  9916. this._strideSize = 3;
  9917. break;
  9918. case VertexBuffer.NormalKind:
  9919. this._strideSize = 3;
  9920. break;
  9921. case VertexBuffer.UVKind:
  9922. this._strideSize = 2;
  9923. break;
  9924. case VertexBuffer.UV2Kind:
  9925. this._strideSize = 2;
  9926. break;
  9927. case VertexBuffer.ColorKind:
  9928. this._strideSize = 4;
  9929. break;
  9930. case VertexBuffer.MatricesIndicesKind:
  9931. this._strideSize = 4;
  9932. break;
  9933. case VertexBuffer.MatricesWeightsKind:
  9934. this._strideSize = 4;
  9935. break;
  9936. }
  9937. }
  9938. // Properties
  9939. VertexBuffer.prototype.isUpdatable = function () {
  9940. return this._updatable;
  9941. };
  9942. VertexBuffer.prototype.getData = function () {
  9943. return this._data;
  9944. };
  9945. VertexBuffer.prototype.getBuffer = function () {
  9946. return this._buffer;
  9947. };
  9948. VertexBuffer.prototype.getStrideSize = function () {
  9949. return this._strideSize;
  9950. };
  9951. // Methods
  9952. VertexBuffer.prototype.create = function (data) {
  9953. if (!data && this._buffer) {
  9954. return; // nothing to do
  9955. }
  9956. data = data || this._data;
  9957. if (!this._buffer) {
  9958. if (this._updatable) {
  9959. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  9960. }
  9961. else {
  9962. this._buffer = this._engine.createVertexBuffer(data);
  9963. }
  9964. }
  9965. if (this._updatable) {
  9966. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  9967. this._data = data;
  9968. }
  9969. };
  9970. VertexBuffer.prototype.update = function (data) {
  9971. this.create(data);
  9972. };
  9973. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  9974. if (!this._buffer) {
  9975. return;
  9976. }
  9977. if (this._updatable) {
  9978. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  9979. this._data = null;
  9980. }
  9981. };
  9982. VertexBuffer.prototype.dispose = function () {
  9983. if (!this._buffer) {
  9984. return;
  9985. }
  9986. if (this._engine._releaseBuffer(this._buffer)) {
  9987. this._buffer = null;
  9988. }
  9989. };
  9990. Object.defineProperty(VertexBuffer, "PositionKind", {
  9991. get: function () {
  9992. return VertexBuffer._PositionKind;
  9993. },
  9994. enumerable: true,
  9995. configurable: true
  9996. });
  9997. Object.defineProperty(VertexBuffer, "NormalKind", {
  9998. get: function () {
  9999. return VertexBuffer._NormalKind;
  10000. },
  10001. enumerable: true,
  10002. configurable: true
  10003. });
  10004. Object.defineProperty(VertexBuffer, "UVKind", {
  10005. get: function () {
  10006. return VertexBuffer._UVKind;
  10007. },
  10008. enumerable: true,
  10009. configurable: true
  10010. });
  10011. Object.defineProperty(VertexBuffer, "UV2Kind", {
  10012. get: function () {
  10013. return VertexBuffer._UV2Kind;
  10014. },
  10015. enumerable: true,
  10016. configurable: true
  10017. });
  10018. Object.defineProperty(VertexBuffer, "ColorKind", {
  10019. get: function () {
  10020. return VertexBuffer._ColorKind;
  10021. },
  10022. enumerable: true,
  10023. configurable: true
  10024. });
  10025. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  10026. get: function () {
  10027. return VertexBuffer._MatricesIndicesKind;
  10028. },
  10029. enumerable: true,
  10030. configurable: true
  10031. });
  10032. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  10033. get: function () {
  10034. return VertexBuffer._MatricesWeightsKind;
  10035. },
  10036. enumerable: true,
  10037. configurable: true
  10038. });
  10039. // Enums
  10040. VertexBuffer._PositionKind = "position";
  10041. VertexBuffer._NormalKind = "normal";
  10042. VertexBuffer._UVKind = "uv";
  10043. VertexBuffer._UV2Kind = "uv2";
  10044. VertexBuffer._ColorKind = "color";
  10045. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  10046. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  10047. return VertexBuffer;
  10048. })();
  10049. BABYLON.VertexBuffer = VertexBuffer;
  10050. })(BABYLON || (BABYLON = {}));
  10051. //# sourceMappingURL=babylon.vertexBuffer.js.map
  10052. var BABYLON;
  10053. (function (BABYLON) {
  10054. var AbstractMesh = (function (_super) {
  10055. __extends(AbstractMesh, _super);
  10056. function AbstractMesh(name, scene) {
  10057. _super.call(this, name, scene);
  10058. // Properties
  10059. this.definedFacingForward = true; // orientation for POV movement & rotation
  10060. this.position = new BABYLON.Vector3(0, 0, 0);
  10061. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10062. this.scaling = new BABYLON.Vector3(1, 1, 1);
  10063. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10064. this.visibility = 1.0;
  10065. this.alphaIndex = Number.MAX_VALUE;
  10066. this.infiniteDistance = false;
  10067. this.isVisible = true;
  10068. this.isPickable = true;
  10069. this.showBoundingBox = false;
  10070. this.showSubMeshesBoundingBox = false;
  10071. this.onDispose = null;
  10072. this.checkCollisions = false;
  10073. this.isBlocker = false;
  10074. this.renderingGroupId = 0;
  10075. this.receiveShadows = false;
  10076. this.renderOutline = false;
  10077. this.outlineColor = BABYLON.Color3.Red();
  10078. this.outlineWidth = 0.02;
  10079. this.renderOverlay = false;
  10080. this.overlayColor = BABYLON.Color3.Red();
  10081. this.overlayAlpha = 0.5;
  10082. this.hasVertexAlpha = false;
  10083. this.useVertexColors = true;
  10084. this.applyFog = true;
  10085. this.useOctreeForRenderingSelection = true;
  10086. this.useOctreeForPicking = true;
  10087. this.useOctreeForCollisions = true;
  10088. this.layerMask = 0x0FFFFFFF;
  10089. // Physics
  10090. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  10091. // Collisions
  10092. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10093. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10094. this._collider = new BABYLON.Collider();
  10095. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10096. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10097. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10098. // Cache
  10099. this._localScaling = BABYLON.Matrix.Zero();
  10100. this._localRotation = BABYLON.Matrix.Zero();
  10101. this._localTranslation = BABYLON.Matrix.Zero();
  10102. this._localBillboard = BABYLON.Matrix.Zero();
  10103. this._localPivotScaling = BABYLON.Matrix.Zero();
  10104. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  10105. this._localWorld = BABYLON.Matrix.Zero();
  10106. this._worldMatrix = BABYLON.Matrix.Zero();
  10107. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  10108. this._absolutePosition = BABYLON.Vector3.Zero();
  10109. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10110. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10111. this._isDirty = false;
  10112. this._pivotMatrix = BABYLON.Matrix.Identity();
  10113. this._isDisposed = false;
  10114. this._renderId = 0;
  10115. this._intersectionsInProgress = new Array();
  10116. this._onAfterWorldMatrixUpdate = new Array();
  10117. scene.addMesh(this);
  10118. }
  10119. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10120. get: function () {
  10121. return AbstractMesh._BILLBOARDMODE_NONE;
  10122. },
  10123. enumerable: true,
  10124. configurable: true
  10125. });
  10126. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10127. get: function () {
  10128. return AbstractMesh._BILLBOARDMODE_X;
  10129. },
  10130. enumerable: true,
  10131. configurable: true
  10132. });
  10133. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10134. get: function () {
  10135. return AbstractMesh._BILLBOARDMODE_Y;
  10136. },
  10137. enumerable: true,
  10138. configurable: true
  10139. });
  10140. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10141. get: function () {
  10142. return AbstractMesh._BILLBOARDMODE_Z;
  10143. },
  10144. enumerable: true,
  10145. configurable: true
  10146. });
  10147. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10148. get: function () {
  10149. return AbstractMesh._BILLBOARDMODE_ALL;
  10150. },
  10151. enumerable: true,
  10152. configurable: true
  10153. });
  10154. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  10155. // Methods
  10156. get: function () {
  10157. return false;
  10158. },
  10159. enumerable: true,
  10160. configurable: true
  10161. });
  10162. AbstractMesh.prototype.getLOD = function (camera) {
  10163. return this;
  10164. };
  10165. AbstractMesh.prototype.getTotalVertices = function () {
  10166. return 0;
  10167. };
  10168. AbstractMesh.prototype.getIndices = function () {
  10169. return null;
  10170. };
  10171. AbstractMesh.prototype.getVerticesData = function (kind) {
  10172. return null;
  10173. };
  10174. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10175. return false;
  10176. };
  10177. AbstractMesh.prototype.getBoundingInfo = function () {
  10178. if (this._masterMesh) {
  10179. return this._masterMesh.getBoundingInfo();
  10180. }
  10181. if (!this._boundingInfo) {
  10182. this._updateBoundingInfo();
  10183. }
  10184. return this._boundingInfo;
  10185. };
  10186. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10187. get: function () {
  10188. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10189. },
  10190. enumerable: true,
  10191. configurable: true
  10192. });
  10193. AbstractMesh.prototype._preActivate = function () {
  10194. };
  10195. AbstractMesh.prototype._activate = function (renderId) {
  10196. this._renderId = renderId;
  10197. };
  10198. AbstractMesh.prototype.getWorldMatrix = function () {
  10199. if (this._masterMesh) {
  10200. return this._masterMesh.getWorldMatrix();
  10201. }
  10202. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10203. this.computeWorldMatrix();
  10204. }
  10205. return this._worldMatrix;
  10206. };
  10207. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10208. get: function () {
  10209. return this._worldMatrix;
  10210. },
  10211. enumerable: true,
  10212. configurable: true
  10213. });
  10214. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10215. get: function () {
  10216. return this._absolutePosition;
  10217. },
  10218. enumerable: true,
  10219. configurable: true
  10220. });
  10221. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10222. if (!this.rotationQuaternion) {
  10223. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10224. this.rotation = BABYLON.Vector3.Zero();
  10225. }
  10226. if (!space || space === 0 /* LOCAL */) {
  10227. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  10228. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  10229. }
  10230. else {
  10231. if (this.parent) {
  10232. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10233. invertParentWorldMatrix.invert();
  10234. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10235. }
  10236. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  10237. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  10238. }
  10239. };
  10240. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10241. var displacementVector = axis.scale(distance);
  10242. if (!space || space === 0 /* LOCAL */) {
  10243. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10244. this.setPositionWithLocalVector(tempV3);
  10245. }
  10246. else {
  10247. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10248. }
  10249. };
  10250. AbstractMesh.prototype.getAbsolutePosition = function () {
  10251. this.computeWorldMatrix();
  10252. return this._absolutePosition;
  10253. };
  10254. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10255. if (!absolutePosition) {
  10256. return;
  10257. }
  10258. var absolutePositionX;
  10259. var absolutePositionY;
  10260. var absolutePositionZ;
  10261. if (absolutePosition.x === undefined) {
  10262. if (arguments.length < 3) {
  10263. return;
  10264. }
  10265. absolutePositionX = arguments[0];
  10266. absolutePositionY = arguments[1];
  10267. absolutePositionZ = arguments[2];
  10268. }
  10269. else {
  10270. absolutePositionX = absolutePosition.x;
  10271. absolutePositionY = absolutePosition.y;
  10272. absolutePositionZ = absolutePosition.z;
  10273. }
  10274. if (this.parent) {
  10275. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10276. invertParentWorldMatrix.invert();
  10277. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10278. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10279. }
  10280. else {
  10281. this.position.x = absolutePositionX;
  10282. this.position.y = absolutePositionY;
  10283. this.position.z = absolutePositionZ;
  10284. }
  10285. };
  10286. // ================================== Point of View Movement =================================
  10287. /**
  10288. * Perform relative position change from the point of view of behind the front of the mesh.
  10289. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10290. * Supports definition of mesh facing forward or backward.
  10291. * @param {number} amountRight
  10292. * @param {number} amountUp
  10293. * @param {number} amountForward
  10294. */
  10295. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10296. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10297. };
  10298. /**
  10299. * Calculate relative position change from the point of view of behind the front of the mesh.
  10300. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10301. * Supports definition of mesh facing forward or backward.
  10302. * @param {number} amountRight
  10303. * @param {number} amountUp
  10304. * @param {number} amountForward
  10305. */
  10306. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10307. var rotMatrix = new BABYLON.Matrix();
  10308. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10309. rotQuaternion.toRotationMatrix(rotMatrix);
  10310. var translationDelta = BABYLON.Vector3.Zero();
  10311. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10312. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10313. return translationDelta;
  10314. };
  10315. // ================================== Point of View Rotation =================================
  10316. /**
  10317. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10318. * Supports definition of mesh facing forward or backward.
  10319. * @param {number} flipBack
  10320. * @param {number} twirlClockwise
  10321. * @param {number} tiltRight
  10322. */
  10323. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10324. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10325. };
  10326. /**
  10327. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10328. * Supports definition of mesh facing forward or backward.
  10329. * @param {number} flipBack
  10330. * @param {number} twirlClockwise
  10331. * @param {number} tiltRight
  10332. */
  10333. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10334. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10335. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10336. };
  10337. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10338. this._pivotMatrix = matrix;
  10339. this._cache.pivotMatrixUpdated = true;
  10340. };
  10341. AbstractMesh.prototype.getPivotMatrix = function () {
  10342. return this._pivotMatrix;
  10343. };
  10344. AbstractMesh.prototype._isSynchronized = function () {
  10345. if (this._isDirty) {
  10346. return false;
  10347. }
  10348. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10349. return false;
  10350. if (this._cache.pivotMatrixUpdated) {
  10351. return false;
  10352. }
  10353. if (this.infiniteDistance) {
  10354. return false;
  10355. }
  10356. if (!this._cache.position.equals(this.position))
  10357. return false;
  10358. if (this.rotationQuaternion) {
  10359. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10360. return false;
  10361. }
  10362. else {
  10363. if (!this._cache.rotation.equals(this.rotation))
  10364. return false;
  10365. }
  10366. if (!this._cache.scaling.equals(this.scaling))
  10367. return false;
  10368. return true;
  10369. };
  10370. AbstractMesh.prototype._initCache = function () {
  10371. _super.prototype._initCache.call(this);
  10372. this._cache.localMatrixUpdated = false;
  10373. this._cache.position = BABYLON.Vector3.Zero();
  10374. this._cache.scaling = BABYLON.Vector3.Zero();
  10375. this._cache.rotation = BABYLON.Vector3.Zero();
  10376. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10377. };
  10378. AbstractMesh.prototype.markAsDirty = function (property) {
  10379. if (property === "rotation") {
  10380. this.rotationQuaternion = null;
  10381. }
  10382. this._currentRenderId = Number.MAX_VALUE;
  10383. this._isDirty = true;
  10384. };
  10385. AbstractMesh.prototype._updateBoundingInfo = function () {
  10386. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10387. this._boundingInfo._update(this.worldMatrixFromCache);
  10388. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10389. };
  10390. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10391. if (!this.subMeshes) {
  10392. return;
  10393. }
  10394. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10395. var subMesh = this.subMeshes[subIndex];
  10396. subMesh.updateBoundingInfo(matrix);
  10397. }
  10398. };
  10399. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10400. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10401. return this._worldMatrix;
  10402. }
  10403. this._cache.position.copyFrom(this.position);
  10404. this._cache.scaling.copyFrom(this.scaling);
  10405. this._cache.pivotMatrixUpdated = false;
  10406. this._currentRenderId = this.getScene().getRenderId();
  10407. this._isDirty = false;
  10408. // Scaling
  10409. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  10410. // Rotation
  10411. if (this.rotationQuaternion) {
  10412. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  10413. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10414. }
  10415. else {
  10416. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  10417. this._cache.rotation.copyFrom(this.rotation);
  10418. }
  10419. // Translation
  10420. if (this.infiniteDistance && !this.parent) {
  10421. var camera = this.getScene().activeCamera;
  10422. var cameraWorldMatrix = camera.getWorldMatrix();
  10423. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10424. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  10425. }
  10426. else {
  10427. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  10428. }
  10429. // Composing transformations
  10430. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  10431. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  10432. // Billboarding
  10433. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10434. var localPosition = this.position.clone();
  10435. var zero = this.getScene().activeCamera.position.clone();
  10436. if (this.parent && this.parent.position) {
  10437. localPosition.addInPlace(this.parent.position);
  10438. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  10439. }
  10440. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  10441. zero = this.getScene().activeCamera.position;
  10442. }
  10443. else {
  10444. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10445. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  10446. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10447. zero.y = localPosition.y + 0.001;
  10448. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10449. zero.z = localPosition.z + 0.001;
  10450. }
  10451. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  10452. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  10453. this._localBillboard.invert();
  10454. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  10455. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  10456. }
  10457. // Local world
  10458. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  10459. // Parent
  10460. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10461. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10462. }
  10463. else {
  10464. this._worldMatrix.copyFrom(this._localWorld);
  10465. }
  10466. // Bounding info
  10467. this._updateBoundingInfo();
  10468. // Absolute position
  10469. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10470. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  10471. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  10472. }
  10473. return this._worldMatrix;
  10474. };
  10475. /**
  10476. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10477. * @param func: callback function to add
  10478. */
  10479. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10480. this._onAfterWorldMatrixUpdate.push(func);
  10481. };
  10482. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10483. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  10484. if (index > -1) {
  10485. this._onAfterWorldMatrixUpdate.splice(index, 1);
  10486. }
  10487. };
  10488. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10489. this.computeWorldMatrix();
  10490. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10491. };
  10492. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10493. this.computeWorldMatrix();
  10494. var invLocalWorldMatrix = this._localWorld.clone();
  10495. invLocalWorldMatrix.invert();
  10496. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10497. };
  10498. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10499. this.computeWorldMatrix();
  10500. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10501. };
  10502. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  10503. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10504. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10505. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10506. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10507. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10508. /// <returns>Mesh oriented towards targetMesh</returns>
  10509. yawCor = yawCor || 0; // default to zero if undefined
  10510. pitchCor = pitchCor || 0;
  10511. rollCor = rollCor || 0;
  10512. var dv = targetPoint.subtract(this.position);
  10513. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10514. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10515. var pitch = Math.atan2(dv.y, len);
  10516. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  10517. };
  10518. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10519. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  10520. return false;
  10521. }
  10522. return true;
  10523. };
  10524. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  10525. if (!camera) {
  10526. camera = this.getScene().activeCamera;
  10527. }
  10528. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  10529. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  10530. return false;
  10531. }
  10532. return true;
  10533. };
  10534. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10535. if (!this._boundingInfo || !mesh._boundingInfo) {
  10536. return false;
  10537. }
  10538. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10539. };
  10540. AbstractMesh.prototype.intersectsPoint = function (point) {
  10541. if (!this._boundingInfo) {
  10542. return false;
  10543. }
  10544. return this._boundingInfo.intersectsPoint(point);
  10545. };
  10546. // Physics
  10547. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10548. var physicsEngine = this.getScene().getPhysicsEngine();
  10549. if (!physicsEngine) {
  10550. return;
  10551. }
  10552. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  10553. if (impostor.impostor) {
  10554. // Old API
  10555. options = impostor;
  10556. impostor = impostor.impostor;
  10557. }
  10558. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  10559. physicsEngine._unregisterMesh(this);
  10560. return;
  10561. }
  10562. if (!options) {
  10563. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  10564. }
  10565. else {
  10566. if (!options.mass && options.mass !== 0)
  10567. options.mass = 0;
  10568. if (!options.friction && options.friction !== 0)
  10569. options.friction = 0.2;
  10570. if (!options.restitution && options.restitution !== 0)
  10571. options.restitution = 0.2;
  10572. }
  10573. this._physicImpostor = impostor;
  10574. this._physicsMass = options.mass;
  10575. this._physicsFriction = options.friction;
  10576. this._physicRestitution = options.restitution;
  10577. return physicsEngine._registerMesh(this, impostor, options);
  10578. };
  10579. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10580. if (!this._physicImpostor) {
  10581. return BABYLON.PhysicsEngine.NoImpostor;
  10582. }
  10583. return this._physicImpostor;
  10584. };
  10585. AbstractMesh.prototype.getPhysicsMass = function () {
  10586. if (!this._physicsMass) {
  10587. return 0;
  10588. }
  10589. return this._physicsMass;
  10590. };
  10591. AbstractMesh.prototype.getPhysicsFriction = function () {
  10592. if (!this._physicsFriction) {
  10593. return 0;
  10594. }
  10595. return this._physicsFriction;
  10596. };
  10597. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10598. if (!this._physicRestitution) {
  10599. return 0;
  10600. }
  10601. return this._physicRestitution;
  10602. };
  10603. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10604. if (!camera) {
  10605. camera = this.getScene().activeCamera;
  10606. }
  10607. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10608. };
  10609. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10610. if (!camera) {
  10611. camera = this.getScene().activeCamera;
  10612. }
  10613. return this.absolutePosition.subtract(camera.position).length();
  10614. };
  10615. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10616. if (!this._physicImpostor) {
  10617. return;
  10618. }
  10619. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  10620. };
  10621. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10622. if (!this._physicImpostor) {
  10623. return;
  10624. }
  10625. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  10626. };
  10627. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10628. if (!this._physicImpostor) {
  10629. return;
  10630. }
  10631. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  10632. };
  10633. // Collisions
  10634. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10635. var globalPosition = this.getAbsolutePosition();
  10636. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10637. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10638. this._collider.radius = this.ellipsoid;
  10639. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  10640. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  10641. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10642. this.position.addInPlace(this._diffPositionForCollisions);
  10643. }
  10644. };
  10645. // Submeshes octree
  10646. /**
  10647. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10648. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10649. */
  10650. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10651. if (maxCapacity === void 0) { maxCapacity = 64; }
  10652. if (maxDepth === void 0) { maxDepth = 2; }
  10653. if (!this._submeshesOctree) {
  10654. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10655. }
  10656. this.computeWorldMatrix(true);
  10657. // Update octree
  10658. var bbox = this.getBoundingInfo().boundingBox;
  10659. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10660. return this._submeshesOctree;
  10661. };
  10662. // Collisions
  10663. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10664. this._generatePointsArray();
  10665. // Transformation
  10666. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10667. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10668. subMesh._lastColliderWorldVertices = [];
  10669. subMesh._trianglePlanes = [];
  10670. var start = subMesh.verticesStart;
  10671. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10672. for (var i = start; i < end; i++) {
  10673. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10674. }
  10675. }
  10676. // Collide
  10677. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  10678. };
  10679. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10680. var subMeshes;
  10681. var len;
  10682. // Octrees
  10683. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10684. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10685. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10686. len = intersections.length;
  10687. subMeshes = intersections.data;
  10688. }
  10689. else {
  10690. subMeshes = this.subMeshes;
  10691. len = subMeshes.length;
  10692. }
  10693. for (var index = 0; index < len; index++) {
  10694. var subMesh = subMeshes[index];
  10695. // Bounding test
  10696. if (len > 1 && !subMesh._checkCollision(collider))
  10697. continue;
  10698. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10699. }
  10700. };
  10701. AbstractMesh.prototype._checkCollision = function (collider) {
  10702. // Bounding box test
  10703. if (!this._boundingInfo._checkCollision(collider))
  10704. return;
  10705. // Transformation matrix
  10706. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10707. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10708. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10709. };
  10710. // Picking
  10711. AbstractMesh.prototype._generatePointsArray = function () {
  10712. return false;
  10713. };
  10714. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10715. var pickingInfo = new BABYLON.PickingInfo();
  10716. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10717. return pickingInfo;
  10718. }
  10719. if (!this._generatePointsArray()) {
  10720. return pickingInfo;
  10721. }
  10722. var intersectInfo = null;
  10723. // Octrees
  10724. var subMeshes;
  10725. var len;
  10726. if (this._submeshesOctree && this.useOctreeForPicking) {
  10727. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10728. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10729. len = intersections.length;
  10730. subMeshes = intersections.data;
  10731. }
  10732. else {
  10733. subMeshes = this.subMeshes;
  10734. len = subMeshes.length;
  10735. }
  10736. for (var index = 0; index < len; index++) {
  10737. var subMesh = subMeshes[index];
  10738. // Bounding test
  10739. if (len > 1 && !subMesh.canIntersects(ray))
  10740. continue;
  10741. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10742. if (currentIntersectInfo) {
  10743. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10744. intersectInfo = currentIntersectInfo;
  10745. intersectInfo.subMeshId = index;
  10746. if (fastCheck) {
  10747. break;
  10748. }
  10749. }
  10750. }
  10751. }
  10752. if (intersectInfo) {
  10753. // Get picked point
  10754. var world = this.getWorldMatrix();
  10755. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10756. var direction = ray.direction.clone();
  10757. direction = direction.scale(intersectInfo.distance);
  10758. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10759. var pickedPoint = worldOrigin.add(worldDirection);
  10760. // Return result
  10761. pickingInfo.hit = true;
  10762. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10763. pickingInfo.pickedPoint = pickedPoint;
  10764. pickingInfo.pickedMesh = this;
  10765. pickingInfo.bu = intersectInfo.bu;
  10766. pickingInfo.bv = intersectInfo.bv;
  10767. pickingInfo.faceId = intersectInfo.faceId;
  10768. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10769. return pickingInfo;
  10770. }
  10771. return pickingInfo;
  10772. };
  10773. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10774. return null;
  10775. };
  10776. AbstractMesh.prototype.releaseSubMeshes = function () {
  10777. if (this.subMeshes) {
  10778. while (this.subMeshes.length) {
  10779. this.subMeshes[0].dispose();
  10780. }
  10781. }
  10782. else {
  10783. this.subMeshes = new Array();
  10784. }
  10785. };
  10786. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10787. var index;
  10788. // Physics
  10789. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  10790. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  10791. }
  10792. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10793. var other = this._intersectionsInProgress[index];
  10794. var pos = other._intersectionsInProgress.indexOf(this);
  10795. other._intersectionsInProgress.splice(pos, 1);
  10796. }
  10797. this._intersectionsInProgress = [];
  10798. // SubMeshes
  10799. this.releaseSubMeshes();
  10800. // Remove from scene
  10801. this.getScene().removeMesh(this);
  10802. if (!doNotRecurse) {
  10803. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10804. if (this.getScene().particleSystems[index].emitter === this) {
  10805. this.getScene().particleSystems[index].dispose();
  10806. index--;
  10807. }
  10808. }
  10809. // Children
  10810. var objects = this.getScene().meshes.slice(0);
  10811. for (index = 0; index < objects.length; index++) {
  10812. if (objects[index].parent === this) {
  10813. objects[index].dispose();
  10814. }
  10815. }
  10816. }
  10817. else {
  10818. for (index = 0; index < this.getScene().meshes.length; index++) {
  10819. var obj = this.getScene().meshes[index];
  10820. if (obj.parent === this) {
  10821. obj.parent = null;
  10822. obj.computeWorldMatrix(true);
  10823. }
  10824. }
  10825. }
  10826. this._onAfterWorldMatrixUpdate = [];
  10827. this._isDisposed = true;
  10828. // Callback
  10829. if (this.onDispose) {
  10830. this.onDispose();
  10831. }
  10832. };
  10833. // Statics
  10834. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10835. AbstractMesh._BILLBOARDMODE_X = 1;
  10836. AbstractMesh._BILLBOARDMODE_Y = 2;
  10837. AbstractMesh._BILLBOARDMODE_Z = 4;
  10838. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10839. return AbstractMesh;
  10840. })(BABYLON.Node);
  10841. BABYLON.AbstractMesh = AbstractMesh;
  10842. })(BABYLON || (BABYLON = {}));
  10843. //# sourceMappingURL=babylon.abstractMesh.js.map
  10844. var BABYLON;
  10845. (function (BABYLON) {
  10846. var _InstancesBatch = (function () {
  10847. function _InstancesBatch() {
  10848. this.mustReturn = false;
  10849. this.visibleInstances = new Array();
  10850. this.renderSelf = new Array();
  10851. }
  10852. return _InstancesBatch;
  10853. })();
  10854. BABYLON._InstancesBatch = _InstancesBatch;
  10855. var Mesh = (function (_super) {
  10856. __extends(Mesh, _super);
  10857. /**
  10858. * @constructor
  10859. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  10860. * @param {Scene} scene - The scene to add this mesh to.
  10861. * @param {Node} parent - The parent of this mesh, if it has one
  10862. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  10863. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  10864. * When false, achieved by calling a clone(), also passing False.
  10865. * This will make creation of children, recursive.
  10866. */
  10867. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  10868. if (parent === void 0) { parent = null; }
  10869. _super.call(this, name, scene);
  10870. // Members
  10871. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10872. this.instances = new Array();
  10873. this._LODLevels = new Array();
  10874. this._onBeforeRenderCallbacks = new Array();
  10875. this._onAfterRenderCallbacks = new Array();
  10876. this._visibleInstances = {};
  10877. this._renderIdForInstances = new Array();
  10878. this._batchCache = new _InstancesBatch();
  10879. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  10880. this._sideOrientation = Mesh._DEFAULTSIDE;
  10881. if (source) {
  10882. // Geometry
  10883. if (source._geometry) {
  10884. source._geometry.applyToMesh(this);
  10885. }
  10886. // Deep copy
  10887. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  10888. // Material
  10889. this.material = source.material;
  10890. if (!doNotCloneChildren) {
  10891. for (var index = 0; index < scene.meshes.length; index++) {
  10892. var mesh = scene.meshes[index];
  10893. if (mesh.parent === source) {
  10894. // doNotCloneChildren is always going to be False
  10895. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  10896. }
  10897. }
  10898. }
  10899. for (index = 0; index < scene.particleSystems.length; index++) {
  10900. var system = scene.particleSystems[index];
  10901. if (system.emitter === source) {
  10902. system.clone(system.name, this);
  10903. }
  10904. }
  10905. this.computeWorldMatrix(true);
  10906. }
  10907. // Parent
  10908. if (parent !== null) {
  10909. this.parent = parent;
  10910. }
  10911. }
  10912. Object.defineProperty(Mesh, "FRONTSIDE", {
  10913. get: function () {
  10914. return Mesh._FRONTSIDE;
  10915. },
  10916. enumerable: true,
  10917. configurable: true
  10918. });
  10919. Object.defineProperty(Mesh, "BACKSIDE", {
  10920. get: function () {
  10921. return Mesh._BACKSIDE;
  10922. },
  10923. enumerable: true,
  10924. configurable: true
  10925. });
  10926. Object.defineProperty(Mesh, "DOUBLESIDE", {
  10927. get: function () {
  10928. return Mesh._DOUBLESIDE;
  10929. },
  10930. enumerable: true,
  10931. configurable: true
  10932. });
  10933. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  10934. get: function () {
  10935. return Mesh._DEFAULTSIDE;
  10936. },
  10937. enumerable: true,
  10938. configurable: true
  10939. });
  10940. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  10941. // Methods
  10942. get: function () {
  10943. return this._LODLevels.length > 0;
  10944. },
  10945. enumerable: true,
  10946. configurable: true
  10947. });
  10948. Mesh.prototype._sortLODLevels = function () {
  10949. this._LODLevels.sort(function (a, b) {
  10950. if (a.distance < b.distance) {
  10951. return 1;
  10952. }
  10953. if (a.distance > b.distance) {
  10954. return -1;
  10955. }
  10956. return 0;
  10957. });
  10958. };
  10959. /**
  10960. * Add a mesh as LOD level triggered at the given distance.
  10961. * @param {number} distance - the distance from the center of the object to show this level
  10962. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  10963. * @return {BABYLON.Mesh} this mesh (for chaining)
  10964. */
  10965. Mesh.prototype.addLODLevel = function (distance, mesh) {
  10966. if (mesh && mesh._masterMesh) {
  10967. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  10968. return this;
  10969. }
  10970. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  10971. this._LODLevels.push(level);
  10972. if (mesh) {
  10973. mesh._masterMesh = this;
  10974. }
  10975. this._sortLODLevels();
  10976. return this;
  10977. };
  10978. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  10979. for (var index = 0; index < this._LODLevels.length; index++) {
  10980. var level = this._LODLevels[index];
  10981. if (level.distance === distance) {
  10982. return level.mesh;
  10983. }
  10984. }
  10985. return null;
  10986. };
  10987. /**
  10988. * Remove a mesh from the LOD array
  10989. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  10990. * @return {BABYLON.Mesh} this mesh (for chaining)
  10991. */
  10992. Mesh.prototype.removeLODLevel = function (mesh) {
  10993. for (var index = 0; index < this._LODLevels.length; index++) {
  10994. if (this._LODLevels[index].mesh === mesh) {
  10995. this._LODLevels.splice(index, 1);
  10996. if (mesh) {
  10997. mesh._masterMesh = null;
  10998. }
  10999. }
  11000. }
  11001. this._sortLODLevels();
  11002. return this;
  11003. };
  11004. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  11005. if (!this._LODLevels || this._LODLevels.length === 0) {
  11006. return this;
  11007. }
  11008. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  11009. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  11010. if (this.onLODLevelSelection) {
  11011. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  11012. }
  11013. return this;
  11014. }
  11015. for (var index = 0; index < this._LODLevels.length; index++) {
  11016. var level = this._LODLevels[index];
  11017. if (level.distance < distanceToCamera) {
  11018. if (level.mesh) {
  11019. level.mesh._preActivate();
  11020. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  11021. }
  11022. if (this.onLODLevelSelection) {
  11023. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  11024. }
  11025. return level.mesh;
  11026. }
  11027. }
  11028. if (this.onLODLevelSelection) {
  11029. this.onLODLevelSelection(distanceToCamera, this, this);
  11030. }
  11031. return this;
  11032. };
  11033. Object.defineProperty(Mesh.prototype, "geometry", {
  11034. get: function () {
  11035. return this._geometry;
  11036. },
  11037. enumerable: true,
  11038. configurable: true
  11039. });
  11040. Mesh.prototype.getTotalVertices = function () {
  11041. if (!this._geometry) {
  11042. return 0;
  11043. }
  11044. return this._geometry.getTotalVertices();
  11045. };
  11046. Mesh.prototype.getVerticesData = function (kind) {
  11047. if (!this._geometry) {
  11048. return null;
  11049. }
  11050. return this._geometry.getVerticesData(kind);
  11051. };
  11052. Mesh.prototype.getVertexBuffer = function (kind) {
  11053. if (!this._geometry) {
  11054. return undefined;
  11055. }
  11056. return this._geometry.getVertexBuffer(kind);
  11057. };
  11058. Mesh.prototype.isVerticesDataPresent = function (kind) {
  11059. if (!this._geometry) {
  11060. if (this._delayInfo) {
  11061. return this._delayInfo.indexOf(kind) !== -1;
  11062. }
  11063. return false;
  11064. }
  11065. return this._geometry.isVerticesDataPresent(kind);
  11066. };
  11067. Mesh.prototype.getVerticesDataKinds = function () {
  11068. if (!this._geometry) {
  11069. var result = [];
  11070. if (this._delayInfo) {
  11071. for (var kind in this._delayInfo) {
  11072. result.push(kind);
  11073. }
  11074. }
  11075. return result;
  11076. }
  11077. return this._geometry.getVerticesDataKinds();
  11078. };
  11079. Mesh.prototype.getTotalIndices = function () {
  11080. if (!this._geometry) {
  11081. return 0;
  11082. }
  11083. return this._geometry.getTotalIndices();
  11084. };
  11085. Mesh.prototype.getIndices = function () {
  11086. if (!this._geometry) {
  11087. return [];
  11088. }
  11089. return this._geometry.getIndices();
  11090. };
  11091. Object.defineProperty(Mesh.prototype, "isBlocked", {
  11092. get: function () {
  11093. return this._masterMesh !== null && this._masterMesh !== undefined;
  11094. },
  11095. enumerable: true,
  11096. configurable: true
  11097. });
  11098. Mesh.prototype.isReady = function () {
  11099. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11100. return false;
  11101. }
  11102. return _super.prototype.isReady.call(this);
  11103. };
  11104. Mesh.prototype.isDisposed = function () {
  11105. return this._isDisposed;
  11106. };
  11107. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  11108. get: function () {
  11109. return this._sideOrientation;
  11110. },
  11111. set: function (sideO) {
  11112. this._sideOrientation = sideO;
  11113. },
  11114. enumerable: true,
  11115. configurable: true
  11116. });
  11117. // Methods
  11118. Mesh.prototype._preActivate = function () {
  11119. var sceneRenderId = this.getScene().getRenderId();
  11120. if (this._preActivateId === sceneRenderId) {
  11121. return;
  11122. }
  11123. this._preActivateId = sceneRenderId;
  11124. this._visibleInstances = null;
  11125. };
  11126. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  11127. if (!this._visibleInstances) {
  11128. this._visibleInstances = {};
  11129. this._visibleInstances.defaultRenderId = renderId;
  11130. this._visibleInstances.selfDefaultRenderId = this._renderId;
  11131. }
  11132. if (!this._visibleInstances[renderId]) {
  11133. this._visibleInstances[renderId] = new Array();
  11134. }
  11135. this._visibleInstances[renderId].push(instance);
  11136. };
  11137. Mesh.prototype.refreshBoundingInfo = function () {
  11138. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11139. if (data) {
  11140. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  11141. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11142. }
  11143. if (this.subMeshes) {
  11144. for (var index = 0; index < this.subMeshes.length; index++) {
  11145. this.subMeshes[index].refreshBoundingInfo();
  11146. }
  11147. }
  11148. this._updateBoundingInfo();
  11149. };
  11150. Mesh.prototype._createGlobalSubMesh = function () {
  11151. var totalVertices = this.getTotalVertices();
  11152. if (!totalVertices || !this.getIndices()) {
  11153. return null;
  11154. }
  11155. this.releaseSubMeshes();
  11156. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  11157. };
  11158. Mesh.prototype.subdivide = function (count) {
  11159. if (count < 1) {
  11160. return;
  11161. }
  11162. var totalIndices = this.getTotalIndices();
  11163. var subdivisionSize = (totalIndices / count) | 0;
  11164. var offset = 0;
  11165. while (subdivisionSize % 3 !== 0) {
  11166. subdivisionSize++;
  11167. }
  11168. this.releaseSubMeshes();
  11169. for (var index = 0; index < count; index++) {
  11170. if (offset >= totalIndices) {
  11171. break;
  11172. }
  11173. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  11174. offset += subdivisionSize;
  11175. }
  11176. this.synchronizeInstances();
  11177. };
  11178. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11179. if (kind instanceof Array) {
  11180. var temp = data;
  11181. data = kind;
  11182. kind = temp;
  11183. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  11184. }
  11185. if (!this._geometry) {
  11186. var vertexData = new BABYLON.VertexData();
  11187. vertexData.set(data, kind);
  11188. var scene = this.getScene();
  11189. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  11190. }
  11191. else {
  11192. this._geometry.setVerticesData(kind, data, updatable, stride);
  11193. }
  11194. };
  11195. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11196. if (!this._geometry) {
  11197. return;
  11198. }
  11199. if (!makeItUnique) {
  11200. this._geometry.updateVerticesData(kind, data, updateExtends);
  11201. }
  11202. else {
  11203. this.makeGeometryUnique();
  11204. this.updateVerticesData(kind, data, updateExtends, false);
  11205. }
  11206. };
  11207. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  11208. if (!this._geometry) {
  11209. return;
  11210. }
  11211. if (!makeItUnique) {
  11212. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  11213. }
  11214. else {
  11215. this.makeGeometryUnique();
  11216. this.updateVerticesDataDirectly(kind, data, offset, false);
  11217. }
  11218. };
  11219. // Mesh positions update function :
  11220. // updates the mesh positions according to the positionFunction returned values.
  11221. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  11222. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  11223. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  11224. if (computeNormals === void 0) { computeNormals = true; }
  11225. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11226. positionFunction(positions);
  11227. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  11228. if (computeNormals) {
  11229. var indices = this.getIndices();
  11230. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11231. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  11232. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  11233. }
  11234. };
  11235. Mesh.prototype.makeGeometryUnique = function () {
  11236. if (!this._geometry) {
  11237. return;
  11238. }
  11239. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  11240. geometry.applyToMesh(this);
  11241. };
  11242. Mesh.prototype.setIndices = function (indices, totalVertices) {
  11243. if (!this._geometry) {
  11244. var vertexData = new BABYLON.VertexData();
  11245. vertexData.indices = indices;
  11246. var scene = this.getScene();
  11247. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  11248. }
  11249. else {
  11250. this._geometry.setIndices(indices, totalVertices);
  11251. }
  11252. };
  11253. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  11254. var engine = this.getScene().getEngine();
  11255. // Wireframe
  11256. var indexToBind;
  11257. switch (fillMode) {
  11258. case BABYLON.Material.PointFillMode:
  11259. indexToBind = null;
  11260. break;
  11261. case BABYLON.Material.WireFrameFillMode:
  11262. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  11263. break;
  11264. default:
  11265. case BABYLON.Material.TriangleFillMode:
  11266. indexToBind = this._geometry.getIndexBuffer();
  11267. break;
  11268. }
  11269. // VBOs
  11270. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  11271. };
  11272. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  11273. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  11274. return;
  11275. }
  11276. var engine = this.getScene().getEngine();
  11277. switch (fillMode) {
  11278. case BABYLON.Material.PointFillMode:
  11279. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  11280. break;
  11281. case BABYLON.Material.WireFrameFillMode:
  11282. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  11283. break;
  11284. default:
  11285. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  11286. }
  11287. };
  11288. Mesh.prototype.registerBeforeRender = function (func) {
  11289. this._onBeforeRenderCallbacks.push(func);
  11290. };
  11291. Mesh.prototype.unregisterBeforeRender = function (func) {
  11292. var index = this._onBeforeRenderCallbacks.indexOf(func);
  11293. if (index > -1) {
  11294. this._onBeforeRenderCallbacks.splice(index, 1);
  11295. }
  11296. };
  11297. Mesh.prototype.registerAfterRender = function (func) {
  11298. this._onAfterRenderCallbacks.push(func);
  11299. };
  11300. Mesh.prototype.unregisterAfterRender = function (func) {
  11301. var index = this._onAfterRenderCallbacks.indexOf(func);
  11302. if (index > -1) {
  11303. this._onAfterRenderCallbacks.splice(index, 1);
  11304. }
  11305. };
  11306. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  11307. var scene = this.getScene();
  11308. this._batchCache.mustReturn = false;
  11309. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  11310. this._batchCache.visibleInstances[subMeshId] = null;
  11311. if (this._visibleInstances) {
  11312. var currentRenderId = scene.getRenderId();
  11313. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  11314. var selfRenderId = this._renderId;
  11315. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  11316. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  11317. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  11318. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  11319. }
  11320. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  11321. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  11322. this._batchCache.mustReturn = true;
  11323. return this._batchCache;
  11324. }
  11325. if (currentRenderId !== selfRenderId) {
  11326. this._batchCache.renderSelf[subMeshId] = false;
  11327. }
  11328. }
  11329. this._renderIdForInstances[subMeshId] = currentRenderId;
  11330. }
  11331. return this._batchCache;
  11332. };
  11333. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  11334. var visibleInstances = batch.visibleInstances[subMesh._id];
  11335. var matricesCount = visibleInstances.length + 1;
  11336. var bufferSize = matricesCount * 16 * 4;
  11337. while (this._instancesBufferSize < bufferSize) {
  11338. this._instancesBufferSize *= 2;
  11339. }
  11340. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  11341. if (this._worldMatricesInstancesBuffer) {
  11342. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11343. }
  11344. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  11345. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  11346. }
  11347. var offset = 0;
  11348. var instancesCount = 0;
  11349. var world = this.getWorldMatrix();
  11350. if (batch.renderSelf[subMesh._id]) {
  11351. world.copyToArray(this._worldMatricesInstancesArray, offset);
  11352. offset += 16;
  11353. instancesCount++;
  11354. }
  11355. if (visibleInstances) {
  11356. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  11357. var instance = visibleInstances[instanceIndex];
  11358. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  11359. offset += 16;
  11360. instancesCount++;
  11361. }
  11362. }
  11363. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  11364. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  11365. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  11366. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  11367. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  11368. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  11369. this._draw(subMesh, fillMode, instancesCount);
  11370. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  11371. };
  11372. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  11373. var scene = this.getScene();
  11374. var engine = scene.getEngine();
  11375. if (hardwareInstancedRendering) {
  11376. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  11377. }
  11378. else {
  11379. if (batch.renderSelf[subMesh._id]) {
  11380. // Draw
  11381. if (onBeforeDraw) {
  11382. onBeforeDraw(false, this.getWorldMatrix());
  11383. }
  11384. this._draw(subMesh, fillMode);
  11385. }
  11386. if (batch.visibleInstances[subMesh._id]) {
  11387. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  11388. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  11389. // World
  11390. var world = instance.getWorldMatrix();
  11391. if (onBeforeDraw) {
  11392. onBeforeDraw(true, world);
  11393. }
  11394. // Draw
  11395. this._draw(subMesh, fillMode);
  11396. }
  11397. }
  11398. }
  11399. };
  11400. Mesh.prototype.render = function (subMesh) {
  11401. var scene = this.getScene();
  11402. // Managing instances
  11403. var batch = this._getInstancesRenderList(subMesh._id);
  11404. if (batch.mustReturn) {
  11405. return;
  11406. }
  11407. // Checking geometry state
  11408. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  11409. return;
  11410. }
  11411. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  11412. this._onBeforeRenderCallbacks[callbackIndex](this);
  11413. }
  11414. var engine = scene.getEngine();
  11415. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  11416. // Material
  11417. var effectiveMaterial = subMesh.getMaterial();
  11418. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  11419. return;
  11420. }
  11421. // Outline - step 1
  11422. var savedDepthWrite = engine.getDepthWrite();
  11423. if (this.renderOutline) {
  11424. engine.setDepthWrite(false);
  11425. scene.getOutlineRenderer().render(subMesh, batch);
  11426. engine.setDepthWrite(savedDepthWrite);
  11427. }
  11428. effectiveMaterial._preBind();
  11429. var effect = effectiveMaterial.getEffect();
  11430. // Bind
  11431. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  11432. this._bind(subMesh, effect, fillMode);
  11433. var world = this.getWorldMatrix();
  11434. effectiveMaterial.bind(world, this);
  11435. // Draw
  11436. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  11437. if (isInstance) {
  11438. effectiveMaterial.bindOnlyWorldMatrix(world);
  11439. }
  11440. });
  11441. // Unbind
  11442. effectiveMaterial.unbind();
  11443. // Outline - step 2
  11444. if (this.renderOutline && savedDepthWrite) {
  11445. engine.setDepthWrite(true);
  11446. engine.setColorWrite(false);
  11447. scene.getOutlineRenderer().render(subMesh, batch);
  11448. engine.setColorWrite(true);
  11449. }
  11450. // Overlay
  11451. if (this.renderOverlay) {
  11452. var currentMode = engine.getAlphaMode();
  11453. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11454. scene.getOutlineRenderer().render(subMesh, batch, true);
  11455. engine.setAlphaMode(currentMode);
  11456. }
  11457. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  11458. this._onAfterRenderCallbacks[callbackIndex](this);
  11459. }
  11460. };
  11461. Mesh.prototype.getEmittedParticleSystems = function () {
  11462. var results = new Array();
  11463. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  11464. var particleSystem = this.getScene().particleSystems[index];
  11465. if (particleSystem.emitter === this) {
  11466. results.push(particleSystem);
  11467. }
  11468. }
  11469. return results;
  11470. };
  11471. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  11472. var results = new Array();
  11473. var descendants = this.getDescendants();
  11474. descendants.push(this);
  11475. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  11476. var particleSystem = this.getScene().particleSystems[index];
  11477. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  11478. results.push(particleSystem);
  11479. }
  11480. }
  11481. return results;
  11482. };
  11483. Mesh.prototype.getChildren = function () {
  11484. var results = [];
  11485. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11486. var mesh = this.getScene().meshes[index];
  11487. if (mesh.parent === this) {
  11488. results.push(mesh);
  11489. }
  11490. }
  11491. return results;
  11492. };
  11493. Mesh.prototype._checkDelayState = function () {
  11494. var _this = this;
  11495. var that = this;
  11496. var scene = this.getScene();
  11497. if (this._geometry) {
  11498. this._geometry.load(scene);
  11499. }
  11500. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11501. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  11502. scene._addPendingData(that);
  11503. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  11504. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  11505. if (data instanceof ArrayBuffer) {
  11506. _this._delayLoadingFunction(data, _this);
  11507. }
  11508. else {
  11509. _this._delayLoadingFunction(JSON.parse(data), _this);
  11510. }
  11511. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11512. scene._removePendingData(_this);
  11513. }, function () {
  11514. }, scene.database, getBinaryData);
  11515. }
  11516. };
  11517. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  11518. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11519. return false;
  11520. }
  11521. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  11522. return false;
  11523. }
  11524. this._checkDelayState();
  11525. return true;
  11526. };
  11527. Mesh.prototype.setMaterialByID = function (id) {
  11528. var materials = this.getScene().materials;
  11529. for (var index = 0; index < materials.length; index++) {
  11530. if (materials[index].id === id) {
  11531. this.material = materials[index];
  11532. return;
  11533. }
  11534. }
  11535. // Multi
  11536. var multiMaterials = this.getScene().multiMaterials;
  11537. for (index = 0; index < multiMaterials.length; index++) {
  11538. if (multiMaterials[index].id === id) {
  11539. this.material = multiMaterials[index];
  11540. return;
  11541. }
  11542. }
  11543. };
  11544. Mesh.prototype.getAnimatables = function () {
  11545. var results = [];
  11546. if (this.material) {
  11547. results.push(this.material);
  11548. }
  11549. if (this.skeleton) {
  11550. results.push(this.skeleton);
  11551. }
  11552. return results;
  11553. };
  11554. // Geometry
  11555. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  11556. // Position
  11557. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  11558. return;
  11559. }
  11560. this._resetPointsArrayCache();
  11561. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11562. var temp = [];
  11563. for (var index = 0; index < data.length; index += 3) {
  11564. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11565. }
  11566. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  11567. // Normals
  11568. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  11569. return;
  11570. }
  11571. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11572. for (index = 0; index < data.length; index += 3) {
  11573. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11574. }
  11575. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  11576. };
  11577. // Cache
  11578. Mesh.prototype._resetPointsArrayCache = function () {
  11579. this._positions = null;
  11580. };
  11581. Mesh.prototype._generatePointsArray = function () {
  11582. if (this._positions)
  11583. return true;
  11584. this._positions = [];
  11585. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11586. if (!data) {
  11587. return false;
  11588. }
  11589. for (var index = 0; index < data.length; index += 3) {
  11590. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  11591. }
  11592. return true;
  11593. };
  11594. // Clone
  11595. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11596. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  11597. };
  11598. // Dispose
  11599. Mesh.prototype.dispose = function (doNotRecurse) {
  11600. if (this._geometry) {
  11601. this._geometry.releaseForMesh(this, true);
  11602. }
  11603. // Instances
  11604. if (this._worldMatricesInstancesBuffer) {
  11605. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11606. this._worldMatricesInstancesBuffer = null;
  11607. }
  11608. while (this.instances.length) {
  11609. this.instances[0].dispose();
  11610. }
  11611. _super.prototype.dispose.call(this, doNotRecurse);
  11612. };
  11613. // Geometric tools
  11614. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  11615. var _this = this;
  11616. var scene = this.getScene();
  11617. var onload = function (img) {
  11618. // Getting height map data
  11619. var canvas = document.createElement("canvas");
  11620. var context = canvas.getContext("2d");
  11621. var heightMapWidth = img.width;
  11622. var heightMapHeight = img.height;
  11623. canvas.width = heightMapWidth;
  11624. canvas.height = heightMapHeight;
  11625. context.drawImage(img, 0, 0);
  11626. // Create VertexData from map data
  11627. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11628. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11629. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  11630. //execute success callback, if set
  11631. if (onSuccess) {
  11632. onSuccess(_this);
  11633. }
  11634. };
  11635. BABYLON.Tools.LoadImage(url, onload, function () {
  11636. }, scene.database);
  11637. };
  11638. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  11639. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11640. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  11641. return;
  11642. }
  11643. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11644. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11645. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11646. var position = BABYLON.Vector3.Zero();
  11647. var normal = BABYLON.Vector3.Zero();
  11648. var uv = BABYLON.Vector2.Zero();
  11649. for (var index = 0; index < positions.length; index += 3) {
  11650. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  11651. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  11652. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  11653. // Compute height
  11654. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  11655. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  11656. var pos = (u + v * heightMapWidth) * 4;
  11657. var r = buffer[pos] / 255.0;
  11658. var g = buffer[pos + 1] / 255.0;
  11659. var b = buffer[pos + 2] / 255.0;
  11660. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  11661. normal.normalize();
  11662. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  11663. position = position.add(normal);
  11664. position.toArray(positions, index);
  11665. }
  11666. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  11667. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  11668. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  11669. };
  11670. Mesh.prototype.convertToFlatShadedMesh = function () {
  11671. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  11672. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  11673. var kinds = this.getVerticesDataKinds();
  11674. var vbs = [];
  11675. var data = [];
  11676. var newdata = [];
  11677. var updatableNormals = false;
  11678. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11679. var kind = kinds[kindIndex];
  11680. var vertexBuffer = this.getVertexBuffer(kind);
  11681. if (kind === BABYLON.VertexBuffer.NormalKind) {
  11682. updatableNormals = vertexBuffer.isUpdatable();
  11683. kinds.splice(kindIndex, 1);
  11684. kindIndex--;
  11685. continue;
  11686. }
  11687. vbs[kind] = vertexBuffer;
  11688. data[kind] = vbs[kind].getData();
  11689. newdata[kind] = [];
  11690. }
  11691. // Save previous submeshes
  11692. var previousSubmeshes = this.subMeshes.slice(0);
  11693. var indices = this.getIndices();
  11694. var totalIndices = this.getTotalIndices();
  11695. for (var index = 0; index < totalIndices; index++) {
  11696. var vertexIndex = indices[index];
  11697. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11698. kind = kinds[kindIndex];
  11699. var stride = vbs[kind].getStrideSize();
  11700. for (var offset = 0; offset < stride; offset++) {
  11701. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  11702. }
  11703. }
  11704. }
  11705. // Updating faces & normal
  11706. var normals = [];
  11707. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  11708. for (index = 0; index < totalIndices; index += 3) {
  11709. indices[index] = index;
  11710. indices[index + 1] = index + 1;
  11711. indices[index + 2] = index + 2;
  11712. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  11713. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  11714. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  11715. var p1p2 = p1.subtract(p2);
  11716. var p3p2 = p3.subtract(p2);
  11717. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  11718. for (var localIndex = 0; localIndex < 3; localIndex++) {
  11719. normals.push(normal.x);
  11720. normals.push(normal.y);
  11721. normals.push(normal.z);
  11722. }
  11723. }
  11724. this.setIndices(indices);
  11725. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  11726. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11727. kind = kinds[kindIndex];
  11728. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  11729. }
  11730. // Updating submeshes
  11731. this.releaseSubMeshes();
  11732. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  11733. var previousOne = previousSubmeshes[submeshIndex];
  11734. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  11735. }
  11736. this.synchronizeInstances();
  11737. };
  11738. // Instances
  11739. Mesh.prototype.createInstance = function (name) {
  11740. return new BABYLON.InstancedMesh(name, this);
  11741. };
  11742. Mesh.prototype.synchronizeInstances = function () {
  11743. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  11744. var instance = this.instances[instanceIndex];
  11745. instance._syncSubMeshes();
  11746. }
  11747. };
  11748. /**
  11749. * Simplify the mesh according to the given array of settings.
  11750. * Function will return immediately and will simplify async.
  11751. * @param settings a collection of simplification settings.
  11752. * @param parallelProcessing should all levels calculate parallel or one after the other.
  11753. * @param type the type of simplification to run.
  11754. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  11755. */
  11756. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  11757. if (parallelProcessing === void 0) { parallelProcessing = true; }
  11758. if (simplificationType === void 0) { simplificationType = 0 /* QUADRATIC */; }
  11759. this.getScene().simplificationQueue.addTask({
  11760. settings: settings,
  11761. parallelProcessing: parallelProcessing,
  11762. mesh: this,
  11763. simplificationType: simplificationType,
  11764. successCallback: successCallback
  11765. });
  11766. };
  11767. /**
  11768. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  11769. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  11770. * This should be used together with the simplification to avoid disappearing triangles.
  11771. * @param successCallback an optional success callback to be called after the optimization finished.
  11772. */
  11773. Mesh.prototype.optimizeIndices = function (successCallback) {
  11774. var _this = this;
  11775. var indices = this.getIndices();
  11776. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11777. var vectorPositions = [];
  11778. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  11779. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  11780. }
  11781. var dupes = [];
  11782. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  11783. var realPos = vectorPositions.length - 1 - iteration;
  11784. var testedPosition = vectorPositions[realPos];
  11785. for (var j = 0; j < realPos; ++j) {
  11786. var againstPosition = vectorPositions[j];
  11787. if (testedPosition.equals(againstPosition)) {
  11788. dupes[realPos] = j;
  11789. break;
  11790. }
  11791. }
  11792. }, function () {
  11793. for (var i = 0; i < indices.length; ++i) {
  11794. indices[i] = dupes[indices[i]] || indices[i];
  11795. }
  11796. //indices are now reordered
  11797. var originalSubMeshes = _this.subMeshes.slice(0);
  11798. _this.setIndices(indices);
  11799. _this.subMeshes = originalSubMeshes;
  11800. if (successCallback) {
  11801. successCallback(_this);
  11802. }
  11803. });
  11804. };
  11805. // Statics
  11806. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  11807. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11808. if (ribbonInstance === void 0) { ribbonInstance = null; }
  11809. if (ribbonInstance) {
  11810. // positionFunction : ribbon case
  11811. // only pathArray and sideOrientation parameters are taken into account for positions update
  11812. var positionsOfRibbon = function (pathArray, sideOrientation) {
  11813. var positionFunction = function (positions) {
  11814. var minlg = pathArray[0].length;
  11815. var i = 0;
  11816. var ns = (sideOrientation == BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  11817. for (var si = 1; si <= ns; si++) {
  11818. for (var p = 0; p < pathArray.length; p++) {
  11819. var path = pathArray[p];
  11820. var l = path.length;
  11821. minlg = (minlg < l) ? minlg : l;
  11822. var j = 0;
  11823. while (j < minlg) {
  11824. positions[i] = path[j].x;
  11825. positions[i + 1] = path[j].y;
  11826. positions[i + 2] = path[j].z;
  11827. j++;
  11828. i += 3;
  11829. }
  11830. }
  11831. }
  11832. };
  11833. return positionFunction;
  11834. };
  11835. var sideOrientation = ribbonInstance.sideOrientation;
  11836. var positionFunction = positionsOfRibbon(pathArray, sideOrientation);
  11837. ribbonInstance.updateMeshPositions(positionFunction, true);
  11838. return ribbonInstance;
  11839. }
  11840. else {
  11841. var ribbon = new Mesh(name, scene);
  11842. ribbon.sideOrientation = sideOrientation;
  11843. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  11844. vertexData.applyToMesh(ribbon, updatable);
  11845. return ribbon;
  11846. }
  11847. };
  11848. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  11849. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11850. var disc = new Mesh(name, scene);
  11851. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  11852. vertexData.applyToMesh(disc, updatable);
  11853. return disc;
  11854. };
  11855. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  11856. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11857. var box = new Mesh(name, scene);
  11858. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  11859. vertexData.applyToMesh(box, updatable);
  11860. return box;
  11861. };
  11862. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  11863. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11864. var sphere = new Mesh(name, scene);
  11865. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  11866. vertexData.applyToMesh(sphere, updatable);
  11867. return sphere;
  11868. };
  11869. // Cylinder and cone (Code inspired by SharpDX.org)
  11870. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  11871. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11872. // subdivisions is a new parameter, we need to support old signature
  11873. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  11874. if (scene !== undefined) {
  11875. updatable = scene;
  11876. }
  11877. scene = subdivisions;
  11878. subdivisions = 1;
  11879. }
  11880. var cylinder = new Mesh(name, scene);
  11881. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  11882. vertexData.applyToMesh(cylinder, updatable);
  11883. return cylinder;
  11884. };
  11885. // Torus (Code from SharpDX.org)
  11886. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  11887. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11888. var torus = new Mesh(name, scene);
  11889. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  11890. vertexData.applyToMesh(torus, updatable);
  11891. return torus;
  11892. };
  11893. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  11894. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11895. var torusKnot = new Mesh(name, scene);
  11896. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  11897. vertexData.applyToMesh(torusKnot, updatable);
  11898. return torusKnot;
  11899. };
  11900. // Lines
  11901. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  11902. if (linesInstance === void 0) { linesInstance = null; }
  11903. if (linesInstance) {
  11904. var positionsOfLines = function (points) {
  11905. var positionFunction = function (positions) {
  11906. var i = 0;
  11907. for (var p = 0; p < points.length; p++) {
  11908. positions[i] = points[p].x;
  11909. positions[i + 1] = points[p].y;
  11910. positions[i + 2] = points[p].z;
  11911. i += 3;
  11912. }
  11913. };
  11914. return positionFunction;
  11915. };
  11916. var positionFunction = positionsOfLines(points);
  11917. linesInstance.updateMeshPositions(positionFunction, false);
  11918. return linesInstance;
  11919. }
  11920. // lines creation
  11921. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  11922. var vertexData = BABYLON.VertexData.CreateLines(points);
  11923. vertexData.applyToMesh(lines, updatable);
  11924. return lines;
  11925. };
  11926. // Extrusion
  11927. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, scene, updatable, sideOrientation, extrudedInstance) {
  11928. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11929. if (extrudedInstance === void 0) { extrudedInstance = null; }
  11930. scale = scale || 1;
  11931. rotation = rotation || 0;
  11932. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, false, scene, updatable, sideOrientation, extrudedInstance);
  11933. return extruded;
  11934. };
  11935. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, scene, updatable, sideOrientation, extrudedInstance) {
  11936. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11937. if (extrudedInstance === void 0) { extrudedInstance = null; }
  11938. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, true, scene, updatable, sideOrientation, extrudedInstance);
  11939. return extrudedCustom;
  11940. };
  11941. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, custom, scene, updtbl, side, instance) {
  11942. // extrusion geometry
  11943. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, custom) {
  11944. var tangents = path3D.getTangents();
  11945. var normals = path3D.getNormals();
  11946. var binormals = path3D.getBinormals();
  11947. var distances = path3D.getDistances();
  11948. var angle = 0;
  11949. var returnScale = function (i, distance) {
  11950. return scale;
  11951. };
  11952. var returnRotation = function (i, distance) {
  11953. return rotation;
  11954. };
  11955. var rotate = custom ? rotateFunction : returnRotation;
  11956. var scl = custom ? scaleFunction : returnScale;
  11957. var index = 0;
  11958. for (var i = 0; i < curve.length; i++) {
  11959. var shapePath = new Array();
  11960. var angleStep = rotate(i, distances[i]);
  11961. var scaleRatio = scl(i, distances[i]);
  11962. for (var p = 0; p < shape.length; p++) {
  11963. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  11964. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  11965. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  11966. shapePath.push(rotated);
  11967. }
  11968. shapePaths[index] = shapePath;
  11969. angle += angleStep;
  11970. index++;
  11971. }
  11972. return shapePaths;
  11973. };
  11974. if (instance) {
  11975. var path3D = (instance.path3D).update(curve);
  11976. var pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, custom);
  11977. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  11978. return instance;
  11979. }
  11980. // extruded shape creation
  11981. var path3D = new BABYLON.Path3D(curve);
  11982. var newShapePaths = new Array();
  11983. var pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, custom);
  11984. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  11985. extrudedGeneric.pathArray = pathArray;
  11986. extrudedGeneric.path3D = path3D;
  11987. return extrudedGeneric;
  11988. };
  11989. // Plane & ground
  11990. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  11991. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11992. var plane = new Mesh(name, scene);
  11993. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  11994. vertexData.applyToMesh(plane, updatable);
  11995. return plane;
  11996. };
  11997. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  11998. var ground = new BABYLON.GroundMesh(name, scene);
  11999. ground._setReady(false);
  12000. ground._subdivisions = subdivisions;
  12001. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  12002. vertexData.applyToMesh(ground, updatable);
  12003. ground._setReady(true);
  12004. return ground;
  12005. };
  12006. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  12007. var tiledGround = new Mesh(name, scene);
  12008. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  12009. vertexData.applyToMesh(tiledGround, updatable);
  12010. return tiledGround;
  12011. };
  12012. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  12013. var ground = new BABYLON.GroundMesh(name, scene);
  12014. ground._subdivisions = subdivisions;
  12015. ground._setReady(false);
  12016. var onload = function (img) {
  12017. // Getting height map data
  12018. var canvas = document.createElement("canvas");
  12019. var context = canvas.getContext("2d");
  12020. var heightMapWidth = img.width;
  12021. var heightMapHeight = img.height;
  12022. canvas.width = heightMapWidth;
  12023. canvas.height = heightMapHeight;
  12024. context.drawImage(img, 0, 0);
  12025. // Create VertexData from map data
  12026. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  12027. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  12028. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  12029. vertexData.applyToMesh(ground, updatable);
  12030. ground._setReady(true);
  12031. //execute ready callback, if set
  12032. if (onReady) {
  12033. onReady(ground);
  12034. }
  12035. };
  12036. BABYLON.Tools.LoadImage(url, onload, function () {
  12037. }, scene.database);
  12038. return ground;
  12039. };
  12040. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, scene, updatable, sideOrientation, tubeInstance) {
  12041. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  12042. if (tubeInstance === void 0) { tubeInstance = null; }
  12043. // tube geometry
  12044. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction) {
  12045. var tangents = path3D.getTangents();
  12046. var normals = path3D.getNormals();
  12047. var distances = path3D.getDistances();
  12048. var pi2 = Math.PI * 2;
  12049. var step = pi2 / tessellation;
  12050. var returnRadius = function (i, distance) { return radius; };
  12051. var radiusFunctionFinal = radiusFunction || returnRadius;
  12052. var circlePath;
  12053. var rad;
  12054. var normal;
  12055. var rotated;
  12056. var rotationMatrix;
  12057. var index = 0;
  12058. for (var i = 0; i < path.length; i++) {
  12059. rad = radiusFunctionFinal(i, distances[i]); // current radius
  12060. circlePath = Array(); // current circle array
  12061. normal = normals[i]; // current normal
  12062. for (var ang = 0; ang < pi2; ang += step) {
  12063. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], ang);
  12064. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  12065. circlePath.push(rotated);
  12066. }
  12067. circlePaths[index] = circlePath;
  12068. index++;
  12069. }
  12070. return circlePaths;
  12071. };
  12072. if (tubeInstance) {
  12073. var path3D = (tubeInstance.path3D).update(path);
  12074. var pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction);
  12075. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  12076. return tubeInstance;
  12077. }
  12078. // tube creation
  12079. var path3D = new BABYLON.Path3D(path);
  12080. var newPathArray = new Array();
  12081. var pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction);
  12082. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  12083. tube.pathArray = pathArray;
  12084. tube.path3D = path3D;
  12085. tube.tessellation = tessellation;
  12086. return tube;
  12087. };
  12088. // Decals
  12089. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  12090. if (angle === void 0) { angle = 0; }
  12091. var indices = sourceMesh.getIndices();
  12092. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12093. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12094. // Getting correct rotation
  12095. if (!normal) {
  12096. var target = new BABYLON.Vector3(0, 0, 1);
  12097. var camera = sourceMesh.getScene().activeCamera;
  12098. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  12099. normal = camera.globalPosition.subtract(cameraWorldTarget);
  12100. }
  12101. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  12102. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  12103. var pitch = Math.atan2(normal.y, len);
  12104. // Matrix
  12105. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  12106. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  12107. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  12108. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  12109. var vertexData = new BABYLON.VertexData();
  12110. vertexData.indices = [];
  12111. vertexData.positions = [];
  12112. vertexData.normals = [];
  12113. vertexData.uvs = [];
  12114. var currentVertexDataIndex = 0;
  12115. var extractDecalVector3 = function (indexId) {
  12116. var vertexId = indices[indexId];
  12117. var result = new BABYLON.PositionNormalVertex();
  12118. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  12119. // Send vector to decal local world
  12120. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  12121. // Get normal
  12122. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  12123. return result;
  12124. };
  12125. // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  12126. var clip = function (vertices, axis) {
  12127. if (vertices.length === 0) {
  12128. return vertices;
  12129. }
  12130. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  12131. var clipVertices = function (v0, v1) {
  12132. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  12133. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  12134. };
  12135. var result = new Array();
  12136. for (var index = 0; index < vertices.length; index += 3) {
  12137. var v1Out;
  12138. var v2Out;
  12139. var v3Out;
  12140. var total = 0;
  12141. var nV1, nV2, nV3, nV4;
  12142. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  12143. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  12144. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  12145. v1Out = d1 > 0;
  12146. v2Out = d2 > 0;
  12147. v3Out = d3 > 0;
  12148. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  12149. switch (total) {
  12150. case 0:
  12151. result.push(vertices[index]);
  12152. result.push(vertices[index + 1]);
  12153. result.push(vertices[index + 2]);
  12154. break;
  12155. case 1:
  12156. if (v1Out) {
  12157. nV1 = vertices[index + 1];
  12158. nV2 = vertices[index + 2];
  12159. nV3 = clipVertices(vertices[index], nV1);
  12160. nV4 = clipVertices(vertices[index], nV2);
  12161. }
  12162. if (v2Out) {
  12163. nV1 = vertices[index];
  12164. nV2 = vertices[index + 2];
  12165. nV3 = clipVertices(vertices[index + 1], nV1);
  12166. nV4 = clipVertices(vertices[index + 1], nV2);
  12167. result.push(nV3);
  12168. result.push(nV2.clone());
  12169. result.push(nV1.clone());
  12170. result.push(nV2.clone());
  12171. result.push(nV3.clone());
  12172. result.push(nV4);
  12173. break;
  12174. }
  12175. if (v3Out) {
  12176. nV1 = vertices[index];
  12177. nV2 = vertices[index + 1];
  12178. nV3 = clipVertices(vertices[index + 2], nV1);
  12179. nV4 = clipVertices(vertices[index + 2], nV2);
  12180. }
  12181. result.push(nV1.clone());
  12182. result.push(nV2.clone());
  12183. result.push(nV3);
  12184. result.push(nV4);
  12185. result.push(nV3.clone());
  12186. result.push(nV2.clone());
  12187. break;
  12188. case 2:
  12189. if (!v1Out) {
  12190. nV1 = vertices[index].clone();
  12191. nV2 = clipVertices(nV1, vertices[index + 1]);
  12192. nV3 = clipVertices(nV1, vertices[index + 2]);
  12193. result.push(nV1);
  12194. result.push(nV2);
  12195. result.push(nV3);
  12196. }
  12197. if (!v2Out) {
  12198. nV1 = vertices[index + 1].clone();
  12199. nV2 = clipVertices(nV1, vertices[index + 2]);
  12200. nV3 = clipVertices(nV1, vertices[index]);
  12201. result.push(nV1);
  12202. result.push(nV2);
  12203. result.push(nV3);
  12204. }
  12205. if (!v3Out) {
  12206. nV1 = vertices[index + 2].clone();
  12207. nV2 = clipVertices(nV1, vertices[index]);
  12208. nV3 = clipVertices(nV1, vertices[index + 1]);
  12209. result.push(nV1);
  12210. result.push(nV2);
  12211. result.push(nV3);
  12212. }
  12213. break;
  12214. case 3:
  12215. break;
  12216. }
  12217. }
  12218. return result;
  12219. };
  12220. for (var index = 0; index < indices.length; index += 3) {
  12221. var faceVertices = new Array();
  12222. faceVertices.push(extractDecalVector3(index));
  12223. faceVertices.push(extractDecalVector3(index + 1));
  12224. faceVertices.push(extractDecalVector3(index + 2));
  12225. // Clip
  12226. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  12227. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  12228. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  12229. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  12230. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  12231. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  12232. if (faceVertices.length === 0) {
  12233. continue;
  12234. }
  12235. // Add UVs and get back to world
  12236. var localRotationMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle);
  12237. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  12238. var vertex = faceVertices[vIndex];
  12239. vertexData.indices.push(currentVertexDataIndex);
  12240. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  12241. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  12242. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  12243. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  12244. currentVertexDataIndex++;
  12245. }
  12246. }
  12247. // Return mesh
  12248. var decal = new Mesh(name, sourceMesh.getScene());
  12249. vertexData.applyToMesh(decal);
  12250. decal.position = position.clone();
  12251. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  12252. return decal;
  12253. };
  12254. // Tools
  12255. Mesh.MinMax = function (meshes) {
  12256. var minVector = null;
  12257. var maxVector = null;
  12258. for (var i in meshes) {
  12259. var mesh = meshes[i];
  12260. var boundingBox = mesh.getBoundingInfo().boundingBox;
  12261. if (!minVector) {
  12262. minVector = boundingBox.minimumWorld;
  12263. maxVector = boundingBox.maximumWorld;
  12264. continue;
  12265. }
  12266. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  12267. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  12268. }
  12269. return {
  12270. min: minVector,
  12271. max: maxVector
  12272. };
  12273. };
  12274. Mesh.Center = function (meshesOrMinMaxVector) {
  12275. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  12276. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  12277. };
  12278. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  12279. if (disposeSource === void 0) { disposeSource = true; }
  12280. var source = meshes[0];
  12281. var material = source.material;
  12282. var scene = source.getScene();
  12283. if (!allow32BitsIndices) {
  12284. var totalVertices = 0;
  12285. for (var index = 0; index < meshes.length; index++) {
  12286. totalVertices += meshes[index].getTotalVertices();
  12287. if (totalVertices > 65536) {
  12288. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  12289. return null;
  12290. }
  12291. }
  12292. }
  12293. // Merge
  12294. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  12295. vertexData.transform(source.getWorldMatrix());
  12296. for (index = 1; index < meshes.length; index++) {
  12297. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  12298. otherVertexData.transform(meshes[index].getWorldMatrix());
  12299. vertexData.merge(otherVertexData);
  12300. }
  12301. var newMesh = new Mesh(source.name + "_merged", scene);
  12302. vertexData.applyToMesh(newMesh);
  12303. // Setting properties
  12304. newMesh.material = material;
  12305. newMesh.checkCollisions = source.checkCollisions;
  12306. // Cleaning
  12307. if (disposeSource) {
  12308. for (index = 0; index < meshes.length; index++) {
  12309. meshes[index].dispose();
  12310. }
  12311. }
  12312. return newMesh;
  12313. };
  12314. // Consts
  12315. Mesh._FRONTSIDE = 0;
  12316. Mesh._BACKSIDE = 1;
  12317. Mesh._DOUBLESIDE = 2;
  12318. Mesh._DEFAULTSIDE = 0;
  12319. return Mesh;
  12320. })(BABYLON.AbstractMesh);
  12321. BABYLON.Mesh = Mesh;
  12322. })(BABYLON || (BABYLON = {}));
  12323. //# sourceMappingURL=babylon.mesh.js.map
  12324. var BABYLON;
  12325. (function (BABYLON) {
  12326. var GroundMesh = (function (_super) {
  12327. __extends(GroundMesh, _super);
  12328. function GroundMesh(name, scene) {
  12329. _super.call(this, name, scene);
  12330. this.generateOctree = false;
  12331. this._worldInverse = new BABYLON.Matrix();
  12332. }
  12333. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  12334. get: function () {
  12335. return this._subdivisions;
  12336. },
  12337. enumerable: true,
  12338. configurable: true
  12339. });
  12340. GroundMesh.prototype.optimize = function (chunksCount) {
  12341. this.subdivide(this._subdivisions);
  12342. this.createOrUpdateSubmeshesOctree(32);
  12343. };
  12344. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  12345. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  12346. this.getWorldMatrix().invertToRef(this._worldInverse);
  12347. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  12348. var pickInfo = this.intersects(ray);
  12349. if (pickInfo.hit) {
  12350. return pickInfo.pickedPoint.y;
  12351. }
  12352. return 0;
  12353. };
  12354. return GroundMesh;
  12355. })(BABYLON.Mesh);
  12356. BABYLON.GroundMesh = GroundMesh;
  12357. })(BABYLON || (BABYLON = {}));
  12358. //# sourceMappingURL=babylon.groundMesh.js.map
  12359. var BABYLON;
  12360. (function (BABYLON) {
  12361. /**
  12362. * Creates an instance based on a source mesh.
  12363. */
  12364. var InstancedMesh = (function (_super) {
  12365. __extends(InstancedMesh, _super);
  12366. function InstancedMesh(name, source) {
  12367. _super.call(this, name, source.getScene());
  12368. source.instances.push(this);
  12369. this._sourceMesh = source;
  12370. this.position.copyFrom(source.position);
  12371. this.rotation.copyFrom(source.rotation);
  12372. this.scaling.copyFrom(source.scaling);
  12373. if (source.rotationQuaternion) {
  12374. this.rotationQuaternion = source.rotationQuaternion.clone();
  12375. }
  12376. this.infiniteDistance = source.infiniteDistance;
  12377. this.setPivotMatrix(source.getPivotMatrix());
  12378. this.refreshBoundingInfo();
  12379. this._syncSubMeshes();
  12380. }
  12381. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  12382. // Methods
  12383. get: function () {
  12384. return this._sourceMesh.receiveShadows;
  12385. },
  12386. enumerable: true,
  12387. configurable: true
  12388. });
  12389. Object.defineProperty(InstancedMesh.prototype, "material", {
  12390. get: function () {
  12391. return this._sourceMesh.material;
  12392. },
  12393. enumerable: true,
  12394. configurable: true
  12395. });
  12396. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  12397. get: function () {
  12398. return this._sourceMesh.visibility;
  12399. },
  12400. enumerable: true,
  12401. configurable: true
  12402. });
  12403. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  12404. get: function () {
  12405. return this._sourceMesh.skeleton;
  12406. },
  12407. enumerable: true,
  12408. configurable: true
  12409. });
  12410. InstancedMesh.prototype.getTotalVertices = function () {
  12411. return this._sourceMesh.getTotalVertices();
  12412. };
  12413. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  12414. get: function () {
  12415. return this._sourceMesh;
  12416. },
  12417. enumerable: true,
  12418. configurable: true
  12419. });
  12420. InstancedMesh.prototype.getVerticesData = function (kind) {
  12421. return this._sourceMesh.getVerticesData(kind);
  12422. };
  12423. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  12424. return this._sourceMesh.isVerticesDataPresent(kind);
  12425. };
  12426. InstancedMesh.prototype.getIndices = function () {
  12427. return this._sourceMesh.getIndices();
  12428. };
  12429. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  12430. get: function () {
  12431. return this._sourceMesh._positions;
  12432. },
  12433. enumerable: true,
  12434. configurable: true
  12435. });
  12436. InstancedMesh.prototype.refreshBoundingInfo = function () {
  12437. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12438. if (data) {
  12439. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  12440. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  12441. }
  12442. this._updateBoundingInfo();
  12443. };
  12444. InstancedMesh.prototype._preActivate = function () {
  12445. if (this._currentLOD) {
  12446. this._currentLOD._preActivate();
  12447. }
  12448. };
  12449. InstancedMesh.prototype._activate = function (renderId) {
  12450. if (this._currentLOD) {
  12451. this._currentLOD._registerInstanceForRenderId(this, renderId);
  12452. }
  12453. };
  12454. InstancedMesh.prototype.getLOD = function (camera) {
  12455. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  12456. if (this._currentLOD === this.sourceMesh) {
  12457. return this;
  12458. }
  12459. return this._currentLOD;
  12460. };
  12461. InstancedMesh.prototype._syncSubMeshes = function () {
  12462. this.releaseSubMeshes();
  12463. if (this._sourceMesh.subMeshes) {
  12464. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  12465. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  12466. }
  12467. }
  12468. };
  12469. InstancedMesh.prototype._generatePointsArray = function () {
  12470. return this._sourceMesh._generatePointsArray();
  12471. };
  12472. // Clone
  12473. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12474. var result = this._sourceMesh.createInstance(name);
  12475. // Deep copy
  12476. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  12477. // Bounding info
  12478. this.refreshBoundingInfo();
  12479. // Parent
  12480. if (newParent) {
  12481. result.parent = newParent;
  12482. }
  12483. if (!doNotCloneChildren) {
  12484. for (var index = 0; index < this.getScene().meshes.length; index++) {
  12485. var mesh = this.getScene().meshes[index];
  12486. if (mesh.parent === this) {
  12487. mesh.clone(mesh.name, result);
  12488. }
  12489. }
  12490. }
  12491. result.computeWorldMatrix(true);
  12492. return result;
  12493. };
  12494. // Dispoe
  12495. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  12496. // Remove from mesh
  12497. var index = this._sourceMesh.instances.indexOf(this);
  12498. this._sourceMesh.instances.splice(index, 1);
  12499. _super.prototype.dispose.call(this, doNotRecurse);
  12500. };
  12501. return InstancedMesh;
  12502. })(BABYLON.AbstractMesh);
  12503. BABYLON.InstancedMesh = InstancedMesh;
  12504. })(BABYLON || (BABYLON = {}));
  12505. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  12506. (function (BABYLON) {
  12507. var SubMesh = (function () {
  12508. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  12509. if (createBoundingBox === void 0) { createBoundingBox = true; }
  12510. this.materialIndex = materialIndex;
  12511. this.verticesStart = verticesStart;
  12512. this.verticesCount = verticesCount;
  12513. this.indexStart = indexStart;
  12514. this.indexCount = indexCount;
  12515. this._renderId = 0;
  12516. this._mesh = mesh;
  12517. this._renderingMesh = renderingMesh || mesh;
  12518. mesh.subMeshes.push(this);
  12519. this._id = mesh.subMeshes.length - 1;
  12520. if (createBoundingBox) {
  12521. this.refreshBoundingInfo();
  12522. mesh.computeWorldMatrix(true);
  12523. }
  12524. }
  12525. SubMesh.prototype.getBoundingInfo = function () {
  12526. return this._boundingInfo;
  12527. };
  12528. SubMesh.prototype.getMesh = function () {
  12529. return this._mesh;
  12530. };
  12531. SubMesh.prototype.getRenderingMesh = function () {
  12532. return this._renderingMesh;
  12533. };
  12534. SubMesh.prototype.getMaterial = function () {
  12535. var rootMaterial = this._renderingMesh.material;
  12536. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  12537. var multiMaterial = rootMaterial;
  12538. return multiMaterial.getSubMaterial(this.materialIndex);
  12539. }
  12540. if (!rootMaterial) {
  12541. return this._mesh.getScene().defaultMaterial;
  12542. }
  12543. return rootMaterial;
  12544. };
  12545. // Methods
  12546. SubMesh.prototype.refreshBoundingInfo = function () {
  12547. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12548. if (!data) {
  12549. this._boundingInfo = this._mesh._boundingInfo;
  12550. return;
  12551. }
  12552. var indices = this._renderingMesh.getIndices();
  12553. var extend;
  12554. if (this.indexStart === 0 && this.indexCount === indices.length) {
  12555. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  12556. }
  12557. else {
  12558. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  12559. }
  12560. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  12561. };
  12562. SubMesh.prototype._checkCollision = function (collider) {
  12563. return this._boundingInfo._checkCollision(collider);
  12564. };
  12565. SubMesh.prototype.updateBoundingInfo = function (world) {
  12566. if (!this._boundingInfo) {
  12567. this.refreshBoundingInfo();
  12568. }
  12569. this._boundingInfo._update(world);
  12570. };
  12571. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  12572. return this._boundingInfo.isInFrustum(frustumPlanes);
  12573. };
  12574. SubMesh.prototype.render = function () {
  12575. this._renderingMesh.render(this);
  12576. };
  12577. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  12578. if (!this._linesIndexBuffer) {
  12579. var linesIndices = [];
  12580. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  12581. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  12582. }
  12583. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  12584. this.linesIndexCount = linesIndices.length;
  12585. }
  12586. return this._linesIndexBuffer;
  12587. };
  12588. SubMesh.prototype.canIntersects = function (ray) {
  12589. return ray.intersectsBox(this._boundingInfo.boundingBox);
  12590. };
  12591. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  12592. var intersectInfo = null;
  12593. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  12594. var p0 = positions[indices[index]];
  12595. var p1 = positions[indices[index + 1]];
  12596. var p2 = positions[indices[index + 2]];
  12597. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  12598. if (currentIntersectInfo) {
  12599. if (currentIntersectInfo.distance < 0) {
  12600. continue;
  12601. }
  12602. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12603. intersectInfo = currentIntersectInfo;
  12604. intersectInfo.faceId = index / 3;
  12605. if (fastCheck) {
  12606. break;
  12607. }
  12608. }
  12609. }
  12610. }
  12611. return intersectInfo;
  12612. };
  12613. // Clone
  12614. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  12615. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  12616. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  12617. return result;
  12618. };
  12619. // Dispose
  12620. SubMesh.prototype.dispose = function () {
  12621. if (this._linesIndexBuffer) {
  12622. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  12623. this._linesIndexBuffer = null;
  12624. }
  12625. // Remove from mesh
  12626. var index = this._mesh.subMeshes.indexOf(this);
  12627. this._mesh.subMeshes.splice(index, 1);
  12628. };
  12629. // Statics
  12630. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  12631. var minVertexIndex = Number.MAX_VALUE;
  12632. var maxVertexIndex = -Number.MAX_VALUE;
  12633. renderingMesh = renderingMesh || mesh;
  12634. var indices = renderingMesh.getIndices();
  12635. for (var index = startIndex; index < startIndex + indexCount; index++) {
  12636. var vertexIndex = indices[index];
  12637. if (vertexIndex < minVertexIndex)
  12638. minVertexIndex = vertexIndex;
  12639. if (vertexIndex > maxVertexIndex)
  12640. maxVertexIndex = vertexIndex;
  12641. }
  12642. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  12643. };
  12644. return SubMesh;
  12645. })();
  12646. BABYLON.SubMesh = SubMesh;
  12647. })(BABYLON || (BABYLON = {}));
  12648. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  12649. (function (BABYLON) {
  12650. var BaseTexture = (function () {
  12651. function BaseTexture(scene) {
  12652. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  12653. this.hasAlpha = false;
  12654. this.getAlphaFromRGB = false;
  12655. this.level = 1;
  12656. this.isCube = false;
  12657. this.isRenderTarget = false;
  12658. this.animations = new Array();
  12659. this.coordinatesIndex = 0;
  12660. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  12661. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12662. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12663. this.anisotropicFilteringLevel = 4;
  12664. this._scene = scene;
  12665. this._scene.textures.push(this);
  12666. }
  12667. BaseTexture.prototype.getScene = function () {
  12668. return this._scene;
  12669. };
  12670. BaseTexture.prototype.getTextureMatrix = function () {
  12671. return null;
  12672. };
  12673. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  12674. return null;
  12675. };
  12676. BaseTexture.prototype.getInternalTexture = function () {
  12677. return this._texture;
  12678. };
  12679. BaseTexture.prototype.isReady = function () {
  12680. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12681. return true;
  12682. }
  12683. if (this._texture) {
  12684. return this._texture.isReady;
  12685. }
  12686. return false;
  12687. };
  12688. BaseTexture.prototype.getSize = function () {
  12689. if (this._texture._width) {
  12690. return { width: this._texture._width, height: this._texture._height };
  12691. }
  12692. if (this._texture._size) {
  12693. return { width: this._texture._size, height: this._texture._size };
  12694. }
  12695. return { width: 0, height: 0 };
  12696. };
  12697. BaseTexture.prototype.getBaseSize = function () {
  12698. if (!this.isReady())
  12699. return { width: 0, height: 0 };
  12700. if (this._texture._size) {
  12701. return { width: this._texture._size, height: this._texture._size };
  12702. }
  12703. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  12704. };
  12705. BaseTexture.prototype.scale = function (ratio) {
  12706. };
  12707. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  12708. get: function () {
  12709. return false;
  12710. },
  12711. enumerable: true,
  12712. configurable: true
  12713. });
  12714. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  12715. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12716. for (var index = 0; index < texturesCache.length; index++) {
  12717. var texturesCacheEntry = texturesCache[index];
  12718. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  12719. texturesCache.splice(index, 1);
  12720. return;
  12721. }
  12722. }
  12723. };
  12724. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  12725. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12726. for (var index = 0; index < texturesCache.length; index++) {
  12727. var texturesCacheEntry = texturesCache[index];
  12728. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  12729. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  12730. texturesCacheEntry.references++;
  12731. return texturesCacheEntry;
  12732. }
  12733. }
  12734. }
  12735. return null;
  12736. };
  12737. BaseTexture.prototype.delayLoad = function () {
  12738. };
  12739. BaseTexture.prototype.releaseInternalTexture = function () {
  12740. if (!this._texture) {
  12741. return;
  12742. }
  12743. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12744. this._texture.references--;
  12745. // Final reference ?
  12746. if (this._texture.references === 0) {
  12747. var index = texturesCache.indexOf(this._texture);
  12748. texturesCache.splice(index, 1);
  12749. this._scene.getEngine()._releaseTexture(this._texture);
  12750. delete this._texture;
  12751. }
  12752. };
  12753. BaseTexture.prototype.clone = function () {
  12754. return null;
  12755. };
  12756. BaseTexture.prototype.dispose = function () {
  12757. // Remove from scene
  12758. var index = this._scene.textures.indexOf(this);
  12759. if (index >= 0) {
  12760. this._scene.textures.splice(index, 1);
  12761. }
  12762. if (this._texture === undefined) {
  12763. return;
  12764. }
  12765. this.releaseInternalTexture();
  12766. // Callback
  12767. if (this.onDispose) {
  12768. this.onDispose();
  12769. }
  12770. };
  12771. return BaseTexture;
  12772. })();
  12773. BABYLON.BaseTexture = BaseTexture;
  12774. })(BABYLON || (BABYLON = {}));
  12775. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  12776. (function (BABYLON) {
  12777. var RenderingGroup = (function () {
  12778. function RenderingGroup(index, scene) {
  12779. this.index = index;
  12780. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12781. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12782. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12783. this._scene = scene;
  12784. }
  12785. RenderingGroup.prototype.render = function (customRenderFunction) {
  12786. if (customRenderFunction) {
  12787. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12788. return true;
  12789. }
  12790. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12791. return false;
  12792. }
  12793. var engine = this._scene.getEngine();
  12794. // Opaque
  12795. var subIndex;
  12796. var submesh;
  12797. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12798. submesh = this._opaqueSubMeshes.data[subIndex];
  12799. submesh.render();
  12800. }
  12801. // Alpha test
  12802. engine.setAlphaTesting(true);
  12803. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12804. submesh = this._alphaTestSubMeshes.data[subIndex];
  12805. submesh.render();
  12806. }
  12807. engine.setAlphaTesting(false);
  12808. // Transparent
  12809. if (this._transparentSubMeshes.length) {
  12810. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12811. submesh = this._transparentSubMeshes.data[subIndex];
  12812. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12813. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  12814. }
  12815. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12816. sortedArray.sort(function (a, b) {
  12817. // Alpha index first
  12818. if (a._alphaIndex > b._alphaIndex) {
  12819. return 1;
  12820. }
  12821. if (a._alphaIndex < b._alphaIndex) {
  12822. return -1;
  12823. }
  12824. // Then distance to camera
  12825. if (a._distanceToCamera < b._distanceToCamera) {
  12826. return 1;
  12827. }
  12828. if (a._distanceToCamera > b._distanceToCamera) {
  12829. return -1;
  12830. }
  12831. return 0;
  12832. });
  12833. // Rendering
  12834. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12835. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12836. submesh = sortedArray[subIndex];
  12837. submesh.render();
  12838. }
  12839. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12840. }
  12841. return true;
  12842. };
  12843. RenderingGroup.prototype.prepare = function () {
  12844. this._opaqueSubMeshes.reset();
  12845. this._transparentSubMeshes.reset();
  12846. this._alphaTestSubMeshes.reset();
  12847. };
  12848. RenderingGroup.prototype.dispatch = function (subMesh) {
  12849. var material = subMesh.getMaterial();
  12850. var mesh = subMesh.getMesh();
  12851. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12852. this._transparentSubMeshes.push(subMesh);
  12853. }
  12854. else if (material.needAlphaTesting()) {
  12855. this._alphaTestSubMeshes.push(subMesh);
  12856. }
  12857. else {
  12858. this._opaqueSubMeshes.push(subMesh); // Opaque
  12859. }
  12860. };
  12861. return RenderingGroup;
  12862. })();
  12863. BABYLON.RenderingGroup = RenderingGroup;
  12864. })(BABYLON || (BABYLON = {}));
  12865. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  12866. (function (BABYLON) {
  12867. var RenderingManager = (function () {
  12868. function RenderingManager(scene) {
  12869. this._renderingGroups = new Array();
  12870. this._scene = scene;
  12871. }
  12872. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12873. if (this._scene._activeParticleSystems.length === 0) {
  12874. return;
  12875. }
  12876. // Particles
  12877. var beforeParticlesDate = BABYLON.Tools.Now;
  12878. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12879. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12880. if (particleSystem.renderingGroupId !== index) {
  12881. continue;
  12882. }
  12883. this._clearDepthBuffer();
  12884. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12885. this._scene._activeParticles += particleSystem.render();
  12886. }
  12887. }
  12888. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12889. };
  12890. RenderingManager.prototype._renderSprites = function (index) {
  12891. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12892. return;
  12893. }
  12894. // Sprites
  12895. var beforeSpritessDate = BABYLON.Tools.Now;
  12896. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12897. var spriteManager = this._scene.spriteManagers[id];
  12898. if (spriteManager.renderingGroupId === index) {
  12899. this._clearDepthBuffer();
  12900. spriteManager.render();
  12901. }
  12902. }
  12903. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12904. };
  12905. RenderingManager.prototype._clearDepthBuffer = function () {
  12906. if (this._depthBufferAlreadyCleaned) {
  12907. return;
  12908. }
  12909. this._scene.getEngine().clear(0, false, true);
  12910. this._depthBufferAlreadyCleaned = true;
  12911. };
  12912. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12913. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12914. this._depthBufferAlreadyCleaned = false;
  12915. var renderingGroup = this._renderingGroups[index];
  12916. var needToStepBack = false;
  12917. if (renderingGroup) {
  12918. this._clearDepthBuffer();
  12919. if (!renderingGroup.render(customRenderFunction)) {
  12920. this._renderingGroups.splice(index, 1);
  12921. needToStepBack = true;
  12922. }
  12923. }
  12924. if (renderSprites) {
  12925. this._renderSprites(index);
  12926. }
  12927. if (renderParticles) {
  12928. this._renderParticles(index, activeMeshes);
  12929. }
  12930. if (needToStepBack) {
  12931. index--;
  12932. }
  12933. }
  12934. };
  12935. RenderingManager.prototype.reset = function () {
  12936. for (var index in this._renderingGroups) {
  12937. var renderingGroup = this._renderingGroups[index];
  12938. renderingGroup.prepare();
  12939. }
  12940. };
  12941. RenderingManager.prototype.dispatch = function (subMesh) {
  12942. var mesh = subMesh.getMesh();
  12943. var renderingGroupId = mesh.renderingGroupId || 0;
  12944. if (!this._renderingGroups[renderingGroupId]) {
  12945. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12946. }
  12947. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12948. };
  12949. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12950. return RenderingManager;
  12951. })();
  12952. BABYLON.RenderingManager = RenderingManager;
  12953. })(BABYLON || (BABYLON = {}));
  12954. //# sourceMappingURL=babylon.renderingManager.js.map
  12955. var BABYLON;
  12956. (function (BABYLON) {
  12957. var Texture = (function (_super) {
  12958. __extends(Texture, _super);
  12959. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  12960. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12961. if (onLoad === void 0) { onLoad = null; }
  12962. if (onError === void 0) { onError = null; }
  12963. if (buffer === void 0) { buffer = null; }
  12964. if (deleteBuffer === void 0) { deleteBuffer = false; }
  12965. _super.call(this, scene);
  12966. this.uOffset = 0;
  12967. this.vOffset = 0;
  12968. this.uScale = 1.0;
  12969. this.vScale = 1.0;
  12970. this.uAng = 0;
  12971. this.vAng = 0;
  12972. this.wAng = 0;
  12973. this.name = url;
  12974. this.url = url;
  12975. this._noMipmap = noMipmap;
  12976. this._invertY = invertY;
  12977. this._samplingMode = samplingMode;
  12978. this._buffer = buffer;
  12979. this._deleteBuffer = deleteBuffer;
  12980. if (!url) {
  12981. return;
  12982. }
  12983. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  12984. if (!this._texture) {
  12985. if (!scene.useDelayedTextureLoading) {
  12986. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  12987. if (deleteBuffer) {
  12988. delete this._buffer;
  12989. }
  12990. }
  12991. else {
  12992. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12993. }
  12994. }
  12995. }
  12996. Texture.prototype.delayLoad = function () {
  12997. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12998. return;
  12999. }
  13000. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  13001. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  13002. if (!this._texture) {
  13003. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  13004. if (this._deleteBuffer) {
  13005. delete this._buffer;
  13006. }
  13007. }
  13008. };
  13009. Texture.prototype.updateSamplingMode = function (samplingMode) {
  13010. if (!this._texture) {
  13011. return;
  13012. }
  13013. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  13014. };
  13015. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  13016. x -= this.uOffset + 0.5;
  13017. y -= this.vOffset + 0.5;
  13018. z -= 0.5;
  13019. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  13020. t.x *= this.uScale;
  13021. t.y *= this.vScale;
  13022. t.x += 0.5;
  13023. t.y += 0.5;
  13024. t.z += 0.5;
  13025. };
  13026. Texture.prototype.getTextureMatrix = function () {
  13027. 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) {
  13028. return this._cachedTextureMatrix;
  13029. }
  13030. this._cachedUOffset = this.uOffset;
  13031. this._cachedVOffset = this.vOffset;
  13032. this._cachedUScale = this.uScale;
  13033. this._cachedVScale = this.vScale;
  13034. this._cachedUAng = this.uAng;
  13035. this._cachedVAng = this.vAng;
  13036. this._cachedWAng = this.wAng;
  13037. if (!this._cachedTextureMatrix) {
  13038. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  13039. this._rowGenerationMatrix = new BABYLON.Matrix();
  13040. this._t0 = BABYLON.Vector3.Zero();
  13041. this._t1 = BABYLON.Vector3.Zero();
  13042. this._t2 = BABYLON.Vector3.Zero();
  13043. }
  13044. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  13045. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  13046. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  13047. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  13048. this._t1.subtractInPlace(this._t0);
  13049. this._t2.subtractInPlace(this._t0);
  13050. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  13051. this._cachedTextureMatrix.m[0] = this._t1.x;
  13052. this._cachedTextureMatrix.m[1] = this._t1.y;
  13053. this._cachedTextureMatrix.m[2] = this._t1.z;
  13054. this._cachedTextureMatrix.m[4] = this._t2.x;
  13055. this._cachedTextureMatrix.m[5] = this._t2.y;
  13056. this._cachedTextureMatrix.m[6] = this._t2.z;
  13057. this._cachedTextureMatrix.m[8] = this._t0.x;
  13058. this._cachedTextureMatrix.m[9] = this._t0.y;
  13059. this._cachedTextureMatrix.m[10] = this._t0.z;
  13060. return this._cachedTextureMatrix;
  13061. };
  13062. Texture.prototype.getReflectionTextureMatrix = function () {
  13063. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  13064. return this._cachedTextureMatrix;
  13065. }
  13066. if (!this._cachedTextureMatrix) {
  13067. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  13068. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  13069. }
  13070. this._cachedCoordinatesMode = this.coordinatesMode;
  13071. switch (this.coordinatesMode) {
  13072. case Texture.SPHERICAL_MODE:
  13073. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  13074. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  13075. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  13076. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  13077. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  13078. break;
  13079. case Texture.PLANAR_MODE:
  13080. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  13081. this._cachedTextureMatrix[0] = this.uScale;
  13082. this._cachedTextureMatrix[5] = this.vScale;
  13083. this._cachedTextureMatrix[12] = this.uOffset;
  13084. this._cachedTextureMatrix[13] = this.vOffset;
  13085. break;
  13086. case Texture.PROJECTION_MODE:
  13087. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  13088. this._projectionModeMatrix.m[0] = 0.5;
  13089. this._projectionModeMatrix.m[5] = -0.5;
  13090. this._projectionModeMatrix.m[10] = 0.0;
  13091. this._projectionModeMatrix.m[12] = 0.5;
  13092. this._projectionModeMatrix.m[13] = 0.5;
  13093. this._projectionModeMatrix.m[14] = 1.0;
  13094. this._projectionModeMatrix.m[15] = 1.0;
  13095. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  13096. break;
  13097. default:
  13098. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  13099. break;
  13100. }
  13101. return this._cachedTextureMatrix;
  13102. };
  13103. Texture.prototype.clone = function () {
  13104. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  13105. // Base texture
  13106. newTexture.hasAlpha = this.hasAlpha;
  13107. newTexture.level = this.level;
  13108. newTexture.wrapU = this.wrapU;
  13109. newTexture.wrapV = this.wrapV;
  13110. newTexture.coordinatesIndex = this.coordinatesIndex;
  13111. newTexture.coordinatesMode = this.coordinatesMode;
  13112. // Texture
  13113. newTexture.uOffset = this.uOffset;
  13114. newTexture.vOffset = this.vOffset;
  13115. newTexture.uScale = this.uScale;
  13116. newTexture.vScale = this.vScale;
  13117. newTexture.uAng = this.uAng;
  13118. newTexture.vAng = this.vAng;
  13119. newTexture.wAng = this.wAng;
  13120. return newTexture;
  13121. };
  13122. // Statics
  13123. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  13124. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  13125. if (onLoad === void 0) { onLoad = null; }
  13126. if (onError === void 0) { onError = null; }
  13127. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  13128. };
  13129. // Constants
  13130. Texture.NEAREST_SAMPLINGMODE = 1;
  13131. Texture.BILINEAR_SAMPLINGMODE = 2;
  13132. Texture.TRILINEAR_SAMPLINGMODE = 3;
  13133. Texture.EXPLICIT_MODE = 0;
  13134. Texture.SPHERICAL_MODE = 1;
  13135. Texture.PLANAR_MODE = 2;
  13136. Texture.CUBIC_MODE = 3;
  13137. Texture.PROJECTION_MODE = 4;
  13138. Texture.SKYBOX_MODE = 5;
  13139. Texture.CLAMP_ADDRESSMODE = 0;
  13140. Texture.WRAP_ADDRESSMODE = 1;
  13141. Texture.MIRROR_ADDRESSMODE = 2;
  13142. return Texture;
  13143. })(BABYLON.BaseTexture);
  13144. BABYLON.Texture = Texture;
  13145. })(BABYLON || (BABYLON = {}));
  13146. //# sourceMappingURL=babylon.texture.js.map
  13147. var BABYLON;
  13148. (function (BABYLON) {
  13149. var CubeTexture = (function (_super) {
  13150. __extends(CubeTexture, _super);
  13151. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  13152. _super.call(this, scene);
  13153. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  13154. this.name = rootUrl;
  13155. this.url = rootUrl;
  13156. this._noMipmap = noMipmap;
  13157. this.hasAlpha = false;
  13158. this._texture = this._getFromCache(rootUrl, noMipmap);
  13159. if (!extensions) {
  13160. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  13161. }
  13162. this._extensions = extensions;
  13163. if (!this._texture) {
  13164. if (!scene.useDelayedTextureLoading) {
  13165. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  13166. }
  13167. else {
  13168. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  13169. }
  13170. }
  13171. this.isCube = true;
  13172. this._textureMatrix = BABYLON.Matrix.Identity();
  13173. }
  13174. CubeTexture.prototype.clone = function () {
  13175. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  13176. // Base texture
  13177. newTexture.level = this.level;
  13178. newTexture.wrapU = this.wrapU;
  13179. newTexture.wrapV = this.wrapV;
  13180. newTexture.coordinatesIndex = this.coordinatesIndex;
  13181. newTexture.coordinatesMode = this.coordinatesMode;
  13182. return newTexture;
  13183. };
  13184. // Methods
  13185. CubeTexture.prototype.delayLoad = function () {
  13186. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  13187. return;
  13188. }
  13189. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  13190. this._texture = this._getFromCache(this.url, this._noMipmap);
  13191. if (!this._texture) {
  13192. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  13193. }
  13194. };
  13195. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  13196. return this._textureMatrix;
  13197. };
  13198. return CubeTexture;
  13199. })(BABYLON.BaseTexture);
  13200. BABYLON.CubeTexture = CubeTexture;
  13201. })(BABYLON || (BABYLON = {}));
  13202. //# sourceMappingURL=babylon.cubeTexture.js.map
  13203. var BABYLON;
  13204. (function (BABYLON) {
  13205. var RenderTargetTexture = (function (_super) {
  13206. __extends(RenderTargetTexture, _super);
  13207. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  13208. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  13209. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  13210. _super.call(this, null, scene, !generateMipMaps);
  13211. this.renderList = new Array();
  13212. this.renderParticles = true;
  13213. this.renderSprites = false;
  13214. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  13215. this._currentRefreshId = -1;
  13216. this._refreshRate = 1;
  13217. this.name = name;
  13218. this.isRenderTarget = true;
  13219. this._size = size;
  13220. this._generateMipMaps = generateMipMaps;
  13221. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  13222. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  13223. // Rendering groups
  13224. this._renderingManager = new BABYLON.RenderingManager(scene);
  13225. }
  13226. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  13227. this._currentRefreshId = -1;
  13228. };
  13229. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  13230. get: function () {
  13231. return this._refreshRate;
  13232. },
  13233. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  13234. set: function (value) {
  13235. this._refreshRate = value;
  13236. this.resetRefreshCounter();
  13237. },
  13238. enumerable: true,
  13239. configurable: true
  13240. });
  13241. RenderTargetTexture.prototype._shouldRender = function () {
  13242. if (this._currentRefreshId === -1) {
  13243. this._currentRefreshId = 1;
  13244. return true;
  13245. }
  13246. if (this.refreshRate === this._currentRefreshId) {
  13247. this._currentRefreshId = 1;
  13248. return true;
  13249. }
  13250. this._currentRefreshId++;
  13251. return false;
  13252. };
  13253. RenderTargetTexture.prototype.isReady = function () {
  13254. if (!this.getScene().renderTargetsEnabled) {
  13255. return false;
  13256. }
  13257. return _super.prototype.isReady.call(this);
  13258. };
  13259. RenderTargetTexture.prototype.getRenderSize = function () {
  13260. return this._size;
  13261. };
  13262. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  13263. get: function () {
  13264. return true;
  13265. },
  13266. enumerable: true,
  13267. configurable: true
  13268. });
  13269. RenderTargetTexture.prototype.scale = function (ratio) {
  13270. var newSize = this._size * ratio;
  13271. this.resize(newSize, this._generateMipMaps);
  13272. };
  13273. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  13274. this.releaseInternalTexture();
  13275. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  13276. };
  13277. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  13278. var scene = this.getScene();
  13279. var engine = scene.getEngine();
  13280. if (this._waitingRenderList) {
  13281. this.renderList = [];
  13282. for (var index = 0; index < this._waitingRenderList.length; index++) {
  13283. var id = this._waitingRenderList[index];
  13284. this.renderList.push(scene.getMeshByID(id));
  13285. }
  13286. delete this._waitingRenderList;
  13287. }
  13288. if (this.renderList && this.renderList.length === 0) {
  13289. return;
  13290. }
  13291. // Bind
  13292. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  13293. engine.bindFramebuffer(this._texture);
  13294. }
  13295. this._renderingManager.reset();
  13296. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  13297. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  13298. var mesh = currentRenderList[meshIndex];
  13299. if (mesh) {
  13300. if (!mesh.isReady()) {
  13301. // Reset _currentRefreshId
  13302. this.resetRefreshCounter();
  13303. continue;
  13304. }
  13305. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  13306. mesh._activate(scene.getRenderId());
  13307. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  13308. var subMesh = mesh.subMeshes[subIndex];
  13309. scene._activeVertices += subMesh.indexCount;
  13310. this._renderingManager.dispatch(subMesh);
  13311. }
  13312. }
  13313. }
  13314. }
  13315. if (this.onBeforeRender) {
  13316. this.onBeforeRender();
  13317. }
  13318. // Clear
  13319. if (this.onClear) {
  13320. this.onClear(engine);
  13321. }
  13322. else {
  13323. engine.clear(scene.clearColor, true, true);
  13324. }
  13325. if (!this._doNotChangeAspectRatio) {
  13326. scene.updateTransformMatrix(true);
  13327. }
  13328. // Render
  13329. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  13330. if (useCameraPostProcess) {
  13331. scene.postProcessManager._finalizeFrame(false, this._texture);
  13332. }
  13333. if (!this._doNotChangeAspectRatio) {
  13334. scene.updateTransformMatrix(true);
  13335. }
  13336. if (this.onAfterRender) {
  13337. this.onAfterRender();
  13338. }
  13339. // Dump ?
  13340. if (dumpForDebug) {
  13341. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  13342. }
  13343. // Unbind
  13344. engine.unBindFramebuffer(this._texture);
  13345. if (this.onAfterUnbind) {
  13346. this.onAfterUnbind();
  13347. }
  13348. };
  13349. RenderTargetTexture.prototype.clone = function () {
  13350. var textureSize = this.getSize();
  13351. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13352. // Base texture
  13353. newTexture.hasAlpha = this.hasAlpha;
  13354. newTexture.level = this.level;
  13355. // RenderTarget Texture
  13356. newTexture.coordinatesMode = this.coordinatesMode;
  13357. newTexture.renderList = this.renderList.slice(0);
  13358. return newTexture;
  13359. };
  13360. return RenderTargetTexture;
  13361. })(BABYLON.Texture);
  13362. BABYLON.RenderTargetTexture = RenderTargetTexture;
  13363. })(BABYLON || (BABYLON = {}));
  13364. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  13365. var BABYLON;
  13366. (function (BABYLON) {
  13367. var ProceduralTexture = (function (_super) {
  13368. __extends(ProceduralTexture, _super);
  13369. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  13370. if (generateMipMaps === void 0) { generateMipMaps = true; }
  13371. _super.call(this, null, scene, !generateMipMaps);
  13372. this._currentRefreshId = -1;
  13373. this._refreshRate = 1;
  13374. this._vertexDeclaration = [2];
  13375. this._vertexStrideSize = 2 * 4;
  13376. this._uniforms = new Array();
  13377. this._samplers = new Array();
  13378. this._textures = new Array();
  13379. this._floats = new Array();
  13380. this._floatsArrays = {};
  13381. this._colors3 = new Array();
  13382. this._colors4 = new Array();
  13383. this._vectors2 = new Array();
  13384. this._vectors3 = new Array();
  13385. this._matrices = new Array();
  13386. this._fallbackTextureUsed = false;
  13387. scene._proceduralTextures.push(this);
  13388. this.name = name;
  13389. this.isRenderTarget = true;
  13390. this._size = size;
  13391. this._generateMipMaps = generateMipMaps;
  13392. this.setFragment(fragment);
  13393. this._fallbackTexture = fallbackTexture;
  13394. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  13395. // VBO
  13396. var vertices = [];
  13397. vertices.push(1, 1);
  13398. vertices.push(-1, 1);
  13399. vertices.push(-1, -1);
  13400. vertices.push(1, -1);
  13401. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13402. // Indices
  13403. var indices = [];
  13404. indices.push(0);
  13405. indices.push(1);
  13406. indices.push(2);
  13407. indices.push(0);
  13408. indices.push(2);
  13409. indices.push(3);
  13410. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13411. }
  13412. ProceduralTexture.prototype.reset = function () {
  13413. if (this._effect === undefined) {
  13414. return;
  13415. }
  13416. var engine = this.getScene().getEngine();
  13417. engine._releaseEffect(this._effect);
  13418. };
  13419. ProceduralTexture.prototype.isReady = function () {
  13420. var _this = this;
  13421. var engine = this.getScene().getEngine();
  13422. var shaders;
  13423. if (!this._fragment) {
  13424. return false;
  13425. }
  13426. if (this._fallbackTextureUsed) {
  13427. return true;
  13428. }
  13429. if (this._fragment.fragmentElement !== undefined) {
  13430. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  13431. }
  13432. else {
  13433. shaders = { vertex: "procedural", fragment: this._fragment };
  13434. }
  13435. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  13436. _this.releaseInternalTexture();
  13437. if (_this._fallbackTexture) {
  13438. _this._texture = _this._fallbackTexture._texture;
  13439. _this._texture.references++;
  13440. }
  13441. _this._fallbackTextureUsed = true;
  13442. });
  13443. return this._effect.isReady();
  13444. };
  13445. ProceduralTexture.prototype.resetRefreshCounter = function () {
  13446. this._currentRefreshId = -1;
  13447. };
  13448. ProceduralTexture.prototype.setFragment = function (fragment) {
  13449. this._fragment = fragment;
  13450. };
  13451. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  13452. get: function () {
  13453. return this._refreshRate;
  13454. },
  13455. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  13456. set: function (value) {
  13457. this._refreshRate = value;
  13458. this.resetRefreshCounter();
  13459. },
  13460. enumerable: true,
  13461. configurable: true
  13462. });
  13463. ProceduralTexture.prototype._shouldRender = function () {
  13464. if (!this.isReady() || !this._texture) {
  13465. return false;
  13466. }
  13467. if (this._fallbackTextureUsed) {
  13468. return false;
  13469. }
  13470. if (this._currentRefreshId === -1) {
  13471. this._currentRefreshId = 1;
  13472. return true;
  13473. }
  13474. if (this.refreshRate === this._currentRefreshId) {
  13475. this._currentRefreshId = 1;
  13476. return true;
  13477. }
  13478. this._currentRefreshId++;
  13479. return false;
  13480. };
  13481. ProceduralTexture.prototype.getRenderSize = function () {
  13482. return this._size;
  13483. };
  13484. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  13485. if (this._fallbackTextureUsed) {
  13486. return;
  13487. }
  13488. this.releaseInternalTexture();
  13489. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  13490. };
  13491. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  13492. if (this._uniforms.indexOf(uniformName) === -1) {
  13493. this._uniforms.push(uniformName);
  13494. }
  13495. };
  13496. ProceduralTexture.prototype.setTexture = function (name, texture) {
  13497. if (this._samplers.indexOf(name) === -1) {
  13498. this._samplers.push(name);
  13499. }
  13500. this._textures[name] = texture;
  13501. return this;
  13502. };
  13503. ProceduralTexture.prototype.setFloat = function (name, value) {
  13504. this._checkUniform(name);
  13505. this._floats[name] = value;
  13506. return this;
  13507. };
  13508. ProceduralTexture.prototype.setFloats = function (name, value) {
  13509. this._checkUniform(name);
  13510. this._floatsArrays[name] = value;
  13511. return this;
  13512. };
  13513. ProceduralTexture.prototype.setColor3 = function (name, value) {
  13514. this._checkUniform(name);
  13515. this._colors3[name] = value;
  13516. return this;
  13517. };
  13518. ProceduralTexture.prototype.setColor4 = function (name, value) {
  13519. this._checkUniform(name);
  13520. this._colors4[name] = value;
  13521. return this;
  13522. };
  13523. ProceduralTexture.prototype.setVector2 = function (name, value) {
  13524. this._checkUniform(name);
  13525. this._vectors2[name] = value;
  13526. return this;
  13527. };
  13528. ProceduralTexture.prototype.setVector3 = function (name, value) {
  13529. this._checkUniform(name);
  13530. this._vectors3[name] = value;
  13531. return this;
  13532. };
  13533. ProceduralTexture.prototype.setMatrix = function (name, value) {
  13534. this._checkUniform(name);
  13535. this._matrices[name] = value;
  13536. return this;
  13537. };
  13538. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13539. var scene = this.getScene();
  13540. var engine = scene.getEngine();
  13541. engine.bindFramebuffer(this._texture);
  13542. // Clear
  13543. engine.clear(scene.clearColor, true, true);
  13544. // Render
  13545. engine.enableEffect(this._effect);
  13546. engine.setState(false);
  13547. for (var name in this._textures) {
  13548. this._effect.setTexture(name, this._textures[name]);
  13549. }
  13550. for (name in this._floats) {
  13551. this._effect.setFloat(name, this._floats[name]);
  13552. }
  13553. for (name in this._floatsArrays) {
  13554. this._effect.setArray(name, this._floatsArrays[name]);
  13555. }
  13556. for (name in this._colors3) {
  13557. this._effect.setColor3(name, this._colors3[name]);
  13558. }
  13559. for (name in this._colors4) {
  13560. var color = this._colors4[name];
  13561. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  13562. }
  13563. for (name in this._vectors2) {
  13564. this._effect.setVector2(name, this._vectors2[name]);
  13565. }
  13566. for (name in this._vectors3) {
  13567. this._effect.setVector3(name, this._vectors3[name]);
  13568. }
  13569. for (name in this._matrices) {
  13570. this._effect.setMatrix(name, this._matrices[name]);
  13571. }
  13572. // VBOs
  13573. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  13574. // Draw order
  13575. engine.draw(true, 0, 6);
  13576. // Unbind
  13577. engine.unBindFramebuffer(this._texture);
  13578. };
  13579. ProceduralTexture.prototype.clone = function () {
  13580. var textureSize = this.getSize();
  13581. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  13582. // Base texture
  13583. newTexture.hasAlpha = this.hasAlpha;
  13584. newTexture.level = this.level;
  13585. // RenderTarget Texture
  13586. newTexture.coordinatesMode = this.coordinatesMode;
  13587. return newTexture;
  13588. };
  13589. ProceduralTexture.prototype.dispose = function () {
  13590. var index = this.getScene()._proceduralTextures.indexOf(this);
  13591. if (index >= 0) {
  13592. this.getScene()._proceduralTextures.splice(index, 1);
  13593. }
  13594. _super.prototype.dispose.call(this);
  13595. };
  13596. return ProceduralTexture;
  13597. })(BABYLON.Texture);
  13598. BABYLON.ProceduralTexture = ProceduralTexture;
  13599. })(BABYLON || (BABYLON = {}));
  13600. //# sourceMappingURL=babylon.proceduralTexture.js.map
  13601. var BABYLON;
  13602. (function (BABYLON) {
  13603. var WoodProceduralTexture = (function (_super) {
  13604. __extends(WoodProceduralTexture, _super);
  13605. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13606. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  13607. this._ampScale = 100.0;
  13608. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  13609. this.updateShaderUniforms();
  13610. this.refreshRate = 0;
  13611. }
  13612. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  13613. this.setFloat("ampScale", this._ampScale);
  13614. this.setColor3("woodColor", this._woodColor);
  13615. };
  13616. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  13617. get: function () {
  13618. return this._ampScale;
  13619. },
  13620. set: function (value) {
  13621. this._ampScale = value;
  13622. this.updateShaderUniforms();
  13623. },
  13624. enumerable: true,
  13625. configurable: true
  13626. });
  13627. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  13628. get: function () {
  13629. return this._woodColor;
  13630. },
  13631. set: function (value) {
  13632. this._woodColor = value;
  13633. this.updateShaderUniforms();
  13634. },
  13635. enumerable: true,
  13636. configurable: true
  13637. });
  13638. return WoodProceduralTexture;
  13639. })(BABYLON.ProceduralTexture);
  13640. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  13641. var FireProceduralTexture = (function (_super) {
  13642. __extends(FireProceduralTexture, _super);
  13643. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13644. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  13645. this._time = 0.0;
  13646. this._speed = new BABYLON.Vector2(0.5, 0.3);
  13647. this._autoGenerateTime = true;
  13648. this._alphaThreshold = 0.5;
  13649. this._fireColors = FireProceduralTexture.RedFireColors;
  13650. this.updateShaderUniforms();
  13651. this.refreshRate = 1;
  13652. }
  13653. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  13654. this.setFloat("time", this._time);
  13655. this.setVector2("speed", this._speed);
  13656. this.setColor3("c1", this._fireColors[0]);
  13657. this.setColor3("c2", this._fireColors[1]);
  13658. this.setColor3("c3", this._fireColors[2]);
  13659. this.setColor3("c4", this._fireColors[3]);
  13660. this.setColor3("c5", this._fireColors[4]);
  13661. this.setColor3("c6", this._fireColors[5]);
  13662. this.setFloat("alphaThreshold", this._alphaThreshold);
  13663. };
  13664. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13665. if (this._autoGenerateTime) {
  13666. this._time += this.getScene().getAnimationRatio() * 0.03;
  13667. this.updateShaderUniforms();
  13668. }
  13669. _super.prototype.render.call(this, useCameraPostProcess);
  13670. };
  13671. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  13672. get: function () {
  13673. return [
  13674. new BABYLON.Color3(0.5, 0.0, 1.0),
  13675. new BABYLON.Color3(0.9, 0.0, 1.0),
  13676. new BABYLON.Color3(0.2, 0.0, 1.0),
  13677. new BABYLON.Color3(1.0, 0.9, 1.0),
  13678. new BABYLON.Color3(0.1, 0.1, 1.0),
  13679. new BABYLON.Color3(0.9, 0.9, 1.0)
  13680. ];
  13681. },
  13682. enumerable: true,
  13683. configurable: true
  13684. });
  13685. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  13686. get: function () {
  13687. return [
  13688. new BABYLON.Color3(0.5, 1.0, 0.0),
  13689. new BABYLON.Color3(0.5, 1.0, 0.0),
  13690. new BABYLON.Color3(0.3, 0.4, 0.0),
  13691. new BABYLON.Color3(0.5, 1.0, 0.0),
  13692. new BABYLON.Color3(0.2, 0.0, 0.0),
  13693. new BABYLON.Color3(0.5, 1.0, 0.0)
  13694. ];
  13695. },
  13696. enumerable: true,
  13697. configurable: true
  13698. });
  13699. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  13700. get: function () {
  13701. return [
  13702. new BABYLON.Color3(0.5, 0.0, 0.1),
  13703. new BABYLON.Color3(0.9, 0.0, 0.0),
  13704. new BABYLON.Color3(0.2, 0.0, 0.0),
  13705. new BABYLON.Color3(1.0, 0.9, 0.0),
  13706. new BABYLON.Color3(0.1, 0.1, 0.1),
  13707. new BABYLON.Color3(0.9, 0.9, 0.9)
  13708. ];
  13709. },
  13710. enumerable: true,
  13711. configurable: true
  13712. });
  13713. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  13714. get: function () {
  13715. return [
  13716. new BABYLON.Color3(0.1, 0.0, 0.5),
  13717. new BABYLON.Color3(0.0, 0.0, 0.5),
  13718. new BABYLON.Color3(0.1, 0.0, 0.2),
  13719. new BABYLON.Color3(0.0, 0.0, 1.0),
  13720. new BABYLON.Color3(0.1, 0.2, 0.3),
  13721. new BABYLON.Color3(0.0, 0.2, 0.9)
  13722. ];
  13723. },
  13724. enumerable: true,
  13725. configurable: true
  13726. });
  13727. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  13728. get: function () {
  13729. return this._fireColors;
  13730. },
  13731. set: function (value) {
  13732. this._fireColors = value;
  13733. this.updateShaderUniforms();
  13734. },
  13735. enumerable: true,
  13736. configurable: true
  13737. });
  13738. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  13739. get: function () {
  13740. return this._time;
  13741. },
  13742. set: function (value) {
  13743. this._time = value;
  13744. this.updateShaderUniforms();
  13745. },
  13746. enumerable: true,
  13747. configurable: true
  13748. });
  13749. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  13750. get: function () {
  13751. return this._speed;
  13752. },
  13753. set: function (value) {
  13754. this._speed = value;
  13755. this.updateShaderUniforms();
  13756. },
  13757. enumerable: true,
  13758. configurable: true
  13759. });
  13760. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  13761. get: function () {
  13762. return this._alphaThreshold;
  13763. },
  13764. set: function (value) {
  13765. this._alphaThreshold = value;
  13766. this.updateShaderUniforms();
  13767. },
  13768. enumerable: true,
  13769. configurable: true
  13770. });
  13771. return FireProceduralTexture;
  13772. })(BABYLON.ProceduralTexture);
  13773. BABYLON.FireProceduralTexture = FireProceduralTexture;
  13774. var CloudProceduralTexture = (function (_super) {
  13775. __extends(CloudProceduralTexture, _super);
  13776. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13777. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  13778. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  13779. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  13780. this.updateShaderUniforms();
  13781. this.refreshRate = 0;
  13782. }
  13783. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  13784. this.setColor3("skyColor", this._skyColor);
  13785. this.setColor3("cloudColor", this._cloudColor);
  13786. };
  13787. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  13788. get: function () {
  13789. return this._skyColor;
  13790. },
  13791. set: function (value) {
  13792. this._skyColor = value;
  13793. this.updateShaderUniforms();
  13794. },
  13795. enumerable: true,
  13796. configurable: true
  13797. });
  13798. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  13799. get: function () {
  13800. return this._cloudColor;
  13801. },
  13802. set: function (value) {
  13803. this._cloudColor = value;
  13804. this.updateShaderUniforms();
  13805. },
  13806. enumerable: true,
  13807. configurable: true
  13808. });
  13809. return CloudProceduralTexture;
  13810. })(BABYLON.ProceduralTexture);
  13811. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  13812. var GrassProceduralTexture = (function (_super) {
  13813. __extends(GrassProceduralTexture, _super);
  13814. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13815. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  13816. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  13817. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  13818. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  13819. this._groundColor = new BABYLON.Color3(1, 1, 1);
  13820. this._grassColors = [
  13821. new BABYLON.Color3(0.29, 0.38, 0.02),
  13822. new BABYLON.Color3(0.36, 0.49, 0.09),
  13823. new BABYLON.Color3(0.51, 0.6, 0.28)
  13824. ];
  13825. this.updateShaderUniforms();
  13826. this.refreshRate = 0;
  13827. }
  13828. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  13829. this.setColor3("herb1Color", this._grassColors[0]);
  13830. this.setColor3("herb2Color", this._grassColors[1]);
  13831. this.setColor3("herb3Color", this._grassColors[2]);
  13832. this.setColor3("groundColor", this._groundColor);
  13833. };
  13834. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  13835. get: function () {
  13836. return this._grassColors;
  13837. },
  13838. set: function (value) {
  13839. this._grassColors = value;
  13840. this.updateShaderUniforms();
  13841. },
  13842. enumerable: true,
  13843. configurable: true
  13844. });
  13845. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  13846. get: function () {
  13847. return this._groundColor;
  13848. },
  13849. set: function (value) {
  13850. this.groundColor = value;
  13851. this.updateShaderUniforms();
  13852. },
  13853. enumerable: true,
  13854. configurable: true
  13855. });
  13856. return GrassProceduralTexture;
  13857. })(BABYLON.ProceduralTexture);
  13858. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  13859. var RoadProceduralTexture = (function (_super) {
  13860. __extends(RoadProceduralTexture, _super);
  13861. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13862. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  13863. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  13864. this.updateShaderUniforms();
  13865. this.refreshRate = 0;
  13866. }
  13867. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  13868. this.setColor3("roadColor", this._roadColor);
  13869. };
  13870. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  13871. get: function () {
  13872. return this._roadColor;
  13873. },
  13874. set: function (value) {
  13875. this._roadColor = value;
  13876. this.updateShaderUniforms();
  13877. },
  13878. enumerable: true,
  13879. configurable: true
  13880. });
  13881. return RoadProceduralTexture;
  13882. })(BABYLON.ProceduralTexture);
  13883. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  13884. var BrickProceduralTexture = (function (_super) {
  13885. __extends(BrickProceduralTexture, _super);
  13886. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13887. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  13888. this._numberOfBricksHeight = 15;
  13889. this._numberOfBricksWidth = 5;
  13890. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13891. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13892. this.updateShaderUniforms();
  13893. this.refreshRate = 0;
  13894. }
  13895. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  13896. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  13897. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  13898. this.setColor3("brickColor", this._brickColor);
  13899. this.setColor3("jointColor", this._jointColor);
  13900. };
  13901. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  13902. get: function () {
  13903. return this._numberOfBricksHeight;
  13904. },
  13905. set: function (value) {
  13906. this._numberOfBricksHeight = value;
  13907. this.updateShaderUniforms();
  13908. },
  13909. enumerable: true,
  13910. configurable: true
  13911. });
  13912. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  13913. get: function () {
  13914. return this._numberOfBricksWidth;
  13915. },
  13916. set: function (value) {
  13917. this._numberOfBricksHeight = value;
  13918. this.updateShaderUniforms();
  13919. },
  13920. enumerable: true,
  13921. configurable: true
  13922. });
  13923. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  13924. get: function () {
  13925. return this._jointColor;
  13926. },
  13927. set: function (value) {
  13928. this._jointColor = value;
  13929. this.updateShaderUniforms();
  13930. },
  13931. enumerable: true,
  13932. configurable: true
  13933. });
  13934. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  13935. get: function () {
  13936. return this._brickColor;
  13937. },
  13938. set: function (value) {
  13939. this._brickColor = value;
  13940. this.updateShaderUniforms();
  13941. },
  13942. enumerable: true,
  13943. configurable: true
  13944. });
  13945. return BrickProceduralTexture;
  13946. })(BABYLON.ProceduralTexture);
  13947. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  13948. var MarbleProceduralTexture = (function (_super) {
  13949. __extends(MarbleProceduralTexture, _super);
  13950. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13951. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  13952. this._numberOfTilesHeight = 3;
  13953. this._numberOfTilesWidth = 3;
  13954. this._amplitude = 9.0;
  13955. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13956. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13957. this.updateShaderUniforms();
  13958. this.refreshRate = 0;
  13959. }
  13960. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  13961. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  13962. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  13963. this.setFloat("amplitude", this._amplitude);
  13964. this.setColor3("marbleColor", this._marbleColor);
  13965. this.setColor3("jointColor", this._jointColor);
  13966. };
  13967. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  13968. get: function () {
  13969. return this._numberOfTilesHeight;
  13970. },
  13971. set: function (value) {
  13972. this._numberOfTilesHeight = value;
  13973. this.updateShaderUniforms();
  13974. },
  13975. enumerable: true,
  13976. configurable: true
  13977. });
  13978. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  13979. get: function () {
  13980. return this._numberOfTilesWidth;
  13981. },
  13982. set: function (value) {
  13983. this._numberOfTilesWidth = value;
  13984. this.updateShaderUniforms();
  13985. },
  13986. enumerable: true,
  13987. configurable: true
  13988. });
  13989. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  13990. get: function () {
  13991. return this._jointColor;
  13992. },
  13993. set: function (value) {
  13994. this._jointColor = value;
  13995. this.updateShaderUniforms();
  13996. },
  13997. enumerable: true,
  13998. configurable: true
  13999. });
  14000. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  14001. get: function () {
  14002. return this._marbleColor;
  14003. },
  14004. set: function (value) {
  14005. this._marbleColor = value;
  14006. this.updateShaderUniforms();
  14007. },
  14008. enumerable: true,
  14009. configurable: true
  14010. });
  14011. return MarbleProceduralTexture;
  14012. })(BABYLON.ProceduralTexture);
  14013. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  14014. })(BABYLON || (BABYLON = {}));
  14015. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  14016. var BABYLON;
  14017. (function (BABYLON) {
  14018. var CustomProceduralTexture = (function (_super) {
  14019. __extends(CustomProceduralTexture, _super);
  14020. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  14021. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  14022. this._animate = true;
  14023. this._time = 0;
  14024. this._texturePath = texturePath;
  14025. //Try to load json
  14026. this.loadJson(texturePath);
  14027. this.refreshRate = 1;
  14028. }
  14029. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  14030. var _this = this;
  14031. var that = this;
  14032. function noConfigFile() {
  14033. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  14034. try {
  14035. that.setFragment(that._texturePath);
  14036. }
  14037. catch (ex) {
  14038. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  14039. }
  14040. }
  14041. var configFileUrl = jsonUrl + "/config.json";
  14042. var xhr = new XMLHttpRequest();
  14043. xhr.open("GET", configFileUrl, true);
  14044. xhr.addEventListener("load", function () {
  14045. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  14046. try {
  14047. _this._config = JSON.parse(xhr.response);
  14048. _this.updateShaderUniforms();
  14049. _this.updateTextures();
  14050. _this.setFragment(_this._texturePath + "/custom");
  14051. _this._animate = _this._config.animate;
  14052. _this.refreshRate = _this._config.refreshrate;
  14053. }
  14054. catch (ex) {
  14055. noConfigFile();
  14056. }
  14057. }
  14058. else {
  14059. noConfigFile();
  14060. }
  14061. }, false);
  14062. xhr.addEventListener("error", function () {
  14063. noConfigFile();
  14064. }, false);
  14065. try {
  14066. xhr.send();
  14067. }
  14068. catch (ex) {
  14069. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  14070. }
  14071. };
  14072. CustomProceduralTexture.prototype.isReady = function () {
  14073. if (!_super.prototype.isReady.call(this)) {
  14074. return false;
  14075. }
  14076. for (var name in this._textures) {
  14077. var texture = this._textures[name];
  14078. if (!texture.isReady()) {
  14079. return false;
  14080. }
  14081. }
  14082. return true;
  14083. };
  14084. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  14085. if (this._animate) {
  14086. this._time += this.getScene().getAnimationRatio() * 0.03;
  14087. this.updateShaderUniforms();
  14088. }
  14089. _super.prototype.render.call(this, useCameraPostProcess);
  14090. };
  14091. CustomProceduralTexture.prototype.updateTextures = function () {
  14092. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  14093. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  14094. }
  14095. };
  14096. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  14097. if (this._config) {
  14098. for (var j = 0; j < this._config.uniforms.length; j++) {
  14099. var uniform = this._config.uniforms[j];
  14100. switch (uniform.type) {
  14101. case "float":
  14102. this.setFloat(uniform.name, uniform.value);
  14103. break;
  14104. case "color3":
  14105. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  14106. break;
  14107. case "color4":
  14108. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  14109. break;
  14110. case "vector2":
  14111. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  14112. break;
  14113. case "vector3":
  14114. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  14115. break;
  14116. }
  14117. }
  14118. }
  14119. this.setFloat("time", this._time);
  14120. };
  14121. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  14122. get: function () {
  14123. return this._animate;
  14124. },
  14125. set: function (value) {
  14126. this._animate = value;
  14127. },
  14128. enumerable: true,
  14129. configurable: true
  14130. });
  14131. return CustomProceduralTexture;
  14132. })(BABYLON.ProceduralTexture);
  14133. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  14134. })(BABYLON || (BABYLON = {}));
  14135. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  14136. var BABYLON;
  14137. (function (BABYLON) {
  14138. var MirrorTexture = (function (_super) {
  14139. __extends(MirrorTexture, _super);
  14140. function MirrorTexture(name, size, scene, generateMipMaps) {
  14141. var _this = this;
  14142. _super.call(this, name, size, scene, generateMipMaps, true);
  14143. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  14144. this._transformMatrix = BABYLON.Matrix.Zero();
  14145. this._mirrorMatrix = BABYLON.Matrix.Zero();
  14146. this.onBeforeRender = function () {
  14147. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  14148. _this._savedViewMatrix = scene.getViewMatrix();
  14149. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  14150. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  14151. scene.clipPlane = _this.mirrorPlane;
  14152. scene.getEngine().cullBackFaces = false;
  14153. };
  14154. this.onAfterRender = function () {
  14155. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  14156. scene.getEngine().cullBackFaces = true;
  14157. delete scene.clipPlane;
  14158. };
  14159. }
  14160. MirrorTexture.prototype.clone = function () {
  14161. var textureSize = this.getSize();
  14162. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  14163. // Base texture
  14164. newTexture.hasAlpha = this.hasAlpha;
  14165. newTexture.level = this.level;
  14166. // Mirror Texture
  14167. newTexture.mirrorPlane = this.mirrorPlane.clone();
  14168. newTexture.renderList = this.renderList.slice(0);
  14169. return newTexture;
  14170. };
  14171. return MirrorTexture;
  14172. })(BABYLON.RenderTargetTexture);
  14173. BABYLON.MirrorTexture = MirrorTexture;
  14174. })(BABYLON || (BABYLON = {}));
  14175. //# sourceMappingURL=babylon.mirrorTexture.js.map
  14176. var BABYLON;
  14177. (function (BABYLON) {
  14178. var DynamicTexture = (function (_super) {
  14179. __extends(DynamicTexture, _super);
  14180. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  14181. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14182. _super.call(this, null, scene, !generateMipMaps);
  14183. this.name = name;
  14184. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14185. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14186. this._generateMipMaps = generateMipMaps;
  14187. if (options.getContext) {
  14188. this._canvas = options;
  14189. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  14190. }
  14191. else {
  14192. this._canvas = document.createElement("canvas");
  14193. if (options.width) {
  14194. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  14195. }
  14196. else {
  14197. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  14198. }
  14199. }
  14200. var textureSize = this.getSize();
  14201. this._canvas.width = textureSize.width;
  14202. this._canvas.height = textureSize.height;
  14203. this._context = this._canvas.getContext("2d");
  14204. }
  14205. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  14206. get: function () {
  14207. return true;
  14208. },
  14209. enumerable: true,
  14210. configurable: true
  14211. });
  14212. DynamicTexture.prototype.scale = function (ratio) {
  14213. var textureSize = this.getSize();
  14214. textureSize.width *= ratio;
  14215. textureSize.height *= ratio;
  14216. this._canvas.width = textureSize.width;
  14217. this._canvas.height = textureSize.height;
  14218. this.releaseInternalTexture();
  14219. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  14220. };
  14221. DynamicTexture.prototype.getContext = function () {
  14222. return this._context;
  14223. };
  14224. DynamicTexture.prototype.clear = function () {
  14225. var size = this.getSize();
  14226. this._context.fillRect(0, 0, size.width, size.height);
  14227. };
  14228. DynamicTexture.prototype.update = function (invertY) {
  14229. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  14230. };
  14231. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  14232. if (update === void 0) { update = true; }
  14233. var size = this.getSize();
  14234. if (clearColor) {
  14235. this._context.fillStyle = clearColor;
  14236. this._context.fillRect(0, 0, size.width, size.height);
  14237. }
  14238. this._context.font = font;
  14239. if (x === null) {
  14240. var textSize = this._context.measureText(text);
  14241. x = (size.width - textSize.width) / 2;
  14242. }
  14243. this._context.fillStyle = color;
  14244. this._context.fillText(text, x, y);
  14245. if (update) {
  14246. this.update(invertY);
  14247. }
  14248. };
  14249. DynamicTexture.prototype.clone = function () {
  14250. var textureSize = this.getSize();
  14251. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  14252. // Base texture
  14253. newTexture.hasAlpha = this.hasAlpha;
  14254. newTexture.level = this.level;
  14255. // Dynamic Texture
  14256. newTexture.wrapU = this.wrapU;
  14257. newTexture.wrapV = this.wrapV;
  14258. return newTexture;
  14259. };
  14260. return DynamicTexture;
  14261. })(BABYLON.Texture);
  14262. BABYLON.DynamicTexture = DynamicTexture;
  14263. })(BABYLON || (BABYLON = {}));
  14264. //# sourceMappingURL=babylon.dynamicTexture.js.map
  14265. var BABYLON;
  14266. (function (BABYLON) {
  14267. var VideoTexture = (function (_super) {
  14268. __extends(VideoTexture, _super);
  14269. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  14270. var _this = this;
  14271. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14272. _super.call(this, null, scene, !generateMipMaps, invertY);
  14273. this._autoLaunch = true;
  14274. this.name = name;
  14275. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  14276. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  14277. var requiredWidth = size.width || size;
  14278. var requiredHeight = size.height || size;
  14279. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  14280. var textureSize = this.getSize();
  14281. this.video = document.createElement("video");
  14282. this.video.width = textureSize.width;
  14283. this.video.height = textureSize.height;
  14284. this.video.autoplay = false;
  14285. this.video.loop = true;
  14286. this.video.addEventListener("canplaythrough", function () {
  14287. if (_this._texture) {
  14288. _this._texture.isReady = true;
  14289. }
  14290. });
  14291. urls.forEach(function (url) {
  14292. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  14293. var source = document.createElement("source");
  14294. source.src = url;
  14295. _this.video.appendChild(source);
  14296. });
  14297. this._lastUpdate = BABYLON.Tools.Now;
  14298. }
  14299. VideoTexture.prototype.update = function () {
  14300. if (this._autoLaunch) {
  14301. this._autoLaunch = false;
  14302. this.video.play();
  14303. }
  14304. var now = BABYLON.Tools.Now;
  14305. if (now - this._lastUpdate < 15) {
  14306. return false;
  14307. }
  14308. this._lastUpdate = now;
  14309. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  14310. return true;
  14311. };
  14312. return VideoTexture;
  14313. })(BABYLON.Texture);
  14314. BABYLON.VideoTexture = VideoTexture;
  14315. })(BABYLON || (BABYLON = {}));
  14316. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  14317. (function (BABYLON) {
  14318. var EffectFallbacks = (function () {
  14319. function EffectFallbacks() {
  14320. this._defines = {};
  14321. this._currentRank = 32;
  14322. this._maxRank = -1;
  14323. }
  14324. EffectFallbacks.prototype.addFallback = function (rank, define) {
  14325. if (!this._defines[rank]) {
  14326. if (rank < this._currentRank) {
  14327. this._currentRank = rank;
  14328. }
  14329. if (rank > this._maxRank) {
  14330. this._maxRank = rank;
  14331. }
  14332. this._defines[rank] = new Array();
  14333. }
  14334. this._defines[rank].push(define);
  14335. };
  14336. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  14337. get: function () {
  14338. return this._currentRank <= this._maxRank;
  14339. },
  14340. enumerable: true,
  14341. configurable: true
  14342. });
  14343. EffectFallbacks.prototype.reduce = function (currentDefines) {
  14344. var currentFallbacks = this._defines[this._currentRank];
  14345. for (var index = 0; index < currentFallbacks.length; index++) {
  14346. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  14347. }
  14348. this._currentRank++;
  14349. return currentDefines;
  14350. };
  14351. return EffectFallbacks;
  14352. })();
  14353. BABYLON.EffectFallbacks = EffectFallbacks;
  14354. var Effect = (function () {
  14355. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  14356. var _this = this;
  14357. this._isReady = false;
  14358. this._compilationError = "";
  14359. this._valueCache = [];
  14360. this._engine = engine;
  14361. this.name = baseName;
  14362. this.defines = defines;
  14363. this._uniformsNames = uniformsNames.concat(samplers);
  14364. this._samplers = samplers;
  14365. this._attributesNames = attributesNames;
  14366. this.onError = onError;
  14367. this.onCompiled = onCompiled;
  14368. var vertexSource;
  14369. var fragmentSource;
  14370. if (baseName.vertexElement) {
  14371. vertexSource = document.getElementById(baseName.vertexElement);
  14372. if (!vertexSource) {
  14373. vertexSource = baseName.vertexElement;
  14374. }
  14375. }
  14376. else {
  14377. vertexSource = baseName.vertex || baseName;
  14378. }
  14379. if (baseName.fragmentElement) {
  14380. fragmentSource = document.getElementById(baseName.fragmentElement);
  14381. if (!fragmentSource) {
  14382. fragmentSource = baseName.fragmentElement;
  14383. }
  14384. }
  14385. else {
  14386. fragmentSource = baseName.fragment || baseName;
  14387. }
  14388. this._loadVertexShader(vertexSource, function (vertexCode) {
  14389. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  14390. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  14391. });
  14392. });
  14393. }
  14394. // Properties
  14395. Effect.prototype.isReady = function () {
  14396. return this._isReady;
  14397. };
  14398. Effect.prototype.getProgram = function () {
  14399. return this._program;
  14400. };
  14401. Effect.prototype.getAttributesNames = function () {
  14402. return this._attributesNames;
  14403. };
  14404. Effect.prototype.getAttributeLocation = function (index) {
  14405. return this._attributes[index];
  14406. };
  14407. Effect.prototype.getAttributeLocationByName = function (name) {
  14408. var index = this._attributesNames.indexOf(name);
  14409. return this._attributes[index];
  14410. };
  14411. Effect.prototype.getAttributesCount = function () {
  14412. return this._attributes.length;
  14413. };
  14414. Effect.prototype.getUniformIndex = function (uniformName) {
  14415. return this._uniformsNames.indexOf(uniformName);
  14416. };
  14417. Effect.prototype.getUniform = function (uniformName) {
  14418. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  14419. };
  14420. Effect.prototype.getSamplers = function () {
  14421. return this._samplers;
  14422. };
  14423. Effect.prototype.getCompilationError = function () {
  14424. return this._compilationError;
  14425. };
  14426. // Methods
  14427. Effect.prototype._loadVertexShader = function (vertex, callback) {
  14428. // DOM element ?
  14429. if (vertex instanceof HTMLElement) {
  14430. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  14431. callback(vertexCode);
  14432. return;
  14433. }
  14434. // Is in local store ?
  14435. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  14436. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  14437. return;
  14438. }
  14439. var vertexShaderUrl;
  14440. if (vertex[0] === ".") {
  14441. vertexShaderUrl = vertex;
  14442. }
  14443. else {
  14444. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  14445. }
  14446. // Vertex shader
  14447. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  14448. };
  14449. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  14450. // DOM element ?
  14451. if (fragment instanceof HTMLElement) {
  14452. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  14453. callback(fragmentCode);
  14454. return;
  14455. }
  14456. // Is in local store ?
  14457. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  14458. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  14459. return;
  14460. }
  14461. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  14462. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  14463. return;
  14464. }
  14465. var fragmentShaderUrl;
  14466. if (fragment[0] === ".") {
  14467. fragmentShaderUrl = fragment;
  14468. }
  14469. else {
  14470. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  14471. }
  14472. // Fragment shader
  14473. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  14474. };
  14475. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  14476. try {
  14477. var engine = this._engine;
  14478. if (!engine.getCaps().highPrecisionShaderSupported) {
  14479. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  14480. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  14481. }
  14482. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  14483. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  14484. this._attributes = engine.getAttributes(this._program, attributesNames);
  14485. for (var index = 0; index < this._samplers.length; index++) {
  14486. var sampler = this.getUniform(this._samplers[index]);
  14487. if (sampler == null) {
  14488. this._samplers.splice(index, 1);
  14489. index--;
  14490. }
  14491. }
  14492. engine.bindSamplers(this);
  14493. this._isReady = true;
  14494. if (this.onCompiled) {
  14495. this.onCompiled(this);
  14496. }
  14497. }
  14498. catch (e) {
  14499. // Is it a problem with precision?
  14500. if (e.message.indexOf("highp") !== -1) {
  14501. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  14502. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  14503. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  14504. return;
  14505. }
  14506. // Let's go through fallbacks then
  14507. if (fallbacks && fallbacks.isMoreFallbacks) {
  14508. defines = fallbacks.reduce(defines);
  14509. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  14510. }
  14511. else {
  14512. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  14513. BABYLON.Tools.Error("Defines: " + defines);
  14514. BABYLON.Tools.Error("Error: " + e.message);
  14515. this._compilationError = e.message;
  14516. if (this.onError) {
  14517. this.onError(this, this._compilationError);
  14518. }
  14519. }
  14520. }
  14521. };
  14522. Effect.prototype._bindTexture = function (channel, texture) {
  14523. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  14524. };
  14525. Effect.prototype.setTexture = function (channel, texture) {
  14526. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  14527. };
  14528. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14529. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  14530. };
  14531. //public _cacheMatrix(uniformName, matrix) {
  14532. // if (!this._valueCache[uniformName]) {
  14533. // this._valueCache[uniformName] = new BABYLON.Matrix();
  14534. // }
  14535. // for (var index = 0; index < 16; index++) {
  14536. // this._valueCache[uniformName].m[index] = matrix.m[index];
  14537. // }
  14538. //};
  14539. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  14540. if (!this._valueCache[uniformName]) {
  14541. this._valueCache[uniformName] = [x, y];
  14542. return;
  14543. }
  14544. this._valueCache[uniformName][0] = x;
  14545. this._valueCache[uniformName][1] = y;
  14546. };
  14547. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  14548. if (!this._valueCache[uniformName]) {
  14549. this._valueCache[uniformName] = [x, y, z];
  14550. return;
  14551. }
  14552. this._valueCache[uniformName][0] = x;
  14553. this._valueCache[uniformName][1] = y;
  14554. this._valueCache[uniformName][2] = z;
  14555. };
  14556. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  14557. if (!this._valueCache[uniformName]) {
  14558. this._valueCache[uniformName] = [x, y, z, w];
  14559. return;
  14560. }
  14561. this._valueCache[uniformName][0] = x;
  14562. this._valueCache[uniformName][1] = y;
  14563. this._valueCache[uniformName][2] = z;
  14564. this._valueCache[uniformName][3] = w;
  14565. };
  14566. Effect.prototype.setArray = function (uniformName, array) {
  14567. this._engine.setArray(this.getUniform(uniformName), array);
  14568. return this;
  14569. };
  14570. Effect.prototype.setArray2 = function (uniformName, array) {
  14571. this._engine.setArray2(this.getUniform(uniformName), array);
  14572. return this;
  14573. };
  14574. Effect.prototype.setArray3 = function (uniformName, array) {
  14575. this._engine.setArray3(this.getUniform(uniformName), array);
  14576. return this;
  14577. };
  14578. Effect.prototype.setArray4 = function (uniformName, array) {
  14579. this._engine.setArray4(this.getUniform(uniformName), array);
  14580. return this;
  14581. };
  14582. Effect.prototype.setMatrices = function (uniformName, matrices) {
  14583. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  14584. return this;
  14585. };
  14586. Effect.prototype.setMatrix = function (uniformName, matrix) {
  14587. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  14588. // return;
  14589. //this._cacheMatrix(uniformName, matrix);
  14590. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  14591. return this;
  14592. };
  14593. Effect.prototype.setFloat = function (uniformName, value) {
  14594. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  14595. return this;
  14596. this._valueCache[uniformName] = value;
  14597. this._engine.setFloat(this.getUniform(uniformName), value);
  14598. return this;
  14599. };
  14600. Effect.prototype.setBool = function (uniformName, bool) {
  14601. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  14602. return this;
  14603. this._valueCache[uniformName] = bool;
  14604. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  14605. return this;
  14606. };
  14607. Effect.prototype.setVector2 = function (uniformName, vector2) {
  14608. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  14609. return this;
  14610. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  14611. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  14612. return this;
  14613. };
  14614. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  14615. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  14616. return this;
  14617. this._cacheFloat2(uniformName, x, y);
  14618. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  14619. return this;
  14620. };
  14621. Effect.prototype.setVector3 = function (uniformName, vector3) {
  14622. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  14623. return this;
  14624. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  14625. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  14626. return this;
  14627. };
  14628. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  14629. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  14630. return this;
  14631. this._cacheFloat3(uniformName, x, y, z);
  14632. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  14633. return this;
  14634. };
  14635. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  14636. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  14637. return this;
  14638. this._cacheFloat4(uniformName, x, y, z, w);
  14639. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  14640. return this;
  14641. };
  14642. Effect.prototype.setColor3 = function (uniformName, color3) {
  14643. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  14644. return this;
  14645. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  14646. this._engine.setColor3(this.getUniform(uniformName), color3);
  14647. return this;
  14648. };
  14649. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  14650. 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)
  14651. return this;
  14652. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  14653. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  14654. return this;
  14655. };
  14656. // Statics
  14657. Effect.ShadersStore={anaglyphPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\n\nvoid main(void)\n{\nvec4 leftFrag = texture2D(leftSampler, vUV);\nleftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\n\nvec4 rightFrag = texture2D(textureSampler, vUV);\nrightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\n\ngl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\n}",
  14658. blackAndWhitePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void)\n{\nfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\ngl_FragColor = vec4(luminance, luminance, luminance, 1.0);\n}",
  14659. blurPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nvoid main(void)\n{\nfloat weights[7];\nweights[0] = 0.05;\nweights[1] = 0.1;\nweights[2] = 0.2;\nweights[3] = 0.3;\nweights[4] = 0.2;\nweights[5] = 0.1;\nweights[6] = 0.05;\n\nvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\nvec2 texelStep = texelSize * direction * blurWidth;\nvec2 start = vUV - 3.0 * texelStep;\n\nvec4 baseColor = vec4(0., 0., 0., 0.);\nvec2 texelOffset = vec2(0., 0.);\n\nfor (int i = 0; i < 7; i++)\n{\nbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\ntexelOffset += texelStep;\n}\n\ngl_FragColor = baseColor;\n}",
  14660. 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) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn 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) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nfloat round(float number){\nreturn sign(number)*floor(abs(number) + 0.5);\n}\n\nvoid main(void)\n{\nfloat brickW = 1.0 / numberOfBricksWidth;\nfloat brickH = 1.0 / numberOfBricksHeight;\nfloat jointWPercentage = 0.01;\nfloat jointHPercentage = 0.05;\nvec3 color = brickColor;\nfloat yi = vUV.y / brickH;\nfloat nyi = round(yi);\nfloat xi = vUV.x / brickW;\n\nif (mod(floor(yi), 2.0) == 0.0){\nxi = xi - 0.5;\n}\n\nfloat nxi = round(xi);\nvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\nif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\ncolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n}\nelse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\ncolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n}\nelse {\nfloat brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\n\nif (brickColorSwitch == 0.0)\ncolor = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\nelse if (brickColorSwitch == 2.0)\ncolor = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\n}\n\ngl_FragColor = vec4(color, 1.0);\n}",
  14661. chromaticAberrationPixelShader:"\n#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler; // original color\n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvoid main(void)\n{\nvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\nfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\n+ centered_screen_pos.y*centered_screen_pos.y;\nfloat radius = sqrt(radius2);\n\nvec4 original = texture2D(textureSampler, vUV);\n\nif (chromatic_aberration > 0.0) {\nvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\nfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\nfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\n\nvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\n\noriginal.r = texture2D(textureSampler, ref_coords_r).r;\noriginal.g = texture2D(textureSampler, ref_coords_g).g;\noriginal.b = texture2D(textureSampler, ref_coords_b).b;\n}\n\ngl_FragColor = original;\n}",
  14662. 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) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn 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) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nvoid main() {\n\nvec2 p = vUV * 12.0;\nvec3 c = mix(skyColor, cloudColor, fbm(p));\ngl_FragColor = vec4(c, 1);\n\n}",
  14663. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\ngl_FragColor = color;\n}",
  14664. colorVertexShader:"precision highp float;\n\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\n\nvoid main(void) {\ngl_Position = worldViewProjection * vec4(position, 1.0);\n}",
  14665. colorCorrectionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler; // screen render\nuniform sampler2D colorTable; // color table with modified colors\n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT = 16.0; // how many slices in the color cube; 1 slice = 1 pixel\n\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\nfloat sliceSize = 1.0 / width; // space of 1 slice\nfloat slicePixelSize = sliceSize / width; // space of 1 pixel\nfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\nfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\nfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\nfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\nfloat s0 = xOffset + (zSlice0 * sliceSize);\nfloat s1 = xOffset + (zSlice1 * sliceSize);\nvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\nvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\nfloat zOffset = mod(uv.z * width, 1.0);\nvec4 result = mix(slice0Color, slice1Color, zOffset);\nreturn result;\n}\n\nvoid main(void)\n{\nvec4 screen_color = texture2D(textureSampler, vUV);\ngl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\n\n}",
  14666. convolutionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform float kernel[9];\n\nvoid main(void)\n{\nvec2 onePixel = vec2(1.0, 1.0) / screenSize;\nvec4 colorSum =\ntexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\ntexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\ntexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\ntexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\ntexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\ntexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\ntexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\ntexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\ntexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\n\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\n\nif (kernelWeight <= 0.0) {\nkernelWeight = 1.0;\n}\n\ngl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\n}",
  14667. 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\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\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#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#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\nfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\nreturn 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#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{\nif (mode == MAP_SPHERICAL)\n{\nvec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\nreturn vec3(reflectionMatrix * vec4(coords, 1.0));\n}\nelse if (mode == MAP_PLANAR)\n{\nvec3 viewDir = worldPos.xyz - vEyePosition;\nvec3 coords = normalize(reflect(viewDir, worldNormal));\n\nreturn vec3(reflectionMatrix * vec4(coords, 1));\n}\nelse if (mode == MAP_CUBIC)\n{\nvec3 viewDir = worldPos.xyz - vEyePosition;\nvec3 coords = reflect(viewDir, worldNormal);\n\nreturn vec3(reflectionMatrix * vec4(coords, 0));\n}\nelse if (mode == MAP_PROJECTION)\n{\nreturn vec3(reflectionMatrix * (view * worldPos));\n}\nelse if (mode == MAP_SKYBOX)\n{\nreturn vPositionUVW;\n}\n\nreturn vec3(0, 0, 0);\n}\n#endif\n\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\nreturn dot(color, bit_shift);\n}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\n{\nvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\ndepth = 0.5 * depth + vec3(0.5);\nvec2 uv = depth.xy;\n\nif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n{\nreturn 1.0;\n}\n\nfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\n\nif (depth.z > shadow)\n{\nreturn darkness;\n}\nreturn 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias)\n{\nvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\ndepth = 0.5 * depth + vec3(0.5);\nvec2 uv = depth.xy;\n\nif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n{\nreturn 1.0;\n}\n\nfloat visibility = 1.;\n\nvec2 poissonDisk[4];\npoissonDisk[0] = vec2(-0.94201624, -0.39906216);\npoissonDisk[1] = vec2(0.94558609, -0.76890725);\npoissonDisk[2] = vec2(-0.094184101, -0.92938870);\npoissonDisk[3] = vec2(0.34495938, 0.29387760);\n\nfloat biasedDepth = depth.z - bias;\n\nif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) < biasedDepth) visibility -= 0.25;\nif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) < biasedDepth) visibility -= 0.25;\nif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) < biasedDepth) visibility -= 0.25;\nif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) < biasedDepth) visibility -= 0.25;\n\nreturn visibility;\n}\n\nfloat linstep(float low, float high, float v) {\nreturn clamp((v - low) / (high - low), 0.0, 1.0);\n}\n\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\n{\nfloat p = smoothstep(compare - bias, compare, moments.x);\nfloat variance = max(moments.y - moments.x * moments.x, 0.02);\nfloat d = compare - moments.x;\nfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\n\nreturn clamp(max(p, p_max), 0.0, 1.0);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias)\n{\nvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\ndepth = 0.5 * depth + vec3(0.5);\nvec2 uv = depth.xy;\n\nif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\n{\nreturn 1.0;\n}\n\nvec4 texel = texture2D(shadowSampler, uv);\n\nvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\nreturn 1.0 - ChebychevInequality(moments, depth.z, bias);\n}\n#endif\n\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\nvec3 dp1 = dFdx(p);\nvec3 dp2 = dFdy(p);\nvec2 duv1 = dFdx(uv);\nvec2 duv2 = dFdy(uv);\n\nvec3 dp2perp = cross(dp2, normal);\nvec3 dp1perp = cross(normal, dp1);\nvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\nvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\nfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\nreturn mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\nvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\nmap = map * 255. / 127. - 128. / 127.;\nmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\nreturn normalize(TBN * map);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\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{\nfloat fogCoeff = 1.0;\nfloat fogStart = vFogInfos.y;\nfloat fogEnd = vFogInfos.z;\nfloat fogDensity = vFogInfos.w;\n\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n}\n\nreturn clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\nstruct lightingInfo\n{\nvec3 diffuse;\nvec3 specular;\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\nlightingInfo result;\n\nvec3 lightVectorW;\nfloat attenuation = 1.0;\nif (lightData.w == 0.)\n{\nvec3 direction = lightData.xyz - vPositionW;\n\nattenuation = max(0., 1.0 - length(direction) / range);\nlightVectorW = normalize(direction);\n}\nelse\n{\nlightVectorW = normalize(-lightData.xyz);\n}\n\nfloat ndl = max(0., dot(vNormal, lightVectorW));\n\nvec3 angleW = normalize(viewDirectionW + lightVectorW);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = pow(specComp, max(1., vSpecularColor.a));\n\nresult.diffuse = ndl * diffuseColor * attenuation;\nresult.specular = specComp * specularColor * attenuation;\n\nreturn result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\nlightingInfo result;\n\nvec3 direction = lightData.xyz - vPositionW;\nvec3 lightVectorW = normalize(direction);\nfloat attenuation = max(0., 1.0 - length(direction) / range);\n\nfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\nfloat spotAtten = 0.0;\n\nif (cosAngle >= lightDirection.w)\n{\ncosAngle = max(0., pow(cosAngle, lightData.w));\nspotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\n\nfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\nvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = pow(specComp, vSpecularColor.a);\n\nresult.diffuse = ndl * spotAtten * diffuseColor * attenuation;\nresult.specular = specComp * specularColor * spotAtten * attenuation;\n\nreturn result;\n}\n\nresult.diffuse = vec3(0.);\nresult.specular = vec3(0.);\n\nreturn result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\nlightingInfo result;\n\nfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\nvec3 angleW = normalize(viewDirectionW + lightData.xyz);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = pow(specComp, vSpecularColor.a);\n\nresult.diffuse = mix(groundColor, diffuseColor, ndl);\nresult.specular = specComp * specularColor;\n\nreturn result;\n}\n\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance > 0.0)\ndiscard;\n#endif\n\nvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\nvec4 baseColor = vec4(1., 1., 1., 1.);\nvec3 diffuseColor = vDiffuseColor.rgb;\n\nfloat alpha = vDiffuseColor.a;\n\n#ifdef VERTEXCOLOR\nbaseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\nbaseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\nif (baseColor.a < 0.4)\ndiscard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\nalpha *= baseColor.a;\n#endif\n\nbaseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n#ifdef NORMAL\nvec3 normalW = normalize(vNormalW);\n#else\nvec3 normalW = vec3(1.0, 1.0, 1.0);\n#endif\n\n\n#ifdef BUMP\nnormalW = perturbNormal(viewDirectionW);\n#endif\n\n\nvec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\nbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase = vec3(0., 0., 0.);\nvec3 specularBase = vec3(0., 0., 0.);\nfloat shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\nlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef HEMILIGHT0\nlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\nlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\nshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z);\n#else\n#ifdef SHADOWPCF0\nshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z);\n#else\nshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\n#endif\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info.diffuse * shadow;\nspecularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\ninfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\nshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z);\n#else\n#ifdef SHADOWPCF1\nshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z);\n#else\nshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\n#endif\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info.diffuse * shadow;\nspecularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\ninfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\nshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z);\n#else\n#ifdef SHADOWPCF2\nshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z);\n#else\nshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\n#endif\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info.diffuse * shadow;\nspecularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\ninfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\nshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z);\n#else\n#ifdef SHADOWPCF3\nshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z);\n#else\nshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\n#endif\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info.diffuse * shadow;\nspecularBase += info.specular * shadow;\n#endif\n\nvec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\nvec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\nif (vReflectionInfos.z != 0.0)\n{\nreflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n}\nelse\n{\nvec2 coords = vReflectionUVW.xy;\n\nif (vReflectionInfos.x == MAP_PROJECTION)\n{\ncoords /= vReflectionUVW.z;\n}\n\ncoords.y = 1.0 - coords.y;\n\nreflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n}\n\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\nreflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\nopacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\nalpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\nalpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n#endif\n\n#ifdef VERTEXALPHA\nalpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\nalpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\nvec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\nemissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\nvec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\ndiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\nvec3 finalSpecular = specularBase * specularColor;\n\n#ifdef SPECULAROVERALPHA\nalpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n\nvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\nfloat fog = CalcFogFactor();\ncolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\ngl_FragColor = color;\n}",
  14668. defaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\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\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\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) {\nmat4 finalWorld;\n\n#ifdef REFLECTION\nvPositionUVW = position;\n#endif\n\n#ifdef INSTANCES\nfinalWorld = mat4(world0, world1, world2, world3);\n#else\nfinalWorld = world;\n#endif\n\n#ifdef BONES\nmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\nmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\nmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\nmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\nfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\n#else\nfinalWorld = finalWorld * (m0 + m1 + m2);\n#endif\n\n#endif\ngl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\nvec4 worldPos = finalWorld * vec4(position, 1.0);\nvPositionW = vec3(worldPos);\n\n#ifdef NORMAL\nvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\nvec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef SPECULAR\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef CLIPPLANE\nfClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n#ifdef FOG\nfFogDistance = (view * worldPos).z;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nvPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\nvPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\nvPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\nvPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n#ifdef VERTEXCOLOR\nvColor = color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize = pointSize;\n#endif\n}",
  14669. 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\nif (texture2D(diffuseSampler, vUV).a < 0.4)\ndiscard;\n#endif\n\nfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\ngl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\n}",
  14670. depthVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\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#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\nmat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\nmat4 finalWorld = world;\n#endif\n\n#ifdef BONES\nmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\nmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\nmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\nmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\nfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\ngl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#else\ngl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\nvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  14671. depthBoxBlurPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\n\nvoid main(void)\n{\nvec4 colorDepth = vec4(0.0);\n\nfor (int x = -OFFSET; x <= OFFSET; x++)\nfor (int y = -OFFSET; y <= OFFSET; y++)\ncolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\n\ngl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\n}",
  14672. depthOfFieldPixelShader:"\n#ifdef GL_ES\nprecision highp float;\n#endif\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\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 edge_blur;\nuniform bool highlights;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n\nvec2 centered_screen_pos;\nfloat radius2;\nfloat radius;\n\n\nvec2 getDistortedCoords(vec2 coords) {\n\nif (distortion == 0.0) { return coords; }\n\nvec2 direction = 1.0 * normalize(centered_screen_pos);\nvec2 dist_coords = vec2(0.5, 0.5);\ndist_coords.x = 0.5 + direction.x * radius2 * 1.0;\ndist_coords.y = 0.5 + direction.y * radius2 * 1.0;\nfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\n\ndist_coords = mix(coords, dist_coords, dist_amount);\n\nreturn dist_coords;\n}\n\nvec4 getBlurColor(vec2 coords, float size) {\n\nvec4 col = texture2D(textureSampler, coords);\nif (size == 0.0) { return col; }\n\nfloat blur_level = min(3.0, ceil(size / 1.0));\n\nfloat w = (size / screen_width);\nfloat h = (size / screen_height);\nfloat total_weight = 1.0;\n\ncol += texture2D(textureSampler, coords + vec2(-0.53*w, 0.15*h))*0.93;\ncol += texture2D(textureSampler, coords + vec2(0.42*w, -0.69*h))*0.90;\ncol += texture2D(textureSampler, coords + vec2(0.20*w, 1.00*h))*0.87;\ncol += texture2D(textureSampler, coords + vec2(-0.97*w, -0.72*h))*0.85;\ncol += texture2D(textureSampler, coords + vec2(1.37*w, -0.14*h))*0.83;\ncol += texture2D(textureSampler, coords + vec2(-1.02*w, 1.16*h))*0.80;\ncol += texture2D(textureSampler, coords + vec2(-0.03*w, -1.69*h))*0.78;\ncol += texture2D(textureSampler, coords + vec2(1.27*w, 1.34*h))*0.76;\ncol += texture2D(textureSampler, coords + vec2(-1.98*w, -0.14*h))*0.74;\ncol += texture2D(textureSampler, coords + vec2(1.66*w, -1.32*h))*0.72;\ntotal_weight += 8.18;\n\nif (blur_level > 1.0) {\ncol += texture2D(textureSampler, coords + vec2(-0.35*w, 2.22*h))*0.70;\ncol += texture2D(textureSampler, coords + vec2(-1.31*w, -1.98*h))*0.67;\ncol += texture2D(textureSampler, coords + vec2(2.42*w, 0.61*h))*0.65;\ncol += texture2D(textureSampler, coords + vec2(-2.31*w, 1.25*h))*0.63;\ncol += texture2D(textureSampler, coords + vec2(0.90*w, -2.59*h))*0.61;\ncol += texture2D(textureSampler, coords + vec2(1.14*w, 2.62*h))*0.59;\ncol += texture2D(textureSampler, coords + vec2(-2.72*w, -1.21*h))*0.56;\ncol += texture2D(textureSampler, coords + vec2(2.93*w, -0.98*h))*0.54;\ncol += texture2D(textureSampler, coords + vec2(-1.56*w, 2.80*h))*0.52;\ncol += texture2D(textureSampler, coords + vec2(-0.77*w, -3.22*h))*0.49;\ntotal_weight += 5.96;\n}\n\nif (blur_level > 2.0) {\ncol += texture2D(textureSampler, coords + vec2(2.83*w, 1.92*h))*0.46;\ncol += texture2D(textureSampler, coords + vec2(-3.49*w, 0.51*h))*0.44;\ncol += texture2D(textureSampler, coords + vec2(2.30*w, -2.82*h))*0.41;\ncol += texture2D(textureSampler, coords + vec2(0.22*w, 3.74*h))*0.38;\ncol += texture2D(textureSampler, coords + vec2(-2.76*w, -2.68*h))*0.34;\ncol += texture2D(textureSampler, coords + vec2(3.95*w, 0.11*h))*0.31;\ncol += texture2D(textureSampler, coords + vec2(-3.07*w, 2.65*h))*0.26;\ncol += texture2D(textureSampler, coords + vec2(0.48*w, -4.13*h))*0.22;\ncol += texture2D(textureSampler, coords + vec2(2.49*w, 3.46*h))*0.15;\ntotal_weight += 2.97;\n}\n\ncol /= total_weight; // scales color according to weights\ncol.a = 1.0;\n\n\nreturn col;\n}\n\nvec2 rand(vec2 co)\n{\nfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\nfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\nreturn clamp(vec2(noise1, noise2), 0.0, 1.0);\n}\n\nvoid main(void)\n{\n\ncentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\nradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\nradius = sqrt(radius2);\n\nvec4 final_color;\nvec2 distorted_coords = getDistortedCoords(vUV);\nvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height); // varies from 0 to SCREEN_WIDTH or _HEIGHT\n\nfloat dof_blur_amount = 0.0;\nfloat depth_bias = 0.0; // positive if the pixel is further than focus depth; negative if closer\nif (focus_depth != -1.0) {\nvec4 depth_sample = texture2D(depthSampler, distorted_coords);\nfloat depth = depth_sample.r;\ndepth_bias = depth - focus_depth;\n\nif (depth_bias > 0.0) { dof_blur_amount = depth_bias * aperture * 2.2; }\nelse { dof_blur_amount = depth_bias * depth_bias * aperture * 30.0; }\n\nif (dof_blur_amount < 0.05) { dof_blur_amount = 0.0; } // no blur at all\n}\n\nfloat edge_blur_amount = 0.0;\nif (edge_blur > 0.0) {\nedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\n}\n\nfloat blur_amount = max(edge_blur_amount, dof_blur_amount);\n\nif (blur_amount == 0.0) {\ngl_FragColor = texture2D(textureSampler, distorted_coords);\n}\nelse {\n\ngl_FragColor = getBlurColor(distorted_coords, blur_amount * 1.7);\n\nif (depth_bias > 0.0 && highlights) {\ngl_FragColor += clamp(dof_blur_amount, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords);\n}\n\nif (blur_noise) {\nvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\nvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\ngl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\n}\n}\n\nif (grain_amount > 0.0) {\nvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\ngl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.20;\n}\n}",
  14673. displayPassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\n\nvoid main(void)\n{\ngl_FragColor = texture2D(passSampler, vUV);\n}",
  14674. filterPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform mat4 kernelMatrix;\n\nvoid main(void)\n{\nvec3 baseColor = texture2D(textureSampler, vUV).rgb;\nvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\n\ngl_FragColor = vec4(updatedColor, 1.0);\n}",
  14675. 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) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn 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) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nvoid main() {\nvec2 p = vUV * 8.0;\nfloat q = fbm(p - time * 0.1);\nvec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\nvec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\nvec3 color = c * cos(shift * vUV.y);\nfloat luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\n\ngl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\n}",
  14676. 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(){\nvec2 localTexelSize = texelSize;\nvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\nvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\nvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\nvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\nvec4 rgbM = texture2D(textureSampler, vUV);\nvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\nfloat lumaNW = dot(rgbNW, luma);\nfloat lumaNE = dot(rgbNE, luma);\nfloat lumaSW = dot(rgbSW, luma);\nfloat lumaSE = dot(rgbSE, luma);\nfloat lumaM = dot(rgbM, luma);\nfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\nfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\nvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\n\nfloat dirReduce = max(\n(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\n\nfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\ndir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\ndir * rcpDirMin)) * localTexelSize;\n\nvec4 rgbA = 0.5 * (\ntexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\ntexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\n\nvec4 rgbB = rgbA * 0.5 + 0.25 * (\ntexture2D(textureSampler, vUV + dir * -0.5) +\ntexture2D(textureSampler, vUV + dir * 0.5));\nfloat lumaB = dot(rgbB, luma);\nif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\ngl_FragColor = rgbA;\n}\nelse {\ngl_FragColor = rgbB;\n}\n}",
  14677. 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) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn 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) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nvoid main(void) {\nvec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\ncolor = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\ncolor = mix(color, herb3Color, rand(gl_FragCoord.xy));\ncolor = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\ngl_FragColor = vec4(color, 1.0);\n}",
  14678. layerPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\n\nvoid main(void) {\nvec4 baseColor = texture2D(textureSampler, vUV);\n\ngl_FragColor = baseColor * color;\n}",
  14679. layerVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec2 position;\n\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) {\n\nvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\ngl_Position = vec4(position, 0.0, 1.0);\n}",
  14680. legacydefaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_PROJECTION 4.\n\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\nvarying vec3 vNormalW;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\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#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#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\nfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\nreturn 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#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\nconst vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\nreturn dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\nvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\nvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\nif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n{\nreturn 1.0;\n}\n\nfloat shadow = unpack(texture2D(shadowSampler, uv));\n\nif (depth.z > shadow)\n{\nreturn 0.;\n}\nreturn 1.;\n}\n\nfloat ChebychevInequality(vec2 moments, float t)\n{\nif (t <= moments.x)\n{\nreturn 1.0;\n}\n\nfloat variance = moments.y - (moments.x * moments.x);\nvariance = max(variance, 0.);\n\nfloat d = t - moments.x;\nreturn variance / (variance + d * d);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\n{\nvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\nvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\nif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n{\nreturn 1.0;\n}\n\nvec4 texel = texture2D(shadowSampler, uv);\n\nvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\nreturn clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\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{\nfloat fogCoeff = 1.0;\nfloat fogStart = vFogInfos.y;\nfloat fogEnd = vFogInfos.z;\nfloat fogDensity = vFogInfos.w;\n\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n}\n\nreturn clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\nmat3 result;\n\nvec3 lightVectorW;\nif (lightData.w == 0.)\n{\nlightVectorW = normalize(lightData.xyz - vPositionW);\n}\nelse\n{\nlightVectorW = normalize(-lightData.xyz);\n}\n\nfloat ndl = max(0., dot(vNormal, lightVectorW));\n\nvec3 angleW = normalize(viewDirectionW + lightVectorW);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\n\nresult[0] = ndl * diffuseColor.rgb;\nresult[1] = specComp * specularColor;\nresult[2] = vec3(0.);\n\nreturn result;\n}\n\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\nmat3 result;\n\nvec3 lightVectorW = normalize(lightData.xyz - vPositionW);\n\nfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\nfloat spotAtten = 0.0;\n\nif (cosAngle >= lightDirection.w)\n{\ncosAngle = max(0., pow(cosAngle, lightData.w));\nspotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\n\nfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\nvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = pow(specComp, vSpecularColor.a);\n\nresult[0] = ndl * spotAtten * diffuseColor.rgb;\nresult[1] = specComp * specularColor * spotAtten;\nresult[2] = vec3(0.);\n\nreturn result;\n}\n\nresult[0] = vec3(0.);\nresult[1] = vec3(0.);\nresult[2] = vec3(0.);\n\nreturn result;\n}\n\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\nmat3 result;\n\nfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\nvec3 angleW = normalize(viewDirectionW + lightData.xyz);\nfloat specComp = max(0., dot(vNormal, angleW));\nspecComp = pow(specComp, vSpecularColor.a);\n\nresult[0] = mix(groundColor, diffuseColor.rgb, ndl);\nresult[1] = specComp * specularColor;\nresult[2] = vec3(0.);\n\nreturn result;\n}\n\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance > 0.0)\ndiscard;\n#endif\n\nvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\nvec4 baseColor = vec4(1., 1., 1., 1.);\nvec3 diffuseColor = vDiffuseColor.rgb;\n\n#ifdef VERTEXCOLOR\nbaseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\nbaseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\nif (baseColor.a < 0.4)\ndiscard;\n#endif\n\nbaseColor.rgb *= vDiffuseInfos.y;\n#endif\n\nvec3 normalW = normalize(vNormalW);\n\nvec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\nbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\nvec3 diffuseBase = vec3(0., 0., 0.);\nvec3 specularBase = vec3(0., 0., 0.);\nfloat shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\nmat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef HEMILIGHT0\nmat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\nmat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\nshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\n#else\nshadow = computeShadow(vPositionFromLight0, shadowSampler0);\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info[0] * shadow;\nspecularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef HEMILIGHT1\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\ninfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\nshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\n#else\nshadow = computeShadow(vPositionFromLight1, shadowSampler1);\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info[0] * shadow;\nspecularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef HEMILIGHT2\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\ninfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\nshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\n#else\nshadow = computeShadow(vPositionFromLight2, shadowSampler2);\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info[0] * shadow;\nspecularBase += info[1] * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\ninfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef HEMILIGHT3\ninfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\ninfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\nshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\n#else\nshadow = computeShadow(vPositionFromLight3, shadowSampler3);\n#endif\n#else\nshadow = 1.;\n#endif\ndiffuseBase += info[0] * shadow;\nspecularBase += info[1] * shadow;\n#endif\n\nvec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\nif (vReflectionInfos.z != 0.0)\n{\nreflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\n}\nelse\n{\nvec2 coords = vReflectionUVW.xy;\n\nif (vReflectionInfos.x == MAP_PROJECTION)\n{\ncoords /= vReflectionUVW.z;\n}\n\ncoords.y = 1.0 - coords.y;\n\nreflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\n}\n\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\nreflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\nfloat alpha = vDiffuseColor.a;\n\n#ifdef OPACITY\nvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n#ifdef OPACITYRGB\nopacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\nalpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\nalpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n#endif\n\n#ifdef VERTEXALPHA\nalpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\nalpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\nvec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\nemissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\nvec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\nspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\ndiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\nvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\nvec3 finalSpecular = specularBase * specularColor;\n\nvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\nfloat fog = CalcFogFactor();\ncolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\ngl_FragColor = color;\n}",
  14681. 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\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\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\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{\nif (mode == MAP_SPHERICAL)\n{\nvec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\nreturn vec3(reflectionMatrix * vec4(coords, 1.0));\n}\nelse if (mode == MAP_PLANAR)\n{\nvec3 viewDir = worldPos.xyz - vEyePosition;\nvec3 coords = normalize(reflect(viewDir, worldNormal));\n\nreturn vec3(reflectionMatrix * vec4(coords, 1));\n}\nelse if (mode == MAP_CUBIC)\n{\nvec3 viewDir = worldPos.xyz - vEyePosition;\nvec3 coords = reflect(viewDir, worldNormal);\n\nreturn vec3(reflectionMatrix * vec4(coords, 0));\n}\nelse if (mode == MAP_PROJECTION)\n{\nreturn vec3(reflectionMatrix * (view * worldPos));\n}\nelse if (mode == MAP_SKYBOX)\n{\nreturn position;\n}\n\nreturn vec3(0, 0, 0);\n}\n#endif\n\nvoid main(void) {\nmat4 finalWorld;\n\n#ifdef BONES\nmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\nmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\nmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n\n#ifdef BONES4\nmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\nfinalWorld = world * (m0 + m1 + m2 + m3);\n#else\nfinalWorld = world * (m0 + m1 + m2);\n#endif\n\n#else\nfinalWorld = world;\n#endif\n\ngl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n\nvec4 worldPos = finalWorld * vec4(position, 1.0);\nvPositionW = vec3(worldPos);\nvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n\n#ifndef UV1\nvec2 uv = vec2(0., 0.);\n#endif\n#ifndef UV2\nvec2 uv2 = vec2(0., 0.);\n#endif\n\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef REFLECTION\nvReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\n#endif\n\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef SPECULAR\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\n}\nelse\n{\nvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\n}\n#endif\n\n#ifdef CLIPPLANE\nfClipDistance = dot(worldPos, vClipPlane);\n#endif\n\n#ifdef FOG\nfFogDistance = (view * worldPos).z;\n#endif\n\n#ifdef SHADOWS\n#ifdef LIGHT0\nvPositionFromLight0 = lightMatrix0 * worldPos;\n#endif\n#ifdef LIGHT1\nvPositionFromLight1 = lightMatrix1 * worldPos;\n#endif\n#ifdef LIGHT2\nvPositionFromLight2 = lightMatrix2 * worldPos;\n#endif\n#ifdef LIGHT3\nvPositionFromLight3 = lightMatrix3 * worldPos;\n#endif\n#endif\n\n#ifdef VERTEXCOLOR\nvColor = color;\n#endif\n}",
  14682. lensFlarePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\n\nvoid main(void) {\nvec4 baseColor = texture2D(textureSampler, vUV);\n\ngl_FragColor = baseColor * color;\n}",
  14683. lensFlareVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) {\n\nvUV = position * madd + madd;\ngl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\n}",
  14684. lensHighlightsPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler; // original color\n\nuniform float gain;\nuniform float threshold;\nuniform bool pentagon;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight = color;\nfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\nfloat lum_threshold;\nif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\nelse { lum_threshold = 0.5 + 0.44 * threshold; }\n\nluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\n\nhighlight *= luminance * gain;\nhighlight.a = 1.0;\n\nreturn highlight;\n}\n\nvoid main(void)\n{\nvec4 original = texture2D(textureSampler, vUV);\n\nif (gain == -1.0) {\ngl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\nreturn;\n}\n\nfloat w = 2.0 / screen_width;\nfloat h = 2.0 / screen_height;\n\nfloat weight = 1.0;\n\nvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\n\nif (pentagon) {\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\n}\nelse {\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\nblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\n}\n\nblurred /= 39.0;\n\ngl_FragColor = blurred;\n\n}",
  14685. 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) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn 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{\nfloat val = 0.0;\nfloat freq = 1.0;\nfor (int i = 0; i < 4; i++)\n{\nval += abs(noise(P*freq) / freq);\nfreq *= 2.07;\n}\nreturn val;\n}\n\nfloat round(float number){\nreturn sign(number)*floor(abs(number) + 0.5);\n}\n\nvec3 marble_color(float x)\n{\nvec3 col;\nx = 0.5*(x + 1.);\nx = sqrt(x);\nx = sqrt(x);\nx = sqrt(x);\ncol = vec3(.2 + .75*x);\ncol.b *= 0.95;\nreturn col;\n}\n\nvoid main()\n{\nfloat brickW = 1.0 / numberOfTilesWidth;\nfloat brickH = 1.0 / numberOfTilesHeight;\nfloat jointWPercentage = 0.01;\nfloat jointHPercentage = 0.01;\nvec3 color = brickColor;\nfloat yi = vUV.y / brickH;\nfloat nyi = round(yi);\nfloat xi = vUV.x / brickW;\n\nif (mod(floor(yi), 2.0) == 0.0){\nxi = xi - 0.5;\n}\n\nfloat nxi = round(xi);\nvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\n\nif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\ncolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\n}\nelse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\ncolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\n}\nelse {\nfloat t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\nt += amplitude * turbulence(brickvUV.xy);\nt = sin(t);\ncolor = marble_color(t);\n}\n\ngl_FragColor = vec4(color, 0.0);\n}",
  14686. oculusDistortionCorrectionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\n\nvec2 HmdWarp(vec2 in01) {\n\nvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\nfloat rSq = theta.x * theta.x + theta.y * theta.y;\nvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\nreturn LensCenter + Scale * rvector;\n}\n\nvoid main(void)\n{\nvec2 tc = HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\nelse{\ngl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\n}\n}",
  14687. 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\nif (texture2D(diffuseSampler, vUV).a < 0.4)\ndiscard;\n#endif\n\ngl_FragColor = color;\n}",
  14688. outlineVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec3 position;\nattribute vec3 normal;\n\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\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\nmat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\nmat4 finalWorld = world;\n#endif\n\nvec3 offsetPosition = position + normal * offset;\n\n#ifdef BONES\nmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\nmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\nmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\nmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\nfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\ngl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#else\ngl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\nvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\nvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  14689. particlesPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\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\nif (fClipDistance > 0.0)\ndiscard;\n#endif\nvec4 baseColor = texture2D(diffuseSampler, vUV);\n\ngl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\n}",
  14690. particlesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\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) {\nvec3 viewPos = (view * vec4(position, 1.0)).xyz;\nvec3 cornerPos;\nfloat size = options.y;\nfloat angle = options.x;\nvec2 offset = options.zw;\n\ncornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\n\nvec3 rotatedCorner;\nrotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\nrotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\nrotatedCorner.z = 0.;\n\nviewPos += rotatedCorner;\ngl_Position = projection * vec4(viewPos, 1.0);\n\nvColor = color;\nvUV = offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos = invView * vec4(viewPos, 1.0);\nfClipDistance = dot(worldPos, vClipPlane);\n#endif\n}",
  14691. passPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nvoid main(void)\n{\ngl_FragColor = texture2D(textureSampler, vUV);\n}",
  14692. postprocessVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec2 position;\n\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) {\n\nvUV = position * madd + madd;\ngl_Position = vec4(position, 0.0, 1.0);\n}",
  14693. proceduralVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\n\nconst vec2 madd = vec2(0.5, 0.5);\n\nvoid main(void) {\nvPosition = position;\nvUV = position * madd + madd;\ngl_Position = vec4(position, 0.0, 1.0);\n}",
  14694. refractionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\n\nvoid main() {\nfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\n\nvec2 uv = vUV - vec2(0.5);\nvec2 offset = uv * depth * ref;\nvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\n\ngl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\n}",
  14695. roadPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvarying vec2 vUV;\nuniform vec3 roadColor;\n\nfloat rand(vec2 n) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn 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) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nvoid main(void) {\nfloat ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\nvec3 color = roadColor * ratioy;\ngl_FragColor = vec4(color, 1.0);\n}",
  14696. shadowMapPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvec4 pack(float depth)\n{\nconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\nconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\n\nvec4 res = fract(depth * bit_shift);\nres -= res.xxyz * bit_mask;\n\nreturn res;\n}\n\nvec2 packHalf(float depth)\n{\nconst vec2 bitOffset = vec2(1.0 / 255., 0.);\nvec2 color = vec2(depth, fract(depth * 255.));\n\nreturn color - (color.yy * bitOffset);\n}\n\nvarying vec4 vPosition;\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler, vUV).a < 0.4)\ndiscard;\n#endif\nfloat depth = vPosition.z / vPosition.w;\ndepth = depth * 0.5 + 0.5;\n\n#ifdef VSM\nfloat moment1 = depth;\nfloat moment2 = moment1 * moment1;\n\ngl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\n#else\ngl_FragColor = pack(depth);\n#endif\n}",
  14697. shadowMapVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\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\nvarying vec4 vPosition;\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\nmat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\nmat4 finalWorld = world;\n#endif\n\n#ifdef BONES\nmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\nmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\nmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\nmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\nfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\n#endif\n\nvPosition = viewProjection * finalWorld * vec4(position, 1.0);\ngl_Position = vPosition;\n\n#ifdef ALPHATEST\n#ifdef UV1\nvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\nvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  14698. spritesPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform bool alphaTest;\n\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\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{\nfloat fogCoeff = 1.0;\nfloat fogStart = vFogInfos.y;\nfloat fogEnd = vFogInfos.z;\nfloat fogDensity = vFogInfos.w;\n\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n}\n\nreturn min(1., max(0., fogCoeff));\n}\n#endif\n\n\nvoid main(void) {\nvec4 baseColor = texture2D(diffuseSampler, vUV);\n\nif (alphaTest)\n{\nif (baseColor.a < 0.95)\ndiscard;\n}\n\nbaseColor *= vColor;\n\n#ifdef FOG\nfloat fog = CalcFogFactor();\nbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\n#endif\n\ngl_FragColor = baseColor;\n}",
  14699. spritesVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n\n#ifdef FOG\nvarying float fFogDistance;\n#endif\n\nvoid main(void) {\nvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz;\nvec2 cornerPos;\n\nfloat angle = position.w;\nvec2 size = vec2(options.x, options.y);\nvec2 offset = options.zw;\nvec2 uvScale = textureInfos.xy;\n\ncornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\n\nvec3 rotatedCorner;\nrotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\nrotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\nrotatedCorner.z = 0.;\n\nviewPos += rotatedCorner;\ngl_Position = projection * vec4(viewPos, 1.0);\n\nvColor = color;\n\nvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\n\nvUV = (uvOffset + cellInfo.zw) * uvScale;\n\n#ifdef FOG\nfFogDistance = viewPos.z;\n#endif\n}",
  14700. 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\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\n\nvarying vec2 vUV;\n\nconst vec2 offset1 = vec2(0.0, 0.001);\nconst vec2 offset2 = vec2(0.001, 0.0);\n\nvec3 normalFromDepth(const float depth, const vec2 coords) {\nfloat depth1 = texture2D(textureSampler, coords + offset1).r;\nfloat depth2 = texture2D(textureSampler, coords + offset2).r;\n\nvec3 p1 = vec3(offset1, depth1 - depth);\nvec3 p2 = vec3(offset2, depth2 - depth);\n\nvec3 normal = cross(p1, p2);\nnormal.z = -normal.z;\n\nreturn normalize(normal);\n}\n\nvoid main(void)\n{\nconst float base = 0.2;\n\nvec3 random = texture2D(randomSampler, vUV * randTextureTiles).rgb;\nfloat depth = texture2D(textureSampler, vUV).r;\nvec3 position = vec3(vUV, depth);\nvec3 normal = normalFromDepth(depth, vUV);\nfloat radiusDepth = radius / depth;\nfloat occlusion = 0.0;\n\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\n\nfor (int i = 0; i < SAMPLES; i++)\n{\nray = radiusDepth * reflect(sampleSphere[i], random);\nhemiRay = position + sign(dot(ray, normal)) * ray;\n\nocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;\ndifference = depth - occlusionDepth;\n\nocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\n}\n\nfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\n\nfloat result = clamp(ao + base, 0.0, 1.0);\ngl_FragColor.r = result;\ngl_FragColor.g = result;\ngl_FragColor.b = result;\ngl_FragColor.a = 1.0;\n}",
  14701. ssaoCombinePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler;\nuniform sampler2D originalColor;\n\nvarying vec2 vUV;\n\nvoid main(void) {\ngl_FragColor = texture2D(originalColor, vUV) * texture2D(textureSampler, vUV);\n}",
  14702. 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) {\nvec2 tc = vUV;\nvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\ndeltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\n\nfloat illuminationDecay = 1.0;\n\nvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\n\nfor(int i=0; i < NUM_SAMPLES; i++) {\ntc -= deltaTexCoord;\nvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\nsample *= illuminationDecay * weight;\ncolor += sample;\nilluminationDecay *= decay;\n}\n\nvec4 realColor = texture2D(textureSampler, vUV);\ngl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\n}",
  14703. volumetricLightScatteringPassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER) || defined(OPACITY)\nvarying vec2 vUV;\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\nuniform sampler2D diffuseSampler;\n#endif\n\n#if defined(OPACITY)\nuniform sampler2D opacitySampler;\nuniform float opacityLevel;\n#endif\n\nvoid main(void)\n{\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\nvec4 diffuseColor = texture2D(diffuseSampler, vUV);\n#endif\n\n#ifdef ALPHATEST\nif (diffuseColor.a < 0.4)\ndiscard;\n#endif\n\n#ifdef OPACITY\nvec4 opacityColor = texture2D(opacitySampler, vUV);\nfloat alpha = 1.0;\n\n#ifdef OPACITYRGB\nopacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\nalpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\n#else\nalpha *= opacityColor.a * opacityLevel;\n#endif\n\n#if defined(BASIC_RENDER)\ngl_FragColor = vec4(diffuseColor.rgb, alpha);\n#else\ngl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\n#endif\n\ngl_FragColor.a = alpha;\n#else\n#ifndef BASIC_RENDER\ngl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n#else\ngl_FragColor = diffuseColor;\n#endif\n#endif\n\n}",
  14704. 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) {\nreturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\n}\n\nfloat noise(vec2 n) {\nconst vec2 d = vec2(0.0, 1.0);\nvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\nreturn 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) {\nfloat total = 0.0, amplitude = 1.0;\nfor (int i = 0; i < 4; i++) {\ntotal += noise(n) * amplitude;\nn += n;\namplitude *= 0.5;\n}\nreturn total;\n}\n\nvoid main(void) {\nfloat ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\nvec3 wood = woodColor * ratioy;\ngl_FragColor = vec4(wood, 1.0);\n}",
  14705. };
  14706. return Effect;
  14707. })();
  14708. BABYLON.Effect = Effect;
  14709. })(BABYLON || (BABYLON = {}));
  14710. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  14711. (function (BABYLON) {
  14712. var Material = (function () {
  14713. function Material(name, scene, doNotAdd) {
  14714. this.name = name;
  14715. this.checkReadyOnEveryCall = true;
  14716. this.checkReadyOnlyOnce = false;
  14717. this.state = "";
  14718. this.alpha = 1.0;
  14719. this.backFaceCulling = true;
  14720. this._wasPreviouslyReady = false;
  14721. this._fillMode = Material.TriangleFillMode;
  14722. this.pointSize = 1.0;
  14723. this.zOffset = 0;
  14724. this.id = name;
  14725. this._scene = scene;
  14726. if (!doNotAdd) {
  14727. scene.materials.push(this);
  14728. }
  14729. }
  14730. Object.defineProperty(Material, "TriangleFillMode", {
  14731. get: function () {
  14732. return Material._TriangleFillMode;
  14733. },
  14734. enumerable: true,
  14735. configurable: true
  14736. });
  14737. Object.defineProperty(Material, "WireFrameFillMode", {
  14738. get: function () {
  14739. return Material._WireFrameFillMode;
  14740. },
  14741. enumerable: true,
  14742. configurable: true
  14743. });
  14744. Object.defineProperty(Material, "PointFillMode", {
  14745. get: function () {
  14746. return Material._PointFillMode;
  14747. },
  14748. enumerable: true,
  14749. configurable: true
  14750. });
  14751. Object.defineProperty(Material.prototype, "wireframe", {
  14752. get: function () {
  14753. return this._fillMode === Material.WireFrameFillMode;
  14754. },
  14755. set: function (value) {
  14756. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  14757. },
  14758. enumerable: true,
  14759. configurable: true
  14760. });
  14761. Object.defineProperty(Material.prototype, "pointsCloud", {
  14762. get: function () {
  14763. return this._fillMode === Material.PointFillMode;
  14764. },
  14765. set: function (value) {
  14766. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  14767. },
  14768. enumerable: true,
  14769. configurable: true
  14770. });
  14771. Object.defineProperty(Material.prototype, "fillMode", {
  14772. get: function () {
  14773. return this._fillMode;
  14774. },
  14775. set: function (value) {
  14776. this._fillMode = value;
  14777. },
  14778. enumerable: true,
  14779. configurable: true
  14780. });
  14781. Material.prototype.isReady = function (mesh, useInstances) {
  14782. return true;
  14783. };
  14784. Material.prototype.getEffect = function () {
  14785. return this._effect;
  14786. };
  14787. Material.prototype.getScene = function () {
  14788. return this._scene;
  14789. };
  14790. Material.prototype.needAlphaBlending = function () {
  14791. return (this.alpha < 1.0);
  14792. };
  14793. Material.prototype.needAlphaTesting = function () {
  14794. return false;
  14795. };
  14796. Material.prototype.getAlphaTestTexture = function () {
  14797. return null;
  14798. };
  14799. Material.prototype.trackCreation = function (onCompiled, onError) {
  14800. };
  14801. Material.prototype._preBind = function () {
  14802. var engine = this._scene.getEngine();
  14803. engine.enableEffect(this._effect);
  14804. engine.setState(this.backFaceCulling, this.zOffset);
  14805. };
  14806. Material.prototype.bind = function (world, mesh) {
  14807. this._scene._cachedMaterial = this;
  14808. if (this.onBind) {
  14809. this.onBind(this, mesh);
  14810. }
  14811. };
  14812. Material.prototype.bindOnlyWorldMatrix = function (world) {
  14813. };
  14814. Material.prototype.unbind = function () {
  14815. };
  14816. Material.prototype.dispose = function (forceDisposeEffect) {
  14817. // Remove from scene
  14818. var index = this._scene.materials.indexOf(this);
  14819. this._scene.materials.splice(index, 1);
  14820. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  14821. if (forceDisposeEffect && this._effect) {
  14822. this._scene.getEngine()._releaseEffect(this._effect);
  14823. this._effect = null;
  14824. }
  14825. // Callback
  14826. if (this.onDispose) {
  14827. this.onDispose();
  14828. }
  14829. };
  14830. Material._TriangleFillMode = 0;
  14831. Material._WireFrameFillMode = 1;
  14832. Material._PointFillMode = 2;
  14833. return Material;
  14834. })();
  14835. BABYLON.Material = Material;
  14836. })(BABYLON || (BABYLON = {}));
  14837. //# sourceMappingURL=babylon.material.js.map
  14838. var BABYLON;
  14839. (function (BABYLON) {
  14840. var maxSimultaneousLights = 4;
  14841. var FresnelParameters = (function () {
  14842. function FresnelParameters() {
  14843. this.isEnabled = true;
  14844. this.leftColor = BABYLON.Color3.White();
  14845. this.rightColor = BABYLON.Color3.Black();
  14846. this.bias = 0;
  14847. this.power = 1;
  14848. }
  14849. return FresnelParameters;
  14850. })();
  14851. BABYLON.FresnelParameters = FresnelParameters;
  14852. var StandardMaterial = (function (_super) {
  14853. __extends(StandardMaterial, _super);
  14854. function StandardMaterial(name, scene) {
  14855. var _this = this;
  14856. _super.call(this, name, scene);
  14857. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14858. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  14859. this.specularColor = new BABYLON.Color3(1, 1, 1);
  14860. this.specularPower = 64;
  14861. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  14862. this.useAlphaFromDiffuseTexture = false;
  14863. this.useSpecularOverAlpha = true;
  14864. this.fogEnabled = true;
  14865. this._cachedDefines = null;
  14866. this._renderTargets = new BABYLON.SmartArray(16);
  14867. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  14868. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  14869. this._scaledDiffuse = new BABYLON.Color3();
  14870. this._scaledSpecular = new BABYLON.Color3();
  14871. this.getRenderTargetTextures = function () {
  14872. _this._renderTargets.reset();
  14873. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  14874. _this._renderTargets.push(_this.reflectionTexture);
  14875. }
  14876. return _this._renderTargets;
  14877. };
  14878. }
  14879. StandardMaterial.prototype.needAlphaBlending = function () {
  14880. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  14881. };
  14882. StandardMaterial.prototype.needAlphaTesting = function () {
  14883. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  14884. };
  14885. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  14886. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  14887. };
  14888. StandardMaterial.prototype.getAlphaTestTexture = function () {
  14889. return this.diffuseTexture;
  14890. };
  14891. // Methods
  14892. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  14893. if (this.checkReadyOnlyOnce) {
  14894. if (this._wasPreviouslyReady) {
  14895. }
  14896. }
  14897. var scene = this.getScene();
  14898. if (!this.checkReadyOnEveryCall) {
  14899. if (this._renderId === scene.getRenderId()) {
  14900. }
  14901. }
  14902. var engine = scene.getEngine();
  14903. var defines = [];
  14904. var fallbacks = new BABYLON.EffectFallbacks();
  14905. var needNormals = false;
  14906. var needUVs = false;
  14907. // Textures
  14908. if (scene.texturesEnabled) {
  14909. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14910. if (!this.diffuseTexture.isReady()) {
  14911. return false;
  14912. }
  14913. else {
  14914. needUVs = true;
  14915. defines.push("#define DIFFUSE");
  14916. }
  14917. }
  14918. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14919. if (!this.ambientTexture.isReady()) {
  14920. return false;
  14921. }
  14922. else {
  14923. needUVs = true;
  14924. defines.push("#define AMBIENT");
  14925. }
  14926. }
  14927. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14928. if (!this.opacityTexture.isReady()) {
  14929. return false;
  14930. }
  14931. else {
  14932. needUVs = true;
  14933. defines.push("#define OPACITY");
  14934. if (this.opacityTexture.getAlphaFromRGB) {
  14935. defines.push("#define OPACITYRGB");
  14936. }
  14937. }
  14938. }
  14939. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14940. if (!this.reflectionTexture.isReady()) {
  14941. return false;
  14942. }
  14943. else {
  14944. needNormals = true;
  14945. needUVs = true;
  14946. defines.push("#define REFLECTION");
  14947. fallbacks.addFallback(0, "REFLECTION");
  14948. }
  14949. }
  14950. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14951. if (!this.emissiveTexture.isReady()) {
  14952. return false;
  14953. }
  14954. else {
  14955. needUVs = true;
  14956. defines.push("#define EMISSIVE");
  14957. }
  14958. }
  14959. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14960. if (!this.specularTexture.isReady()) {
  14961. return false;
  14962. }
  14963. else {
  14964. needUVs = true;
  14965. defines.push("#define SPECULAR");
  14966. fallbacks.addFallback(0, "SPECULAR");
  14967. }
  14968. }
  14969. }
  14970. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  14971. if (!this.bumpTexture.isReady()) {
  14972. return false;
  14973. }
  14974. else {
  14975. needUVs = true;
  14976. defines.push("#define BUMP");
  14977. fallbacks.addFallback(0, "BUMP");
  14978. }
  14979. }
  14980. // Effect
  14981. if (this.useSpecularOverAlpha) {
  14982. defines.push("#define SPECULAROVERALPHA");
  14983. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  14984. }
  14985. if (scene.clipPlane) {
  14986. defines.push("#define CLIPPLANE");
  14987. }
  14988. if (engine.getAlphaTesting()) {
  14989. defines.push("#define ALPHATEST");
  14990. }
  14991. if (this._shouldUseAlphaFromDiffuseTexture()) {
  14992. defines.push("#define ALPHAFROMDIFFUSE");
  14993. }
  14994. // Point size
  14995. if (this.pointsCloud || scene.forcePointsCloud) {
  14996. defines.push("#define POINTSIZE");
  14997. }
  14998. // Fog
  14999. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15000. defines.push("#define FOG");
  15001. fallbacks.addFallback(1, "FOG");
  15002. }
  15003. var shadowsActivated = false;
  15004. var lightIndex = 0;
  15005. if (scene.lightsEnabled) {
  15006. for (var index = 0; index < scene.lights.length; index++) {
  15007. var light = scene.lights[index];
  15008. if (!light.isEnabled()) {
  15009. continue;
  15010. }
  15011. // Excluded check
  15012. if (light._excludedMeshesIds.length > 0) {
  15013. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  15014. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  15015. if (excludedMesh) {
  15016. light.excludedMeshes.push(excludedMesh);
  15017. }
  15018. }
  15019. light._excludedMeshesIds = [];
  15020. }
  15021. // Included check
  15022. if (light._includedOnlyMeshesIds.length > 0) {
  15023. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  15024. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  15025. if (includedOnlyMesh) {
  15026. light.includedOnlyMeshes.push(includedOnlyMesh);
  15027. }
  15028. }
  15029. light._includedOnlyMeshesIds = [];
  15030. }
  15031. if (!light.canAffectMesh(mesh)) {
  15032. continue;
  15033. }
  15034. needNormals = true;
  15035. defines.push("#define LIGHT" + lightIndex);
  15036. if (lightIndex > 0) {
  15037. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  15038. }
  15039. var type;
  15040. if (light instanceof BABYLON.SpotLight) {
  15041. type = "#define SPOTLIGHT" + lightIndex;
  15042. }
  15043. else if (light instanceof BABYLON.HemisphericLight) {
  15044. type = "#define HEMILIGHT" + lightIndex;
  15045. }
  15046. else {
  15047. type = "#define POINTDIRLIGHT" + lightIndex;
  15048. }
  15049. defines.push(type);
  15050. if (lightIndex > 0) {
  15051. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  15052. }
  15053. // Shadows
  15054. if (scene.shadowsEnabled) {
  15055. var shadowGenerator = light.getShadowGenerator();
  15056. if (mesh && mesh.receiveShadows && shadowGenerator) {
  15057. defines.push("#define SHADOW" + lightIndex);
  15058. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  15059. if (!shadowsActivated) {
  15060. defines.push("#define SHADOWS");
  15061. shadowsActivated = true;
  15062. }
  15063. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  15064. defines.push("#define SHADOWVSM" + lightIndex);
  15065. if (lightIndex > 0) {
  15066. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  15067. }
  15068. }
  15069. if (shadowGenerator.usePoissonSampling) {
  15070. defines.push("#define SHADOWPCF" + lightIndex);
  15071. if (lightIndex > 0) {
  15072. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  15073. }
  15074. }
  15075. }
  15076. }
  15077. lightIndex++;
  15078. if (lightIndex === maxSimultaneousLights)
  15079. break;
  15080. }
  15081. }
  15082. if (StandardMaterial.FresnelEnabled) {
  15083. // Fresnel
  15084. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  15085. var fresnelRank = 1;
  15086. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  15087. defines.push("#define DIFFUSEFRESNEL");
  15088. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  15089. fresnelRank++;
  15090. }
  15091. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  15092. defines.push("#define OPACITYFRESNEL");
  15093. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  15094. fresnelRank++;
  15095. }
  15096. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  15097. defines.push("#define REFLECTIONFRESNEL");
  15098. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  15099. fresnelRank++;
  15100. }
  15101. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  15102. defines.push("#define EMISSIVEFRESNEL");
  15103. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  15104. fresnelRank++;
  15105. }
  15106. needNormals = true;
  15107. defines.push("#define FRESNEL");
  15108. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  15109. }
  15110. }
  15111. // Attribs
  15112. var attribs = [BABYLON.VertexBuffer.PositionKind];
  15113. if (mesh) {
  15114. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15115. attribs.push(BABYLON.VertexBuffer.NormalKind);
  15116. defines.push("#define NORMAL");
  15117. }
  15118. if (needUVs) {
  15119. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15120. attribs.push(BABYLON.VertexBuffer.UVKind);
  15121. defines.push("#define UV1");
  15122. }
  15123. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  15124. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  15125. defines.push("#define UV2");
  15126. }
  15127. }
  15128. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  15129. attribs.push(BABYLON.VertexBuffer.ColorKind);
  15130. defines.push("#define VERTEXCOLOR");
  15131. if (mesh.hasVertexAlpha) {
  15132. defines.push("#define VERTEXALPHA");
  15133. }
  15134. }
  15135. if (mesh.useBones) {
  15136. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15137. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15138. defines.push("#define BONES");
  15139. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  15140. defines.push("#define BONES4");
  15141. fallbacks.addFallback(0, "BONES4");
  15142. }
  15143. // Instances
  15144. if (useInstances) {
  15145. defines.push("#define INSTANCES");
  15146. attribs.push("world0");
  15147. attribs.push("world1");
  15148. attribs.push("world2");
  15149. attribs.push("world3");
  15150. }
  15151. }
  15152. // Get correct effect
  15153. var join = defines.join("\n");
  15154. if (this._cachedDefines !== join) {
  15155. this._cachedDefines = join;
  15156. scene.resetCachedMaterial();
  15157. // Legacy browser patch
  15158. var shaderName = "default";
  15159. if (!scene.getEngine().getCaps().standardDerivatives) {
  15160. shaderName = "legacydefault";
  15161. }
  15162. 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);
  15163. }
  15164. if (!this._effect.isReady()) {
  15165. return false;
  15166. }
  15167. this._renderId = scene.getRenderId();
  15168. this._wasPreviouslyReady = true;
  15169. return true;
  15170. };
  15171. StandardMaterial.prototype.unbind = function () {
  15172. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  15173. this._effect.setTexture("reflection2DSampler", null);
  15174. }
  15175. };
  15176. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  15177. this._effect.setMatrix("world", world);
  15178. };
  15179. StandardMaterial.prototype.bind = function (world, mesh) {
  15180. var scene = this.getScene();
  15181. // Matrices
  15182. this.bindOnlyWorldMatrix(world);
  15183. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  15184. // Bones
  15185. if (mesh && mesh.useBones) {
  15186. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  15187. }
  15188. if (scene.getCachedMaterial() !== this) {
  15189. if (StandardMaterial.FresnelEnabled) {
  15190. // Fresnel
  15191. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  15192. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  15193. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  15194. }
  15195. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  15196. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  15197. }
  15198. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  15199. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  15200. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  15201. }
  15202. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  15203. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  15204. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  15205. }
  15206. }
  15207. // Textures
  15208. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  15209. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  15210. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  15211. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  15212. }
  15213. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  15214. this._effect.setTexture("ambientSampler", this.ambientTexture);
  15215. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  15216. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  15217. }
  15218. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  15219. this._effect.setTexture("opacitySampler", this.opacityTexture);
  15220. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  15221. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  15222. }
  15223. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  15224. if (this.reflectionTexture.isCube) {
  15225. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  15226. }
  15227. else {
  15228. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  15229. }
  15230. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  15231. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  15232. }
  15233. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  15234. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  15235. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  15236. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  15237. }
  15238. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  15239. this._effect.setTexture("specularSampler", this.specularTexture);
  15240. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  15241. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  15242. }
  15243. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  15244. this._effect.setTexture("bumpSampler", this.bumpTexture);
  15245. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  15246. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  15247. }
  15248. // Clip plane
  15249. if (scene.clipPlane) {
  15250. var clipPlane = scene.clipPlane;
  15251. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  15252. }
  15253. // Point size
  15254. if (this.pointsCloud) {
  15255. this._effect.setFloat("pointSize", this.pointSize);
  15256. }
  15257. // Colors
  15258. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  15259. // Scaling down color according to emissive
  15260. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  15261. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  15262. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  15263. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  15264. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  15265. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  15266. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  15267. }
  15268. // Scaling down color according to emissive
  15269. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  15270. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  15271. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  15272. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  15273. if (scene.lightsEnabled) {
  15274. var lightIndex = 0;
  15275. for (var index = 0; index < scene.lights.length; index++) {
  15276. var light = scene.lights[index];
  15277. if (!light.isEnabled()) {
  15278. continue;
  15279. }
  15280. if (!light.canAffectMesh(mesh)) {
  15281. continue;
  15282. }
  15283. if (light instanceof BABYLON.PointLight) {
  15284. // Point Light
  15285. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  15286. }
  15287. else if (light instanceof BABYLON.DirectionalLight) {
  15288. // Directional Light
  15289. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  15290. }
  15291. else if (light instanceof BABYLON.SpotLight) {
  15292. // Spot Light
  15293. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  15294. }
  15295. else if (light instanceof BABYLON.HemisphericLight) {
  15296. // Hemispheric Light
  15297. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  15298. }
  15299. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  15300. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  15301. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  15302. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  15303. // Shadows
  15304. if (scene.shadowsEnabled) {
  15305. var shadowGenerator = light.getShadowGenerator();
  15306. if (mesh.receiveShadows && shadowGenerator) {
  15307. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  15308. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  15309. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  15310. }
  15311. }
  15312. lightIndex++;
  15313. if (lightIndex === maxSimultaneousLights)
  15314. break;
  15315. }
  15316. }
  15317. // View
  15318. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  15319. this._effect.setMatrix("view", scene.getViewMatrix());
  15320. }
  15321. // Fog
  15322. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  15323. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  15324. this._effect.setColor3("vFogColor", scene.fogColor);
  15325. }
  15326. _super.prototype.bind.call(this, world, mesh);
  15327. };
  15328. StandardMaterial.prototype.getAnimatables = function () {
  15329. var results = [];
  15330. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  15331. results.push(this.diffuseTexture);
  15332. }
  15333. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  15334. results.push(this.ambientTexture);
  15335. }
  15336. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  15337. results.push(this.opacityTexture);
  15338. }
  15339. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  15340. results.push(this.reflectionTexture);
  15341. }
  15342. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  15343. results.push(this.emissiveTexture);
  15344. }
  15345. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  15346. results.push(this.specularTexture);
  15347. }
  15348. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  15349. results.push(this.bumpTexture);
  15350. }
  15351. return results;
  15352. };
  15353. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  15354. if (this.diffuseTexture) {
  15355. this.diffuseTexture.dispose();
  15356. }
  15357. if (this.ambientTexture) {
  15358. this.ambientTexture.dispose();
  15359. }
  15360. if (this.opacityTexture) {
  15361. this.opacityTexture.dispose();
  15362. }
  15363. if (this.reflectionTexture) {
  15364. this.reflectionTexture.dispose();
  15365. }
  15366. if (this.emissiveTexture) {
  15367. this.emissiveTexture.dispose();
  15368. }
  15369. if (this.specularTexture) {
  15370. this.specularTexture.dispose();
  15371. }
  15372. if (this.bumpTexture) {
  15373. this.bumpTexture.dispose();
  15374. }
  15375. _super.prototype.dispose.call(this, forceDisposeEffect);
  15376. };
  15377. StandardMaterial.prototype.clone = function (name) {
  15378. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  15379. // Base material
  15380. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  15381. newStandardMaterial.alpha = this.alpha;
  15382. newStandardMaterial.fillMode = this.fillMode;
  15383. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  15384. // Standard material
  15385. if (this.diffuseTexture && this.diffuseTexture.clone) {
  15386. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  15387. }
  15388. if (this.ambientTexture && this.ambientTexture.clone) {
  15389. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  15390. }
  15391. if (this.opacityTexture && this.opacityTexture.clone) {
  15392. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  15393. }
  15394. if (this.reflectionTexture && this.reflectionTexture.clone) {
  15395. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  15396. }
  15397. if (this.emissiveTexture && this.emissiveTexture.clone) {
  15398. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  15399. }
  15400. if (this.specularTexture && this.specularTexture.clone) {
  15401. newStandardMaterial.specularTexture = this.specularTexture.clone();
  15402. }
  15403. if (this.bumpTexture && this.bumpTexture.clone) {
  15404. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  15405. }
  15406. newStandardMaterial.ambientColor = this.ambientColor.clone();
  15407. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  15408. newStandardMaterial.specularColor = this.specularColor.clone();
  15409. newStandardMaterial.specularPower = this.specularPower;
  15410. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  15411. return newStandardMaterial;
  15412. };
  15413. // Statics
  15414. // Flags used to enable or disable a type of texture for all Standard Materials
  15415. StandardMaterial.DiffuseTextureEnabled = true;
  15416. StandardMaterial.AmbientTextureEnabled = true;
  15417. StandardMaterial.OpacityTextureEnabled = true;
  15418. StandardMaterial.ReflectionTextureEnabled = true;
  15419. StandardMaterial.EmissiveTextureEnabled = true;
  15420. StandardMaterial.SpecularTextureEnabled = true;
  15421. StandardMaterial.BumpTextureEnabled = true;
  15422. StandardMaterial.FresnelEnabled = true;
  15423. return StandardMaterial;
  15424. })(BABYLON.Material);
  15425. BABYLON.StandardMaterial = StandardMaterial;
  15426. })(BABYLON || (BABYLON = {}));
  15427. //# sourceMappingURL=babylon.standardMaterial.js.map
  15428. var BABYLON;
  15429. (function (BABYLON) {
  15430. var MultiMaterial = (function (_super) {
  15431. __extends(MultiMaterial, _super);
  15432. function MultiMaterial(name, scene) {
  15433. _super.call(this, name, scene, true);
  15434. this.subMaterials = new Array();
  15435. scene.multiMaterials.push(this);
  15436. }
  15437. // Properties
  15438. MultiMaterial.prototype.getSubMaterial = function (index) {
  15439. if (index < 0 || index >= this.subMaterials.length) {
  15440. return this.getScene().defaultMaterial;
  15441. }
  15442. return this.subMaterials[index];
  15443. };
  15444. // Methods
  15445. MultiMaterial.prototype.isReady = function (mesh) {
  15446. for (var index = 0; index < this.subMaterials.length; index++) {
  15447. var subMaterial = this.subMaterials[index];
  15448. if (subMaterial) {
  15449. if (!this.subMaterials[index].isReady(mesh)) {
  15450. return false;
  15451. }
  15452. }
  15453. }
  15454. return true;
  15455. };
  15456. return MultiMaterial;
  15457. })(BABYLON.Material);
  15458. BABYLON.MultiMaterial = MultiMaterial;
  15459. })(BABYLON || (BABYLON = {}));
  15460. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  15461. (function (BABYLON) {
  15462. var Database = (function () {
  15463. function Database(urlToScene, callbackManifestChecked) {
  15464. // Handling various flavors of prefixed version of IndexedDB
  15465. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  15466. this.callbackManifestChecked = callbackManifestChecked;
  15467. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  15468. this.db = null;
  15469. this.enableSceneOffline = false;
  15470. this.enableTexturesOffline = false;
  15471. this.manifestVersionFound = 0;
  15472. this.mustUpdateRessources = false;
  15473. this.hasReachedQuota = false;
  15474. this.checkManifestFile();
  15475. }
  15476. Database.prototype.checkManifestFile = function () {
  15477. var _this = this;
  15478. function noManifestFile() {
  15479. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  15480. that.enableSceneOffline = false;
  15481. that.enableTexturesOffline = false;
  15482. that.callbackManifestChecked(false);
  15483. }
  15484. var that = this;
  15485. var manifestURL = this.currentSceneUrl + ".manifest";
  15486. var xhr = new XMLHttpRequest();
  15487. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  15488. xhr.open("GET", manifestURLTimeStamped, true);
  15489. xhr.addEventListener("load", function () {
  15490. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  15491. try {
  15492. var manifestFile = JSON.parse(xhr.response);
  15493. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  15494. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  15495. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  15496. _this.manifestVersionFound = manifestFile.version;
  15497. }
  15498. if (_this.callbackManifestChecked) {
  15499. _this.callbackManifestChecked(true);
  15500. }
  15501. }
  15502. catch (ex) {
  15503. noManifestFile();
  15504. }
  15505. }
  15506. else {
  15507. noManifestFile();
  15508. }
  15509. }, false);
  15510. xhr.addEventListener("error", function (event) {
  15511. noManifestFile();
  15512. }, false);
  15513. try {
  15514. xhr.send();
  15515. }
  15516. catch (ex) {
  15517. BABYLON.Tools.Error("Error on XHR send request.");
  15518. that.callbackManifestChecked(false);
  15519. }
  15520. };
  15521. Database.prototype.openAsync = function (successCallback, errorCallback) {
  15522. var _this = this;
  15523. function handleError() {
  15524. that.isSupported = false;
  15525. if (errorCallback)
  15526. errorCallback();
  15527. }
  15528. var that = this;
  15529. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  15530. // Your browser doesn't support IndexedDB
  15531. this.isSupported = false;
  15532. if (errorCallback)
  15533. errorCallback();
  15534. }
  15535. else {
  15536. // If the DB hasn't been opened or created yet
  15537. if (!this.db) {
  15538. this.hasReachedQuota = false;
  15539. this.isSupported = true;
  15540. var request = this.idbFactory.open("babylonjs", 1);
  15541. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  15542. request.onerror = function (event) {
  15543. handleError();
  15544. };
  15545. // executes when a version change transaction cannot complete due to other active transactions
  15546. request.onblocked = function (event) {
  15547. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  15548. handleError();
  15549. };
  15550. // DB has been opened successfully
  15551. request.onsuccess = function (event) {
  15552. _this.db = request.result;
  15553. successCallback();
  15554. };
  15555. // Initialization of the DB. Creating Scenes & Textures stores
  15556. request.onupgradeneeded = function (event) {
  15557. _this.db = (event.target).result;
  15558. try {
  15559. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  15560. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  15561. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  15562. }
  15563. catch (ex) {
  15564. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  15565. handleError();
  15566. }
  15567. };
  15568. }
  15569. else {
  15570. if (successCallback)
  15571. successCallback();
  15572. }
  15573. }
  15574. };
  15575. Database.prototype.loadImageFromDB = function (url, image) {
  15576. var _this = this;
  15577. var completeURL = Database.ReturnFullUrlLocation(url);
  15578. var saveAndLoadImage = function () {
  15579. if (!_this.hasReachedQuota && _this.db !== null) {
  15580. // the texture is not yet in the DB, let's try to save it
  15581. _this._saveImageIntoDBAsync(completeURL, image);
  15582. }
  15583. else {
  15584. image.src = url;
  15585. }
  15586. };
  15587. if (!this.mustUpdateRessources) {
  15588. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  15589. }
  15590. else {
  15591. saveAndLoadImage();
  15592. }
  15593. };
  15594. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  15595. if (this.isSupported && this.db !== null) {
  15596. var texture;
  15597. var transaction = this.db.transaction(["textures"]);
  15598. transaction.onabort = function (event) {
  15599. image.src = url;
  15600. };
  15601. transaction.oncomplete = function (event) {
  15602. var blobTextureURL;
  15603. if (texture) {
  15604. var URL = window.URL || window.webkitURL;
  15605. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  15606. image.onerror = function () {
  15607. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  15608. image.src = url;
  15609. };
  15610. image.src = blobTextureURL;
  15611. }
  15612. else {
  15613. notInDBCallback();
  15614. }
  15615. };
  15616. var getRequest = transaction.objectStore("textures").get(url);
  15617. getRequest.onsuccess = function (event) {
  15618. texture = (event.target).result;
  15619. };
  15620. getRequest.onerror = function (event) {
  15621. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  15622. image.src = url;
  15623. };
  15624. }
  15625. else {
  15626. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15627. image.src = url;
  15628. }
  15629. };
  15630. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  15631. var _this = this;
  15632. if (this.isSupported) {
  15633. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  15634. var generateBlobUrl = function () {
  15635. var blobTextureURL;
  15636. if (blob) {
  15637. var URL = window.URL || window.webkitURL;
  15638. try {
  15639. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  15640. }
  15641. catch (ex) {
  15642. blobTextureURL = URL.createObjectURL(blob);
  15643. }
  15644. }
  15645. image.src = blobTextureURL;
  15646. };
  15647. if (Database.isUASupportingBlobStorage) {
  15648. var xhr = new XMLHttpRequest(), blob;
  15649. xhr.open("GET", url, true);
  15650. xhr.responseType = "blob";
  15651. xhr.addEventListener("load", function () {
  15652. if (xhr.status === 200) {
  15653. // Blob as response (XHR2)
  15654. blob = xhr.response;
  15655. var transaction = _this.db.transaction(["textures"], "readwrite");
  15656. // the transaction could abort because of a QuotaExceededError error
  15657. transaction.onabort = function (event) {
  15658. try {
  15659. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15660. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15661. this.hasReachedQuota = true;
  15662. }
  15663. }
  15664. catch (ex) {
  15665. }
  15666. generateBlobUrl();
  15667. };
  15668. transaction.oncomplete = function (event) {
  15669. generateBlobUrl();
  15670. };
  15671. var newTexture = { textureUrl: url, data: blob };
  15672. try {
  15673. // Put the blob into the dabase
  15674. var addRequest = transaction.objectStore("textures").put(newTexture);
  15675. addRequest.onsuccess = function (event) {
  15676. };
  15677. addRequest.onerror = function (event) {
  15678. generateBlobUrl();
  15679. };
  15680. }
  15681. catch (ex) {
  15682. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  15683. if (ex.code === 25) {
  15684. Database.isUASupportingBlobStorage = false;
  15685. }
  15686. image.src = url;
  15687. }
  15688. }
  15689. else {
  15690. image.src = url;
  15691. }
  15692. }, false);
  15693. xhr.addEventListener("error", function (event) {
  15694. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  15695. image.src = url;
  15696. }, false);
  15697. xhr.send();
  15698. }
  15699. else {
  15700. image.src = url;
  15701. }
  15702. }
  15703. else {
  15704. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15705. image.src = url;
  15706. }
  15707. };
  15708. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  15709. var _this = this;
  15710. var updateVersion = function (event) {
  15711. // the version is not yet in the DB or we need to update it
  15712. _this._saveVersionIntoDBAsync(url, versionLoaded);
  15713. };
  15714. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  15715. };
  15716. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  15717. var _this = this;
  15718. if (this.isSupported) {
  15719. var version;
  15720. try {
  15721. var transaction = this.db.transaction(["versions"]);
  15722. transaction.oncomplete = function (event) {
  15723. if (version) {
  15724. // If the version in the JSON file is > than the version in DB
  15725. if (_this.manifestVersionFound > version.data) {
  15726. _this.mustUpdateRessources = true;
  15727. updateInDBCallback();
  15728. }
  15729. else {
  15730. callback(version.data);
  15731. }
  15732. }
  15733. else {
  15734. _this.mustUpdateRessources = true;
  15735. updateInDBCallback();
  15736. }
  15737. };
  15738. transaction.onabort = function (event) {
  15739. callback(-1);
  15740. };
  15741. var getRequest = transaction.objectStore("versions").get(url);
  15742. getRequest.onsuccess = function (event) {
  15743. version = (event.target).result;
  15744. };
  15745. getRequest.onerror = function (event) {
  15746. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  15747. callback(-1);
  15748. };
  15749. }
  15750. catch (ex) {
  15751. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  15752. callback(-1);
  15753. }
  15754. }
  15755. else {
  15756. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15757. callback(-1);
  15758. }
  15759. };
  15760. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  15761. var _this = this;
  15762. if (this.isSupported && !this.hasReachedQuota) {
  15763. try {
  15764. // Open a transaction to the database
  15765. var transaction = this.db.transaction(["versions"], "readwrite");
  15766. // the transaction could abort because of a QuotaExceededError error
  15767. transaction.onabort = function (event) {
  15768. try {
  15769. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15770. _this.hasReachedQuota = true;
  15771. }
  15772. }
  15773. catch (ex) {
  15774. }
  15775. callback(-1);
  15776. };
  15777. transaction.oncomplete = function (event) {
  15778. callback(_this.manifestVersionFound);
  15779. };
  15780. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  15781. // Put the scene into the database
  15782. var addRequest = transaction.objectStore("versions").put(newVersion);
  15783. addRequest.onsuccess = function (event) {
  15784. };
  15785. addRequest.onerror = function (event) {
  15786. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  15787. };
  15788. }
  15789. catch (ex) {
  15790. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  15791. callback(-1);
  15792. }
  15793. }
  15794. else {
  15795. callback(-1);
  15796. }
  15797. };
  15798. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  15799. var _this = this;
  15800. var completeUrl = Database.ReturnFullUrlLocation(url);
  15801. var saveAndLoadFile = function (event) {
  15802. // the scene is not yet in the DB, let's try to save it
  15803. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  15804. };
  15805. this._checkVersionFromDB(completeUrl, function (version) {
  15806. if (version !== -1) {
  15807. if (!_this.mustUpdateRessources) {
  15808. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  15809. }
  15810. else {
  15811. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  15812. }
  15813. }
  15814. else {
  15815. errorCallback();
  15816. }
  15817. });
  15818. };
  15819. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  15820. if (this.isSupported) {
  15821. var targetStore;
  15822. if (url.indexOf(".babylon") !== -1) {
  15823. targetStore = "scenes";
  15824. }
  15825. else {
  15826. targetStore = "textures";
  15827. }
  15828. var file;
  15829. var transaction = this.db.transaction([targetStore]);
  15830. transaction.oncomplete = function (event) {
  15831. if (file) {
  15832. callback(file.data);
  15833. }
  15834. else {
  15835. notInDBCallback();
  15836. }
  15837. };
  15838. transaction.onabort = function (event) {
  15839. notInDBCallback();
  15840. };
  15841. var getRequest = transaction.objectStore(targetStore).get(url);
  15842. getRequest.onsuccess = function (event) {
  15843. file = (event.target).result;
  15844. };
  15845. getRequest.onerror = function (event) {
  15846. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  15847. notInDBCallback();
  15848. };
  15849. }
  15850. else {
  15851. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15852. callback();
  15853. }
  15854. };
  15855. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  15856. var _this = this;
  15857. if (this.isSupported) {
  15858. var targetStore;
  15859. if (url.indexOf(".babylon") !== -1) {
  15860. targetStore = "scenes";
  15861. }
  15862. else {
  15863. targetStore = "textures";
  15864. }
  15865. // Create XHR
  15866. var xhr = new XMLHttpRequest(), fileData;
  15867. xhr.open("GET", url, true);
  15868. if (useArrayBuffer) {
  15869. xhr.responseType = "arraybuffer";
  15870. }
  15871. xhr.onprogress = progressCallback;
  15872. xhr.addEventListener("load", function () {
  15873. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  15874. // Blob as response (XHR2)
  15875. //fileData = xhr.responseText;
  15876. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  15877. if (!_this.hasReachedQuota) {
  15878. // Open a transaction to the database
  15879. var transaction = _this.db.transaction([targetStore], "readwrite");
  15880. // the transaction could abort because of a QuotaExceededError error
  15881. transaction.onabort = function (event) {
  15882. try {
  15883. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15884. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15885. this.hasReachedQuota = true;
  15886. }
  15887. }
  15888. catch (ex) {
  15889. }
  15890. callback(fileData);
  15891. };
  15892. transaction.oncomplete = function (event) {
  15893. callback(fileData);
  15894. };
  15895. var newFile;
  15896. if (targetStore === "scenes") {
  15897. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  15898. }
  15899. else {
  15900. newFile = { textureUrl: url, data: fileData };
  15901. }
  15902. try {
  15903. // Put the scene into the database
  15904. var addRequest = transaction.objectStore(targetStore).put(newFile);
  15905. addRequest.onsuccess = function (event) {
  15906. };
  15907. addRequest.onerror = function (event) {
  15908. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  15909. };
  15910. }
  15911. catch (ex) {
  15912. callback(fileData);
  15913. }
  15914. }
  15915. else {
  15916. callback(fileData);
  15917. }
  15918. }
  15919. else {
  15920. callback();
  15921. }
  15922. }, false);
  15923. xhr.addEventListener("error", function (event) {
  15924. BABYLON.Tools.Error("error on XHR request.");
  15925. callback();
  15926. }, false);
  15927. xhr.send();
  15928. }
  15929. else {
  15930. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15931. callback();
  15932. }
  15933. };
  15934. Database.isUASupportingBlobStorage = true;
  15935. Database.parseURL = function (url) {
  15936. var a = document.createElement('a');
  15937. a.href = url;
  15938. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  15939. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  15940. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  15941. return absLocation;
  15942. };
  15943. Database.ReturnFullUrlLocation = function (url) {
  15944. if (url.indexOf("http:/") === -1) {
  15945. return (BABYLON.Database.parseURL(window.location.href) + url);
  15946. }
  15947. else {
  15948. return url;
  15949. }
  15950. };
  15951. return Database;
  15952. })();
  15953. BABYLON.Database = Database;
  15954. })(BABYLON || (BABYLON = {}));
  15955. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  15956. (function (BABYLON) {
  15957. var SpriteManager = (function () {
  15958. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  15959. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15960. this.name = name;
  15961. this.cellSize = cellSize;
  15962. this.sprites = new Array();
  15963. this.renderingGroupId = 0;
  15964. this.fogEnabled = true;
  15965. this._vertexDeclaration = [4, 4, 4, 4];
  15966. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  15967. this._capacity = capacity;
  15968. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  15969. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15970. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15971. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  15972. this._scene = scene;
  15973. this._scene.spriteManagers.push(this);
  15974. // VBO
  15975. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15976. var indices = [];
  15977. var index = 0;
  15978. for (var count = 0; count < capacity; count++) {
  15979. indices.push(index);
  15980. indices.push(index + 1);
  15981. indices.push(index + 2);
  15982. indices.push(index);
  15983. indices.push(index + 2);
  15984. indices.push(index + 3);
  15985. index += 4;
  15986. }
  15987. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15988. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15989. // Effects
  15990. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  15991. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  15992. }
  15993. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  15994. var arrayOffset = index * 16;
  15995. if (offsetX === 0)
  15996. offsetX = this._epsilon;
  15997. else if (offsetX === 1)
  15998. offsetX = 1 - this._epsilon;
  15999. if (offsetY === 0)
  16000. offsetY = this._epsilon;
  16001. else if (offsetY === 1)
  16002. offsetY = 1 - this._epsilon;
  16003. this._vertices[arrayOffset] = sprite.position.x;
  16004. this._vertices[arrayOffset + 1] = sprite.position.y;
  16005. this._vertices[arrayOffset + 2] = sprite.position.z;
  16006. this._vertices[arrayOffset + 3] = sprite.angle;
  16007. this._vertices[arrayOffset + 4] = sprite.width;
  16008. this._vertices[arrayOffset + 5] = sprite.height;
  16009. this._vertices[arrayOffset + 6] = offsetX;
  16010. this._vertices[arrayOffset + 7] = offsetY;
  16011. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  16012. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  16013. var offset = (sprite.cellIndex / rowSize) >> 0;
  16014. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  16015. this._vertices[arrayOffset + 11] = offset;
  16016. // Color
  16017. this._vertices[arrayOffset + 12] = sprite.color.r;
  16018. this._vertices[arrayOffset + 13] = sprite.color.g;
  16019. this._vertices[arrayOffset + 14] = sprite.color.b;
  16020. this._vertices[arrayOffset + 15] = sprite.color.a;
  16021. };
  16022. SpriteManager.prototype.render = function () {
  16023. // Check
  16024. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  16025. return;
  16026. var engine = this._scene.getEngine();
  16027. var baseSize = this._spriteTexture.getBaseSize();
  16028. // Sprites
  16029. var deltaTime = engine.getDeltaTime();
  16030. var max = Math.min(this._capacity, this.sprites.length);
  16031. var rowSize = baseSize.width / this.cellSize;
  16032. var offset = 0;
  16033. for (var index = 0; index < max; index++) {
  16034. var sprite = this.sprites[index];
  16035. if (!sprite) {
  16036. continue;
  16037. }
  16038. sprite._animate(deltaTime);
  16039. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  16040. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  16041. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  16042. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  16043. }
  16044. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  16045. // Render
  16046. var effect = this._effectBase;
  16047. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  16048. effect = this._effectFog;
  16049. }
  16050. engine.enableEffect(effect);
  16051. var viewMatrix = this._scene.getViewMatrix();
  16052. effect.setTexture("diffuseSampler", this._spriteTexture);
  16053. effect.setMatrix("view", viewMatrix);
  16054. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  16055. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  16056. // Fog
  16057. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  16058. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  16059. effect.setColor3("vFogColor", this._scene.fogColor);
  16060. }
  16061. // VBOs
  16062. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16063. // Draw order
  16064. effect.setBool("alphaTest", true);
  16065. engine.setColorWrite(false);
  16066. engine.draw(true, 0, max * 6);
  16067. engine.setColorWrite(true);
  16068. effect.setBool("alphaTest", false);
  16069. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16070. engine.draw(true, 0, max * 6);
  16071. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16072. };
  16073. SpriteManager.prototype.dispose = function () {
  16074. if (this._vertexBuffer) {
  16075. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16076. this._vertexBuffer = null;
  16077. }
  16078. if (this._indexBuffer) {
  16079. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16080. this._indexBuffer = null;
  16081. }
  16082. if (this._spriteTexture) {
  16083. this._spriteTexture.dispose();
  16084. this._spriteTexture = null;
  16085. }
  16086. // Remove from scene
  16087. var index = this._scene.spriteManagers.indexOf(this);
  16088. this._scene.spriteManagers.splice(index, 1);
  16089. // Callback
  16090. if (this.onDispose) {
  16091. this.onDispose();
  16092. }
  16093. };
  16094. return SpriteManager;
  16095. })();
  16096. BABYLON.SpriteManager = SpriteManager;
  16097. })(BABYLON || (BABYLON = {}));
  16098. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  16099. (function (BABYLON) {
  16100. var Sprite = (function () {
  16101. function Sprite(name, manager) {
  16102. this.name = name;
  16103. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16104. this.width = 1.0;
  16105. this.height = 1.0;
  16106. this.angle = 0;
  16107. this.cellIndex = 0;
  16108. this.invertU = 0;
  16109. this.invertV = 0;
  16110. this.animations = new Array();
  16111. this._animationStarted = false;
  16112. this._loopAnimation = false;
  16113. this._fromIndex = 0;
  16114. this._toIndex = 0;
  16115. this._delay = 0;
  16116. this._direction = 1;
  16117. this._frameCount = 0;
  16118. this._time = 0;
  16119. this._manager = manager;
  16120. this._manager.sprites.push(this);
  16121. this.position = BABYLON.Vector3.Zero();
  16122. }
  16123. Object.defineProperty(Sprite.prototype, "size", {
  16124. get: function () {
  16125. return this.width;
  16126. },
  16127. set: function (value) {
  16128. this.width = value;
  16129. this.height = value;
  16130. },
  16131. enumerable: true,
  16132. configurable: true
  16133. });
  16134. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  16135. this._fromIndex = from;
  16136. this._toIndex = to;
  16137. this._loopAnimation = loop;
  16138. this._delay = delay;
  16139. this._animationStarted = true;
  16140. this._direction = from < to ? 1 : -1;
  16141. this.cellIndex = from;
  16142. this._time = 0;
  16143. };
  16144. Sprite.prototype.stopAnimation = function () {
  16145. this._animationStarted = false;
  16146. };
  16147. Sprite.prototype._animate = function (deltaTime) {
  16148. if (!this._animationStarted)
  16149. return;
  16150. this._time += deltaTime;
  16151. if (this._time > this._delay) {
  16152. this._time = this._time % this._delay;
  16153. this.cellIndex += this._direction;
  16154. if (this.cellIndex == this._toIndex) {
  16155. if (this._loopAnimation) {
  16156. this.cellIndex = this._fromIndex;
  16157. }
  16158. else {
  16159. this._animationStarted = false;
  16160. if (this.disposeWhenFinishedAnimating) {
  16161. this.dispose();
  16162. }
  16163. }
  16164. }
  16165. }
  16166. };
  16167. Sprite.prototype.dispose = function () {
  16168. for (var i = 0; i < this._manager.sprites.length; i++) {
  16169. if (this._manager.sprites[i] == this) {
  16170. this._manager.sprites.splice(i, 1);
  16171. }
  16172. }
  16173. };
  16174. return Sprite;
  16175. })();
  16176. BABYLON.Sprite = Sprite;
  16177. })(BABYLON || (BABYLON = {}));
  16178. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  16179. (function (BABYLON) {
  16180. var Layer = (function () {
  16181. function Layer(name, imgUrl, scene, isBackground, color) {
  16182. this.name = name;
  16183. this._vertexDeclaration = [2];
  16184. this._vertexStrideSize = 2 * 4;
  16185. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  16186. this.isBackground = isBackground === undefined ? true : isBackground;
  16187. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  16188. this._scene = scene;
  16189. this._scene.layers.push(this);
  16190. // VBO
  16191. var vertices = [];
  16192. vertices.push(1, 1);
  16193. vertices.push(-1, 1);
  16194. vertices.push(-1, -1);
  16195. vertices.push(1, -1);
  16196. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16197. // Indices
  16198. var indices = [];
  16199. indices.push(0);
  16200. indices.push(1);
  16201. indices.push(2);
  16202. indices.push(0);
  16203. indices.push(2);
  16204. indices.push(3);
  16205. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16206. // Effects
  16207. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  16208. }
  16209. Layer.prototype.render = function () {
  16210. // Check
  16211. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  16212. return;
  16213. var engine = this._scene.getEngine();
  16214. // Render
  16215. engine.enableEffect(this._effect);
  16216. engine.setState(false);
  16217. // Texture
  16218. this._effect.setTexture("textureSampler", this.texture);
  16219. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  16220. // Color
  16221. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  16222. // VBOs
  16223. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16224. // Draw order
  16225. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16226. engine.draw(true, 0, 6);
  16227. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16228. };
  16229. Layer.prototype.dispose = function () {
  16230. if (this._vertexBuffer) {
  16231. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16232. this._vertexBuffer = null;
  16233. }
  16234. if (this._indexBuffer) {
  16235. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16236. this._indexBuffer = null;
  16237. }
  16238. if (this.texture) {
  16239. this.texture.dispose();
  16240. this.texture = null;
  16241. }
  16242. // Remove from scene
  16243. var index = this._scene.layers.indexOf(this);
  16244. this._scene.layers.splice(index, 1);
  16245. // Callback
  16246. if (this.onDispose) {
  16247. this.onDispose();
  16248. }
  16249. };
  16250. return Layer;
  16251. })();
  16252. BABYLON.Layer = Layer;
  16253. })(BABYLON || (BABYLON = {}));
  16254. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  16255. (function (BABYLON) {
  16256. var Particle = (function () {
  16257. function Particle() {
  16258. this.position = BABYLON.Vector3.Zero();
  16259. this.direction = BABYLON.Vector3.Zero();
  16260. this.color = new BABYLON.Color4(0, 0, 0, 0);
  16261. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  16262. this.lifeTime = 1.0;
  16263. this.age = 0;
  16264. this.size = 0;
  16265. this.angle = 0;
  16266. this.angularSpeed = 0;
  16267. }
  16268. Particle.prototype.copyTo = function (other) {
  16269. other.position.copyFrom(this.position);
  16270. other.direction.copyFrom(this.direction);
  16271. other.color.copyFrom(this.color);
  16272. other.colorStep.copyFrom(this.colorStep);
  16273. other.lifeTime = this.lifeTime;
  16274. other.age = this.age;
  16275. other.size = this.size;
  16276. other.angle = this.angle;
  16277. other.angularSpeed = this.angularSpeed;
  16278. };
  16279. return Particle;
  16280. })();
  16281. BABYLON.Particle = Particle;
  16282. })(BABYLON || (BABYLON = {}));
  16283. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  16284. (function (BABYLON) {
  16285. var randomNumber = function (min, max) {
  16286. if (min === max) {
  16287. return (min);
  16288. }
  16289. var random = Math.random();
  16290. return ((random * (max - min)) + min);
  16291. };
  16292. var ParticleSystem = (function () {
  16293. function ParticleSystem(name, capacity, scene, customEffect) {
  16294. var _this = this;
  16295. this.name = name;
  16296. this.renderingGroupId = 0;
  16297. this.emitter = null;
  16298. this.emitRate = 10;
  16299. this.manualEmitCount = -1;
  16300. this.updateSpeed = 0.01;
  16301. this.targetStopDuration = 0;
  16302. this.disposeOnStop = false;
  16303. this.minEmitPower = 1;
  16304. this.maxEmitPower = 1;
  16305. this.minLifeTime = 1;
  16306. this.maxLifeTime = 1;
  16307. this.minSize = 1;
  16308. this.maxSize = 1;
  16309. this.minAngularSpeed = 0;
  16310. this.maxAngularSpeed = 0;
  16311. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  16312. this.forceDepthWrite = false;
  16313. this.gravity = BABYLON.Vector3.Zero();
  16314. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  16315. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  16316. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  16317. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  16318. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16319. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16320. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  16321. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16322. this.particles = new Array();
  16323. this._vertexDeclaration = [3, 4, 4];
  16324. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  16325. this._stockParticles = new Array();
  16326. this._newPartsExcess = 0;
  16327. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  16328. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  16329. this._scaledDirection = BABYLON.Vector3.Zero();
  16330. this._scaledGravity = BABYLON.Vector3.Zero();
  16331. this._currentRenderId = -1;
  16332. this._started = false;
  16333. this._stopped = false;
  16334. this._actualFrame = 0;
  16335. this.id = name;
  16336. this._capacity = capacity;
  16337. this._scene = scene;
  16338. this._customEffect = customEffect;
  16339. scene.particleSystems.push(this);
  16340. // VBO
  16341. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  16342. var indices = [];
  16343. var index = 0;
  16344. for (var count = 0; count < capacity; count++) {
  16345. indices.push(index);
  16346. indices.push(index + 1);
  16347. indices.push(index + 2);
  16348. indices.push(index);
  16349. indices.push(index + 2);
  16350. indices.push(index + 3);
  16351. index += 4;
  16352. }
  16353. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16354. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  16355. // Default behaviors
  16356. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  16357. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  16358. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  16359. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  16360. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  16361. };
  16362. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  16363. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  16364. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  16365. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  16366. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  16367. };
  16368. this.updateFunction = function (particles) {
  16369. for (var index = 0; index < particles.length; index++) {
  16370. var particle = particles[index];
  16371. particle.age += _this._scaledUpdateSpeed;
  16372. if (particle.age >= particle.lifeTime) {
  16373. _this.recycleParticle(particle);
  16374. index--;
  16375. continue;
  16376. }
  16377. else {
  16378. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  16379. particle.color.addInPlace(_this._scaledColorStep);
  16380. if (particle.color.a < 0)
  16381. particle.color.a = 0;
  16382. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  16383. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  16384. particle.position.addInPlace(_this._scaledDirection);
  16385. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  16386. particle.direction.addInPlace(_this._scaledGravity);
  16387. }
  16388. }
  16389. };
  16390. }
  16391. ParticleSystem.prototype.recycleParticle = function (particle) {
  16392. var lastParticle = this.particles.pop();
  16393. if (lastParticle !== particle) {
  16394. lastParticle.copyTo(particle);
  16395. this._stockParticles.push(lastParticle);
  16396. }
  16397. };
  16398. ParticleSystem.prototype.getCapacity = function () {
  16399. return this._capacity;
  16400. };
  16401. ParticleSystem.prototype.isAlive = function () {
  16402. return this._alive;
  16403. };
  16404. ParticleSystem.prototype.isStarted = function () {
  16405. return this._started;
  16406. };
  16407. ParticleSystem.prototype.start = function () {
  16408. this._started = true;
  16409. this._stopped = false;
  16410. this._actualFrame = 0;
  16411. };
  16412. ParticleSystem.prototype.stop = function () {
  16413. this._stopped = true;
  16414. };
  16415. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  16416. var offset = index * 11;
  16417. this._vertices[offset] = particle.position.x;
  16418. this._vertices[offset + 1] = particle.position.y;
  16419. this._vertices[offset + 2] = particle.position.z;
  16420. this._vertices[offset + 3] = particle.color.r;
  16421. this._vertices[offset + 4] = particle.color.g;
  16422. this._vertices[offset + 5] = particle.color.b;
  16423. this._vertices[offset + 6] = particle.color.a;
  16424. this._vertices[offset + 7] = particle.angle;
  16425. this._vertices[offset + 8] = particle.size;
  16426. this._vertices[offset + 9] = offsetX;
  16427. this._vertices[offset + 10] = offsetY;
  16428. };
  16429. ParticleSystem.prototype._update = function (newParticles) {
  16430. // Update current
  16431. this._alive = this.particles.length > 0;
  16432. this.updateFunction(this.particles);
  16433. // Add new ones
  16434. var worldMatrix;
  16435. if (this.emitter.position) {
  16436. worldMatrix = this.emitter.getWorldMatrix();
  16437. }
  16438. else {
  16439. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  16440. }
  16441. for (var index = 0; index < newParticles; index++) {
  16442. if (this.particles.length === this._capacity) {
  16443. break;
  16444. }
  16445. if (this._stockParticles.length !== 0) {
  16446. var particle = this._stockParticles.pop();
  16447. particle.age = 0;
  16448. }
  16449. else {
  16450. particle = new BABYLON.Particle();
  16451. }
  16452. this.particles.push(particle);
  16453. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  16454. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  16455. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  16456. particle.size = randomNumber(this.minSize, this.maxSize);
  16457. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  16458. this.startPositionFunction(worldMatrix, particle.position);
  16459. var step = randomNumber(0, 1.0);
  16460. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  16461. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  16462. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  16463. }
  16464. };
  16465. ParticleSystem.prototype._getEffect = function () {
  16466. if (this._customEffect) {
  16467. return this._customEffect;
  16468. }
  16469. ;
  16470. var defines = [];
  16471. if (this._scene.clipPlane) {
  16472. defines.push("#define CLIPPLANE");
  16473. }
  16474. // Effect
  16475. var join = defines.join("\n");
  16476. if (this._cachedDefines !== join) {
  16477. this._cachedDefines = join;
  16478. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  16479. }
  16480. return this._effect;
  16481. };
  16482. ParticleSystem.prototype.animate = function () {
  16483. if (!this._started)
  16484. return;
  16485. var effect = this._getEffect();
  16486. // Check
  16487. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  16488. return;
  16489. if (this._currentRenderId === this._scene.getRenderId()) {
  16490. return;
  16491. }
  16492. this._currentRenderId = this._scene.getRenderId();
  16493. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  16494. // determine the number of particles we need to create
  16495. var emitCout;
  16496. if (this.manualEmitCount > -1) {
  16497. emitCout = this.manualEmitCount;
  16498. this.manualEmitCount = 0;
  16499. }
  16500. else {
  16501. emitCout = this.emitRate;
  16502. }
  16503. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  16504. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  16505. if (this._newPartsExcess > 1.0) {
  16506. newParticles += this._newPartsExcess >> 0;
  16507. this._newPartsExcess -= this._newPartsExcess >> 0;
  16508. }
  16509. this._alive = false;
  16510. if (!this._stopped) {
  16511. this._actualFrame += this._scaledUpdateSpeed;
  16512. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  16513. this.stop();
  16514. }
  16515. else {
  16516. newParticles = 0;
  16517. }
  16518. this._update(newParticles);
  16519. // Stopped?
  16520. if (this._stopped) {
  16521. if (!this._alive) {
  16522. this._started = false;
  16523. if (this.disposeOnStop) {
  16524. this._scene._toBeDisposed.push(this);
  16525. }
  16526. }
  16527. }
  16528. // Update VBO
  16529. var offset = 0;
  16530. for (var index = 0; index < this.particles.length; index++) {
  16531. var particle = this.particles[index];
  16532. this._appendParticleVertex(offset++, particle, 0, 0);
  16533. this._appendParticleVertex(offset++, particle, 1, 0);
  16534. this._appendParticleVertex(offset++, particle, 1, 1);
  16535. this._appendParticleVertex(offset++, particle, 0, 1);
  16536. }
  16537. var engine = this._scene.getEngine();
  16538. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  16539. };
  16540. ParticleSystem.prototype.render = function () {
  16541. var effect = this._getEffect();
  16542. // Check
  16543. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  16544. return 0;
  16545. var engine = this._scene.getEngine();
  16546. // Render
  16547. engine.enableEffect(effect);
  16548. engine.setState(false);
  16549. var viewMatrix = this._scene.getViewMatrix();
  16550. effect.setTexture("diffuseSampler", this.particleTexture);
  16551. effect.setMatrix("view", viewMatrix);
  16552. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  16553. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  16554. if (this._scene.clipPlane) {
  16555. var clipPlane = this._scene.clipPlane;
  16556. var invView = viewMatrix.clone();
  16557. invView.invert();
  16558. effect.setMatrix("invView", invView);
  16559. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  16560. }
  16561. // VBOs
  16562. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16563. // Draw order
  16564. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  16565. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  16566. }
  16567. else {
  16568. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16569. }
  16570. if (this.forceDepthWrite) {
  16571. engine.setDepthWrite(true);
  16572. }
  16573. engine.draw(true, 0, this.particles.length * 6);
  16574. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16575. return this.particles.length;
  16576. };
  16577. ParticleSystem.prototype.dispose = function () {
  16578. if (this._vertexBuffer) {
  16579. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16580. this._vertexBuffer = null;
  16581. }
  16582. if (this._indexBuffer) {
  16583. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16584. this._indexBuffer = null;
  16585. }
  16586. if (this.particleTexture) {
  16587. this.particleTexture.dispose();
  16588. this.particleTexture = null;
  16589. }
  16590. // Remove from scene
  16591. var index = this._scene.particleSystems.indexOf(this);
  16592. this._scene.particleSystems.splice(index, 1);
  16593. // Callback
  16594. if (this.onDispose) {
  16595. this.onDispose();
  16596. }
  16597. };
  16598. // Clone
  16599. ParticleSystem.prototype.clone = function (name, newEmitter) {
  16600. var result = new ParticleSystem(name, this._capacity, this._scene);
  16601. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  16602. if (newEmitter === undefined) {
  16603. newEmitter = this.emitter;
  16604. }
  16605. result.emitter = newEmitter;
  16606. if (this.particleTexture) {
  16607. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  16608. }
  16609. result.start();
  16610. return result;
  16611. };
  16612. // Statics
  16613. ParticleSystem.BLENDMODE_ONEONE = 0;
  16614. ParticleSystem.BLENDMODE_STANDARD = 1;
  16615. return ParticleSystem;
  16616. })();
  16617. BABYLON.ParticleSystem = ParticleSystem;
  16618. })(BABYLON || (BABYLON = {}));
  16619. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  16620. (function (BABYLON) {
  16621. var Animation = (function () {
  16622. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  16623. this.name = name;
  16624. this.targetProperty = targetProperty;
  16625. this.framePerSecond = framePerSecond;
  16626. this.dataType = dataType;
  16627. this.loopMode = loopMode;
  16628. this._offsetsCache = {};
  16629. this._highLimitsCache = {};
  16630. this._stopped = false;
  16631. this.targetPropertyPath = targetProperty.split(".");
  16632. this.dataType = dataType;
  16633. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  16634. }
  16635. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  16636. var dataType = undefined;
  16637. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  16638. dataType = Animation.ANIMATIONTYPE_FLOAT;
  16639. }
  16640. else if (from instanceof BABYLON.Quaternion) {
  16641. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  16642. }
  16643. else if (from instanceof BABYLON.Vector3) {
  16644. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  16645. }
  16646. else if (from instanceof BABYLON.Vector2) {
  16647. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  16648. }
  16649. else if (from instanceof BABYLON.Color3) {
  16650. dataType = Animation.ANIMATIONTYPE_COLOR3;
  16651. }
  16652. if (dataType == undefined) {
  16653. return null;
  16654. }
  16655. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  16656. var keys = [];
  16657. keys.push({ frame: 0, value: from });
  16658. keys.push({ frame: totalFrame, value: to });
  16659. animation.setKeys(keys);
  16660. mesh.animations.push(animation);
  16661. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  16662. };
  16663. // Methods
  16664. Animation.prototype.isStopped = function () {
  16665. return this._stopped;
  16666. };
  16667. Animation.prototype.getKeys = function () {
  16668. return this._keys;
  16669. };
  16670. Animation.prototype.getEasingFunction = function () {
  16671. return this._easingFunction;
  16672. };
  16673. Animation.prototype.setEasingFunction = function (easingFunction) {
  16674. this._easingFunction = easingFunction;
  16675. };
  16676. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  16677. return startValue + (endValue - startValue) * gradient;
  16678. };
  16679. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  16680. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  16681. };
  16682. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  16683. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  16684. };
  16685. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  16686. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  16687. };
  16688. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  16689. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  16690. };
  16691. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  16692. var startScale = new BABYLON.Vector3(0, 0, 0);
  16693. var startRotation = new BABYLON.Quaternion();
  16694. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  16695. startValue.decompose(startScale, startRotation, startTranslation);
  16696. var endScale = new BABYLON.Vector3(0, 0, 0);
  16697. var endRotation = new BABYLON.Quaternion();
  16698. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  16699. endValue.decompose(endScale, endRotation, endTranslation);
  16700. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  16701. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  16702. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  16703. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  16704. return result;
  16705. };
  16706. Animation.prototype.clone = function () {
  16707. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  16708. clone.setKeys(this._keys);
  16709. return clone;
  16710. };
  16711. Animation.prototype.setKeys = function (values) {
  16712. this._keys = values.slice(0);
  16713. this._offsetsCache = {};
  16714. this._highLimitsCache = {};
  16715. };
  16716. Animation.prototype._getKeyValue = function (value) {
  16717. if (typeof value === "function") {
  16718. return value();
  16719. }
  16720. return value;
  16721. };
  16722. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  16723. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  16724. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  16725. }
  16726. this.currentFrame = currentFrame;
  16727. // Try to get a hash to find the right key
  16728. var startKey = Math.max(0, Math.min(this._keys.length - 1, Math.floor(this._keys.length * (currentFrame - this._keys[0].frame) / (this._keys[this._keys.length - 1].frame - this._keys[0].frame)) - 1));
  16729. if (this._keys[startKey].frame >= currentFrame) {
  16730. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  16731. startKey--;
  16732. }
  16733. }
  16734. for (var key = startKey; key < this._keys.length; key++) {
  16735. if (this._keys[key + 1].frame >= currentFrame) {
  16736. var startValue = this._getKeyValue(this._keys[key].value);
  16737. var endValue = this._getKeyValue(this._keys[key + 1].value);
  16738. // gradient : percent of currentFrame between the frame inf and the frame sup
  16739. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  16740. // check for easingFunction and correction of gradient
  16741. if (this._easingFunction != null) {
  16742. gradient = this._easingFunction.ease(gradient);
  16743. }
  16744. switch (this.dataType) {
  16745. case Animation.ANIMATIONTYPE_FLOAT:
  16746. switch (loopMode) {
  16747. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16748. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16749. return this.floatInterpolateFunction(startValue, endValue, gradient);
  16750. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16751. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  16752. }
  16753. break;
  16754. case Animation.ANIMATIONTYPE_QUATERNION:
  16755. var quaternion = null;
  16756. switch (loopMode) {
  16757. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16758. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16759. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  16760. break;
  16761. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16762. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16763. break;
  16764. }
  16765. return quaternion;
  16766. case Animation.ANIMATIONTYPE_VECTOR3:
  16767. switch (loopMode) {
  16768. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16769. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16770. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  16771. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16772. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16773. }
  16774. case Animation.ANIMATIONTYPE_VECTOR2:
  16775. switch (loopMode) {
  16776. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16777. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16778. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  16779. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16780. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16781. }
  16782. case Animation.ANIMATIONTYPE_COLOR3:
  16783. switch (loopMode) {
  16784. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16785. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16786. return this.color3InterpolateFunction(startValue, endValue, gradient);
  16787. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16788. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16789. }
  16790. case Animation.ANIMATIONTYPE_MATRIX:
  16791. switch (loopMode) {
  16792. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16793. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16794. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16795. return startValue;
  16796. }
  16797. default:
  16798. break;
  16799. }
  16800. break;
  16801. }
  16802. }
  16803. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  16804. };
  16805. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  16806. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  16807. this._stopped = true;
  16808. return false;
  16809. }
  16810. var returnValue = true;
  16811. // Adding a start key at frame 0 if missing
  16812. if (this._keys[0].frame !== 0) {
  16813. var newKey = { frame: 0, value: this._keys[0].value };
  16814. this._keys.splice(0, 0, newKey);
  16815. }
  16816. // Check limits
  16817. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  16818. from = this._keys[0].frame;
  16819. }
  16820. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  16821. to = this._keys[this._keys.length - 1].frame;
  16822. }
  16823. // Compute ratio
  16824. var range = to - from;
  16825. var offsetValue;
  16826. // ratio represents the frame delta between from and to
  16827. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  16828. var highLimitValue = 0;
  16829. if (ratio > range && !loop) {
  16830. returnValue = false;
  16831. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  16832. }
  16833. else {
  16834. // Get max value if required
  16835. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  16836. var keyOffset = to.toString() + from.toString();
  16837. if (!this._offsetsCache[keyOffset]) {
  16838. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16839. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16840. switch (this.dataType) {
  16841. case Animation.ANIMATIONTYPE_FLOAT:
  16842. this._offsetsCache[keyOffset] = toValue - fromValue;
  16843. break;
  16844. case Animation.ANIMATIONTYPE_QUATERNION:
  16845. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16846. break;
  16847. case Animation.ANIMATIONTYPE_VECTOR3:
  16848. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16849. case Animation.ANIMATIONTYPE_VECTOR2:
  16850. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16851. case Animation.ANIMATIONTYPE_COLOR3:
  16852. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16853. default:
  16854. break;
  16855. }
  16856. this._highLimitsCache[keyOffset] = toValue;
  16857. }
  16858. highLimitValue = this._highLimitsCache[keyOffset];
  16859. offsetValue = this._offsetsCache[keyOffset];
  16860. }
  16861. }
  16862. if (offsetValue === undefined) {
  16863. switch (this.dataType) {
  16864. case Animation.ANIMATIONTYPE_FLOAT:
  16865. offsetValue = 0;
  16866. break;
  16867. case Animation.ANIMATIONTYPE_QUATERNION:
  16868. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  16869. break;
  16870. case Animation.ANIMATIONTYPE_VECTOR3:
  16871. offsetValue = BABYLON.Vector3.Zero();
  16872. break;
  16873. case Animation.ANIMATIONTYPE_VECTOR2:
  16874. offsetValue = BABYLON.Vector2.Zero();
  16875. break;
  16876. case Animation.ANIMATIONTYPE_COLOR3:
  16877. offsetValue = BABYLON.Color3.Black();
  16878. }
  16879. }
  16880. // Compute value
  16881. var repeatCount = (ratio / range) >> 0;
  16882. var currentFrame = returnValue ? from + ratio % range : to;
  16883. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  16884. // Set value
  16885. if (this.targetPropertyPath.length > 1) {
  16886. var property = this._target[this.targetPropertyPath[0]];
  16887. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  16888. property = property[this.targetPropertyPath[index]];
  16889. }
  16890. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  16891. }
  16892. else {
  16893. this._target[this.targetPropertyPath[0]] = currentValue;
  16894. }
  16895. if (this._target.markAsDirty) {
  16896. this._target.markAsDirty(this.targetProperty);
  16897. }
  16898. if (!returnValue) {
  16899. this._stopped = true;
  16900. }
  16901. return returnValue;
  16902. };
  16903. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  16904. get: function () {
  16905. return Animation._ANIMATIONTYPE_FLOAT;
  16906. },
  16907. enumerable: true,
  16908. configurable: true
  16909. });
  16910. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  16911. get: function () {
  16912. return Animation._ANIMATIONTYPE_VECTOR3;
  16913. },
  16914. enumerable: true,
  16915. configurable: true
  16916. });
  16917. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  16918. get: function () {
  16919. return Animation._ANIMATIONTYPE_VECTOR2;
  16920. },
  16921. enumerable: true,
  16922. configurable: true
  16923. });
  16924. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  16925. get: function () {
  16926. return Animation._ANIMATIONTYPE_QUATERNION;
  16927. },
  16928. enumerable: true,
  16929. configurable: true
  16930. });
  16931. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  16932. get: function () {
  16933. return Animation._ANIMATIONTYPE_MATRIX;
  16934. },
  16935. enumerable: true,
  16936. configurable: true
  16937. });
  16938. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  16939. get: function () {
  16940. return Animation._ANIMATIONTYPE_COLOR3;
  16941. },
  16942. enumerable: true,
  16943. configurable: true
  16944. });
  16945. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  16946. get: function () {
  16947. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  16948. },
  16949. enumerable: true,
  16950. configurable: true
  16951. });
  16952. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  16953. get: function () {
  16954. return Animation._ANIMATIONLOOPMODE_CYCLE;
  16955. },
  16956. enumerable: true,
  16957. configurable: true
  16958. });
  16959. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  16960. get: function () {
  16961. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  16962. },
  16963. enumerable: true,
  16964. configurable: true
  16965. });
  16966. // Statics
  16967. Animation._ANIMATIONTYPE_FLOAT = 0;
  16968. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  16969. Animation._ANIMATIONTYPE_QUATERNION = 2;
  16970. Animation._ANIMATIONTYPE_MATRIX = 3;
  16971. Animation._ANIMATIONTYPE_COLOR3 = 4;
  16972. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  16973. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  16974. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  16975. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  16976. return Animation;
  16977. })();
  16978. BABYLON.Animation = Animation;
  16979. })(BABYLON || (BABYLON = {}));
  16980. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  16981. (function (BABYLON) {
  16982. var Animatable = (function () {
  16983. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  16984. if (fromFrame === void 0) { fromFrame = 0; }
  16985. if (toFrame === void 0) { toFrame = 100; }
  16986. if (loopAnimation === void 0) { loopAnimation = false; }
  16987. if (speedRatio === void 0) { speedRatio = 1.0; }
  16988. this.target = target;
  16989. this.fromFrame = fromFrame;
  16990. this.toFrame = toFrame;
  16991. this.loopAnimation = loopAnimation;
  16992. this.speedRatio = speedRatio;
  16993. this.onAnimationEnd = onAnimationEnd;
  16994. this._animations = new Array();
  16995. this._paused = false;
  16996. this.animationStarted = false;
  16997. if (animations) {
  16998. this.appendAnimations(target, animations);
  16999. }
  17000. this._scene = scene;
  17001. scene._activeAnimatables.push(this);
  17002. }
  17003. // Methods
  17004. Animatable.prototype.appendAnimations = function (target, animations) {
  17005. for (var index = 0; index < animations.length; index++) {
  17006. var animation = animations[index];
  17007. animation._target = target;
  17008. this._animations.push(animation);
  17009. }
  17010. };
  17011. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  17012. var animations = this._animations;
  17013. for (var index = 0; index < animations.length; index++) {
  17014. if (animations[index].targetProperty === property) {
  17015. return animations[index];
  17016. }
  17017. }
  17018. return null;
  17019. };
  17020. Animatable.prototype.pause = function () {
  17021. if (this._paused) {
  17022. return;
  17023. }
  17024. this._paused = true;
  17025. };
  17026. Animatable.prototype.restart = function () {
  17027. this._paused = false;
  17028. };
  17029. Animatable.prototype.stop = function () {
  17030. var index = this._scene._activeAnimatables.indexOf(this);
  17031. if (index > -1) {
  17032. this._scene._activeAnimatables.splice(index, 1);
  17033. }
  17034. if (this.onAnimationEnd) {
  17035. this.onAnimationEnd();
  17036. }
  17037. };
  17038. Animatable.prototype._animate = function (delay) {
  17039. if (this._paused) {
  17040. if (!this._pausedDelay) {
  17041. this._pausedDelay = delay;
  17042. }
  17043. return true;
  17044. }
  17045. if (!this._localDelayOffset) {
  17046. this._localDelayOffset = delay;
  17047. }
  17048. else if (this._pausedDelay) {
  17049. this._localDelayOffset += delay - this._pausedDelay;
  17050. this._pausedDelay = null;
  17051. }
  17052. // Animating
  17053. var running = false;
  17054. var animations = this._animations;
  17055. for (var index = 0; index < animations.length; index++) {
  17056. var animation = animations[index];
  17057. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  17058. running = running || isRunning;
  17059. }
  17060. if (!running) {
  17061. // Remove from active animatables
  17062. index = this._scene._activeAnimatables.indexOf(this);
  17063. this._scene._activeAnimatables.splice(index, 1);
  17064. }
  17065. if (!running && this.onAnimationEnd) {
  17066. this.onAnimationEnd();
  17067. }
  17068. return running;
  17069. };
  17070. return Animatable;
  17071. })();
  17072. BABYLON.Animatable = Animatable;
  17073. })(BABYLON || (BABYLON = {}));
  17074. //# sourceMappingURL=babylon.animatable.js.map
  17075. var BABYLON;
  17076. (function (BABYLON) {
  17077. var EasingFunction = (function () {
  17078. function EasingFunction() {
  17079. // Properties
  17080. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  17081. }
  17082. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  17083. get: function () {
  17084. return EasingFunction._EASINGMODE_EASEIN;
  17085. },
  17086. enumerable: true,
  17087. configurable: true
  17088. });
  17089. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  17090. get: function () {
  17091. return EasingFunction._EASINGMODE_EASEOUT;
  17092. },
  17093. enumerable: true,
  17094. configurable: true
  17095. });
  17096. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  17097. get: function () {
  17098. return EasingFunction._EASINGMODE_EASEINOUT;
  17099. },
  17100. enumerable: true,
  17101. configurable: true
  17102. });
  17103. EasingFunction.prototype.setEasingMode = function (easingMode) {
  17104. var n = Math.min(Math.max(easingMode, 0), 2);
  17105. this._easingMode = n;
  17106. };
  17107. EasingFunction.prototype.getEasingMode = function () {
  17108. return this._easingMode;
  17109. };
  17110. EasingFunction.prototype.easeInCore = function (gradient) {
  17111. throw new Error('You must implement this method');
  17112. };
  17113. EasingFunction.prototype.ease = function (gradient) {
  17114. switch (this._easingMode) {
  17115. case EasingFunction.EASINGMODE_EASEIN:
  17116. return this.easeInCore(gradient);
  17117. case EasingFunction.EASINGMODE_EASEOUT:
  17118. return (1 - this.easeInCore(1 - gradient));
  17119. }
  17120. if (gradient >= 0.5) {
  17121. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  17122. }
  17123. return (this.easeInCore(gradient * 2) * 0.5);
  17124. };
  17125. //Statics
  17126. EasingFunction._EASINGMODE_EASEIN = 0;
  17127. EasingFunction._EASINGMODE_EASEOUT = 1;
  17128. EasingFunction._EASINGMODE_EASEINOUT = 2;
  17129. return EasingFunction;
  17130. })();
  17131. BABYLON.EasingFunction = EasingFunction;
  17132. var CircleEase = (function (_super) {
  17133. __extends(CircleEase, _super);
  17134. function CircleEase() {
  17135. _super.apply(this, arguments);
  17136. }
  17137. CircleEase.prototype.easeInCore = function (gradient) {
  17138. gradient = Math.max(0, Math.min(1, gradient));
  17139. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  17140. };
  17141. return CircleEase;
  17142. })(EasingFunction);
  17143. BABYLON.CircleEase = CircleEase;
  17144. var BackEase = (function (_super) {
  17145. __extends(BackEase, _super);
  17146. function BackEase(amplitude) {
  17147. if (amplitude === void 0) { amplitude = 1; }
  17148. _super.call(this);
  17149. this.amplitude = amplitude;
  17150. }
  17151. BackEase.prototype.easeInCore = function (gradient) {
  17152. var num = Math.max(0, this.amplitude);
  17153. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  17154. };
  17155. return BackEase;
  17156. })(EasingFunction);
  17157. BABYLON.BackEase = BackEase;
  17158. var BounceEase = (function (_super) {
  17159. __extends(BounceEase, _super);
  17160. function BounceEase(bounces, bounciness) {
  17161. if (bounces === void 0) { bounces = 3; }
  17162. if (bounciness === void 0) { bounciness = 2; }
  17163. _super.call(this);
  17164. this.bounces = bounces;
  17165. this.bounciness = bounciness;
  17166. }
  17167. BounceEase.prototype.easeInCore = function (gradient) {
  17168. var y = Math.max(0.0, this.bounces);
  17169. var bounciness = this.bounciness;
  17170. if (bounciness <= 1.0) {
  17171. bounciness = 1.001;
  17172. }
  17173. var num9 = Math.pow(bounciness, y);
  17174. var num5 = 1.0 - bounciness;
  17175. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  17176. var num15 = gradient * num4;
  17177. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  17178. var num3 = Math.floor(num65);
  17179. var num13 = num3 + 1.0;
  17180. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  17181. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  17182. var num7 = (num8 + num12) * 0.5;
  17183. var num6 = gradient - num7;
  17184. var num2 = num7 - num8;
  17185. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  17186. };
  17187. return BounceEase;
  17188. })(EasingFunction);
  17189. BABYLON.BounceEase = BounceEase;
  17190. var CubicEase = (function (_super) {
  17191. __extends(CubicEase, _super);
  17192. function CubicEase() {
  17193. _super.apply(this, arguments);
  17194. }
  17195. CubicEase.prototype.easeInCore = function (gradient) {
  17196. return (gradient * gradient * gradient);
  17197. };
  17198. return CubicEase;
  17199. })(EasingFunction);
  17200. BABYLON.CubicEase = CubicEase;
  17201. var ElasticEase = (function (_super) {
  17202. __extends(ElasticEase, _super);
  17203. function ElasticEase(oscillations, springiness) {
  17204. if (oscillations === void 0) { oscillations = 3; }
  17205. if (springiness === void 0) { springiness = 3; }
  17206. _super.call(this);
  17207. this.oscillations = oscillations;
  17208. this.springiness = springiness;
  17209. }
  17210. ElasticEase.prototype.easeInCore = function (gradient) {
  17211. var num2;
  17212. var num3 = Math.max(0.0, this.oscillations);
  17213. var num = Math.max(0.0, this.springiness);
  17214. if (num == 0) {
  17215. num2 = gradient;
  17216. }
  17217. else {
  17218. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  17219. }
  17220. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  17221. };
  17222. return ElasticEase;
  17223. })(EasingFunction);
  17224. BABYLON.ElasticEase = ElasticEase;
  17225. var ExponentialEase = (function (_super) {
  17226. __extends(ExponentialEase, _super);
  17227. function ExponentialEase(exponent) {
  17228. if (exponent === void 0) { exponent = 2; }
  17229. _super.call(this);
  17230. this.exponent = exponent;
  17231. }
  17232. ExponentialEase.prototype.easeInCore = function (gradient) {
  17233. if (this.exponent <= 0) {
  17234. return gradient;
  17235. }
  17236. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  17237. };
  17238. return ExponentialEase;
  17239. })(EasingFunction);
  17240. BABYLON.ExponentialEase = ExponentialEase;
  17241. var PowerEase = (function (_super) {
  17242. __extends(PowerEase, _super);
  17243. function PowerEase(power) {
  17244. if (power === void 0) { power = 2; }
  17245. _super.call(this);
  17246. this.power = power;
  17247. }
  17248. PowerEase.prototype.easeInCore = function (gradient) {
  17249. var y = Math.max(0.0, this.power);
  17250. return Math.pow(gradient, y);
  17251. };
  17252. return PowerEase;
  17253. })(EasingFunction);
  17254. BABYLON.PowerEase = PowerEase;
  17255. var QuadraticEase = (function (_super) {
  17256. __extends(QuadraticEase, _super);
  17257. function QuadraticEase() {
  17258. _super.apply(this, arguments);
  17259. }
  17260. QuadraticEase.prototype.easeInCore = function (gradient) {
  17261. return (gradient * gradient);
  17262. };
  17263. return QuadraticEase;
  17264. })(EasingFunction);
  17265. BABYLON.QuadraticEase = QuadraticEase;
  17266. var QuarticEase = (function (_super) {
  17267. __extends(QuarticEase, _super);
  17268. function QuarticEase() {
  17269. _super.apply(this, arguments);
  17270. }
  17271. QuarticEase.prototype.easeInCore = function (gradient) {
  17272. return (gradient * gradient * gradient * gradient);
  17273. };
  17274. return QuarticEase;
  17275. })(EasingFunction);
  17276. BABYLON.QuarticEase = QuarticEase;
  17277. var QuinticEase = (function (_super) {
  17278. __extends(QuinticEase, _super);
  17279. function QuinticEase() {
  17280. _super.apply(this, arguments);
  17281. }
  17282. QuinticEase.prototype.easeInCore = function (gradient) {
  17283. return (gradient * gradient * gradient * gradient * gradient);
  17284. };
  17285. return QuinticEase;
  17286. })(EasingFunction);
  17287. BABYLON.QuinticEase = QuinticEase;
  17288. var SineEase = (function (_super) {
  17289. __extends(SineEase, _super);
  17290. function SineEase() {
  17291. _super.apply(this, arguments);
  17292. }
  17293. SineEase.prototype.easeInCore = function (gradient) {
  17294. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  17295. };
  17296. return SineEase;
  17297. })(EasingFunction);
  17298. BABYLON.SineEase = SineEase;
  17299. var BezierCurveEase = (function (_super) {
  17300. __extends(BezierCurveEase, _super);
  17301. function BezierCurveEase(x1, y1, x2, y2) {
  17302. if (x1 === void 0) { x1 = 0; }
  17303. if (y1 === void 0) { y1 = 0; }
  17304. if (x2 === void 0) { x2 = 1; }
  17305. if (y2 === void 0) { y2 = 1; }
  17306. _super.call(this);
  17307. this.x1 = x1;
  17308. this.y1 = y1;
  17309. this.x2 = x2;
  17310. this.y2 = y2;
  17311. }
  17312. BezierCurveEase.prototype.easeInCore = function (gradient) {
  17313. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  17314. };
  17315. return BezierCurveEase;
  17316. })(EasingFunction);
  17317. BABYLON.BezierCurveEase = BezierCurveEase;
  17318. })(BABYLON || (BABYLON = {}));
  17319. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  17320. (function (BABYLON) {
  17321. var Octree = (function () {
  17322. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  17323. if (maxDepth === void 0) { maxDepth = 2; }
  17324. this.maxDepth = maxDepth;
  17325. this.dynamicContent = new Array();
  17326. this._maxBlockCapacity = maxBlockCapacity || 64;
  17327. this._selectionContent = new BABYLON.SmartArray(1024);
  17328. this._creationFunc = creationFunc;
  17329. }
  17330. // Methods
  17331. Octree.prototype.update = function (worldMin, worldMax, entries) {
  17332. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  17333. };
  17334. Octree.prototype.addMesh = function (entry) {
  17335. for (var index = 0; index < this.blocks.length; index++) {
  17336. var block = this.blocks[index];
  17337. block.addEntry(entry);
  17338. }
  17339. };
  17340. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  17341. this._selectionContent.reset();
  17342. for (var index = 0; index < this.blocks.length; index++) {
  17343. var block = this.blocks[index];
  17344. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  17345. }
  17346. if (allowDuplicate) {
  17347. this._selectionContent.concat(this.dynamicContent);
  17348. }
  17349. else {
  17350. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  17351. }
  17352. return this._selectionContent;
  17353. };
  17354. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  17355. this._selectionContent.reset();
  17356. for (var index = 0; index < this.blocks.length; index++) {
  17357. var block = this.blocks[index];
  17358. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  17359. }
  17360. if (allowDuplicate) {
  17361. this._selectionContent.concat(this.dynamicContent);
  17362. }
  17363. else {
  17364. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  17365. }
  17366. return this._selectionContent;
  17367. };
  17368. Octree.prototype.intersectsRay = function (ray) {
  17369. this._selectionContent.reset();
  17370. for (var index = 0; index < this.blocks.length; index++) {
  17371. var block = this.blocks[index];
  17372. block.intersectsRay(ray, this._selectionContent);
  17373. }
  17374. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  17375. return this._selectionContent;
  17376. };
  17377. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  17378. target.blocks = new Array();
  17379. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  17380. for (var x = 0; x < 2; x++) {
  17381. for (var y = 0; y < 2; y++) {
  17382. for (var z = 0; z < 2; z++) {
  17383. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  17384. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  17385. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  17386. block.addEntries(entries);
  17387. target.blocks.push(block);
  17388. }
  17389. }
  17390. }
  17391. };
  17392. Octree.CreationFuncForMeshes = function (entry, block) {
  17393. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  17394. block.entries.push(entry);
  17395. }
  17396. };
  17397. Octree.CreationFuncForSubMeshes = function (entry, block) {
  17398. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  17399. block.entries.push(entry);
  17400. }
  17401. };
  17402. return Octree;
  17403. })();
  17404. BABYLON.Octree = Octree;
  17405. })(BABYLON || (BABYLON = {}));
  17406. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  17407. (function (BABYLON) {
  17408. var OctreeBlock = (function () {
  17409. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  17410. this.entries = new Array();
  17411. this._boundingVectors = new Array();
  17412. this._capacity = capacity;
  17413. this._depth = depth;
  17414. this._maxDepth = maxDepth;
  17415. this._creationFunc = creationFunc;
  17416. this._minPoint = minPoint;
  17417. this._maxPoint = maxPoint;
  17418. this._boundingVectors.push(minPoint.clone());
  17419. this._boundingVectors.push(maxPoint.clone());
  17420. this._boundingVectors.push(minPoint.clone());
  17421. this._boundingVectors[2].x = maxPoint.x;
  17422. this._boundingVectors.push(minPoint.clone());
  17423. this._boundingVectors[3].y = maxPoint.y;
  17424. this._boundingVectors.push(minPoint.clone());
  17425. this._boundingVectors[4].z = maxPoint.z;
  17426. this._boundingVectors.push(maxPoint.clone());
  17427. this._boundingVectors[5].z = minPoint.z;
  17428. this._boundingVectors.push(maxPoint.clone());
  17429. this._boundingVectors[6].x = minPoint.x;
  17430. this._boundingVectors.push(maxPoint.clone());
  17431. this._boundingVectors[7].y = minPoint.y;
  17432. }
  17433. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  17434. // Property
  17435. get: function () {
  17436. return this._capacity;
  17437. },
  17438. enumerable: true,
  17439. configurable: true
  17440. });
  17441. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  17442. get: function () {
  17443. return this._minPoint;
  17444. },
  17445. enumerable: true,
  17446. configurable: true
  17447. });
  17448. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  17449. get: function () {
  17450. return this._maxPoint;
  17451. },
  17452. enumerable: true,
  17453. configurable: true
  17454. });
  17455. // Methods
  17456. OctreeBlock.prototype.addEntry = function (entry) {
  17457. if (this.blocks) {
  17458. for (var index = 0; index < this.blocks.length; index++) {
  17459. var block = this.blocks[index];
  17460. block.addEntry(entry);
  17461. }
  17462. return;
  17463. }
  17464. this._creationFunc(entry, this);
  17465. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  17466. this.createInnerBlocks();
  17467. }
  17468. };
  17469. OctreeBlock.prototype.addEntries = function (entries) {
  17470. for (var index = 0; index < entries.length; index++) {
  17471. var mesh = entries[index];
  17472. this.addEntry(mesh);
  17473. }
  17474. };
  17475. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  17476. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  17477. if (this.blocks) {
  17478. for (var index = 0; index < this.blocks.length; index++) {
  17479. var block = this.blocks[index];
  17480. block.select(frustumPlanes, selection, allowDuplicate);
  17481. }
  17482. return;
  17483. }
  17484. if (allowDuplicate) {
  17485. selection.concat(this.entries);
  17486. }
  17487. else {
  17488. selection.concatWithNoDuplicate(this.entries);
  17489. }
  17490. }
  17491. };
  17492. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  17493. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  17494. if (this.blocks) {
  17495. for (var index = 0; index < this.blocks.length; index++) {
  17496. var block = this.blocks[index];
  17497. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  17498. }
  17499. return;
  17500. }
  17501. if (allowDuplicate) {
  17502. selection.concat(this.entries);
  17503. }
  17504. else {
  17505. selection.concatWithNoDuplicate(this.entries);
  17506. }
  17507. }
  17508. };
  17509. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  17510. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  17511. if (this.blocks) {
  17512. for (var index = 0; index < this.blocks.length; index++) {
  17513. var block = this.blocks[index];
  17514. block.intersectsRay(ray, selection);
  17515. }
  17516. return;
  17517. }
  17518. selection.concatWithNoDuplicate(this.entries);
  17519. }
  17520. };
  17521. OctreeBlock.prototype.createInnerBlocks = function () {
  17522. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  17523. };
  17524. return OctreeBlock;
  17525. })();
  17526. BABYLON.OctreeBlock = OctreeBlock;
  17527. })(BABYLON || (BABYLON = {}));
  17528. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  17529. (function (BABYLON) {
  17530. var Bone = (function () {
  17531. function Bone(name, skeleton, parentBone, matrix) {
  17532. this.name = name;
  17533. this.children = new Array();
  17534. this.animations = new Array();
  17535. this._worldTransform = new BABYLON.Matrix();
  17536. this._absoluteTransform = new BABYLON.Matrix();
  17537. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  17538. this._skeleton = skeleton;
  17539. this._matrix = matrix;
  17540. this._baseMatrix = matrix;
  17541. skeleton.bones.push(this);
  17542. if (parentBone) {
  17543. this._parent = parentBone;
  17544. parentBone.children.push(this);
  17545. }
  17546. else {
  17547. this._parent = null;
  17548. }
  17549. this._updateDifferenceMatrix();
  17550. }
  17551. // Members
  17552. Bone.prototype.getParent = function () {
  17553. return this._parent;
  17554. };
  17555. Bone.prototype.getLocalMatrix = function () {
  17556. return this._matrix;
  17557. };
  17558. Bone.prototype.getBaseMatrix = function () {
  17559. return this._baseMatrix;
  17560. };
  17561. Bone.prototype.getWorldMatrix = function () {
  17562. return this._worldTransform;
  17563. };
  17564. Bone.prototype.getInvertedAbsoluteTransform = function () {
  17565. return this._invertedAbsoluteTransform;
  17566. };
  17567. Bone.prototype.getAbsoluteMatrix = function () {
  17568. var matrix = this._matrix.clone();
  17569. var parent = this._parent;
  17570. while (parent) {
  17571. matrix = matrix.multiply(parent.getLocalMatrix());
  17572. parent = parent.getParent();
  17573. }
  17574. return matrix;
  17575. };
  17576. // Methods
  17577. Bone.prototype.updateMatrix = function (matrix) {
  17578. this._matrix = matrix;
  17579. this._skeleton._markAsDirty();
  17580. this._updateDifferenceMatrix();
  17581. };
  17582. Bone.prototype._updateDifferenceMatrix = function () {
  17583. if (this._parent) {
  17584. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  17585. }
  17586. else {
  17587. this._absoluteTransform.copyFrom(this._matrix);
  17588. }
  17589. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  17590. for (var index = 0; index < this.children.length; index++) {
  17591. this.children[index]._updateDifferenceMatrix();
  17592. }
  17593. };
  17594. Bone.prototype.markAsDirty = function () {
  17595. this._skeleton._markAsDirty();
  17596. };
  17597. return Bone;
  17598. })();
  17599. BABYLON.Bone = Bone;
  17600. })(BABYLON || (BABYLON = {}));
  17601. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  17602. (function (BABYLON) {
  17603. var Skeleton = (function () {
  17604. function Skeleton(name, id, scene) {
  17605. this.name = name;
  17606. this.id = id;
  17607. this.bones = new Array();
  17608. this._isDirty = true;
  17609. this._identity = BABYLON.Matrix.Identity();
  17610. this.bones = [];
  17611. this._scene = scene;
  17612. scene.skeletons.push(this);
  17613. this.prepare();
  17614. //make sure it will recalculate the matrix next time prepare is called.
  17615. this._isDirty = true;
  17616. }
  17617. // Members
  17618. Skeleton.prototype.getTransformMatrices = function () {
  17619. return this._transformMatrices;
  17620. };
  17621. // Methods
  17622. Skeleton.prototype._markAsDirty = function () {
  17623. this._isDirty = true;
  17624. };
  17625. Skeleton.prototype.prepare = function () {
  17626. if (!this._isDirty) {
  17627. return;
  17628. }
  17629. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  17630. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  17631. }
  17632. for (var index = 0; index < this.bones.length; index++) {
  17633. var bone = this.bones[index];
  17634. var parentBone = bone.getParent();
  17635. if (parentBone) {
  17636. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  17637. }
  17638. else {
  17639. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  17640. }
  17641. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  17642. }
  17643. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  17644. this._isDirty = false;
  17645. this._scene._activeBones += this.bones.length;
  17646. };
  17647. Skeleton.prototype.getAnimatables = function () {
  17648. if (!this._animatables || this._animatables.length !== this.bones.length) {
  17649. this._animatables = [];
  17650. for (var index = 0; index < this.bones.length; index++) {
  17651. this._animatables.push(this.bones[index]);
  17652. }
  17653. }
  17654. return this._animatables;
  17655. };
  17656. Skeleton.prototype.clone = function (name, id) {
  17657. var result = new Skeleton(name, id || name, this._scene);
  17658. for (var index = 0; index < this.bones.length; index++) {
  17659. var source = this.bones[index];
  17660. var parentBone = null;
  17661. if (source.getParent()) {
  17662. var parentIndex = this.bones.indexOf(source.getParent());
  17663. parentBone = result.bones[parentIndex];
  17664. }
  17665. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  17666. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  17667. }
  17668. return result;
  17669. };
  17670. return Skeleton;
  17671. })();
  17672. BABYLON.Skeleton = Skeleton;
  17673. })(BABYLON || (BABYLON = {}));
  17674. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  17675. (function (BABYLON) {
  17676. var PostProcess = (function () {
  17677. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  17678. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  17679. this.name = name;
  17680. this.width = -1;
  17681. this.height = -1;
  17682. this._reusable = false;
  17683. this._textures = new BABYLON.SmartArray(2);
  17684. this._currentRenderTextureInd = 0;
  17685. if (camera != null) {
  17686. this._camera = camera;
  17687. this._scene = camera.getScene();
  17688. camera.attachPostProcess(this);
  17689. this._engine = this._scene.getEngine();
  17690. }
  17691. else {
  17692. this._engine = engine;
  17693. }
  17694. this._renderRatio = ratio;
  17695. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  17696. this._reusable = reusable || false;
  17697. samplers = samplers || [];
  17698. samplers.push("textureSampler");
  17699. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  17700. }
  17701. PostProcess.prototype.isReusable = function () {
  17702. return this._reusable;
  17703. };
  17704. PostProcess.prototype.activate = function (camera, sourceTexture) {
  17705. camera = camera || this._camera;
  17706. var scene = camera.getScene();
  17707. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  17708. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  17709. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  17710. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  17711. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  17712. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  17713. if (this._textures.length > 0) {
  17714. for (var i = 0; i < this._textures.length; i++) {
  17715. this._engine._releaseTexture(this._textures.data[i]);
  17716. }
  17717. this._textures.reset();
  17718. }
  17719. this.width = desiredWidth;
  17720. this.height = desiredHeight;
  17721. 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 }));
  17722. if (this._reusable) {
  17723. 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 }));
  17724. }
  17725. if (this.onSizeChanged) {
  17726. this.onSizeChanged();
  17727. }
  17728. }
  17729. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  17730. if (this.onActivate) {
  17731. this.onActivate(camera);
  17732. }
  17733. // Clear
  17734. if (this.clearColor) {
  17735. this._engine.clear(this.clearColor, true, true);
  17736. }
  17737. else {
  17738. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  17739. }
  17740. if (this._reusable) {
  17741. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  17742. }
  17743. };
  17744. PostProcess.prototype.apply = function () {
  17745. // Check
  17746. if (!this._effect.isReady())
  17747. return null;
  17748. // States
  17749. this._engine.enableEffect(this._effect);
  17750. this._engine.setState(false);
  17751. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17752. this._engine.setDepthBuffer(false);
  17753. this._engine.setDepthWrite(false);
  17754. // Texture
  17755. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  17756. // Parameters
  17757. if (this.onApply) {
  17758. this.onApply(this._effect);
  17759. }
  17760. return this._effect;
  17761. };
  17762. PostProcess.prototype.dispose = function (camera) {
  17763. camera = camera || this._camera;
  17764. if (this._textures.length > 0) {
  17765. for (var i = 0; i < this._textures.length; i++) {
  17766. this._engine._releaseTexture(this._textures.data[i]);
  17767. }
  17768. this._textures.reset();
  17769. }
  17770. if (!camera) {
  17771. return;
  17772. }
  17773. camera.detachPostProcess(this);
  17774. var index = camera._postProcesses.indexOf(this);
  17775. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  17776. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  17777. }
  17778. };
  17779. return PostProcess;
  17780. })();
  17781. BABYLON.PostProcess = PostProcess;
  17782. })(BABYLON || (BABYLON = {}));
  17783. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  17784. (function (BABYLON) {
  17785. var PostProcessManager = (function () {
  17786. function PostProcessManager(scene) {
  17787. this._vertexDeclaration = [2];
  17788. this._vertexStrideSize = 2 * 4;
  17789. this._scene = scene;
  17790. }
  17791. PostProcessManager.prototype._prepareBuffers = function () {
  17792. if (this._vertexBuffer) {
  17793. return;
  17794. }
  17795. // VBO
  17796. var vertices = [];
  17797. vertices.push(1, 1);
  17798. vertices.push(-1, 1);
  17799. vertices.push(-1, -1);
  17800. vertices.push(1, -1);
  17801. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  17802. // Indices
  17803. var indices = [];
  17804. indices.push(0);
  17805. indices.push(1);
  17806. indices.push(2);
  17807. indices.push(0);
  17808. indices.push(2);
  17809. indices.push(3);
  17810. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  17811. };
  17812. // Methods
  17813. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  17814. var postProcesses = this._scene.activeCamera._postProcesses;
  17815. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17816. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17817. return false;
  17818. }
  17819. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  17820. return true;
  17821. };
  17822. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  17823. var engine = this._scene.getEngine();
  17824. for (var index = 0; index < postProcesses.length; index++) {
  17825. if (index < postProcesses.length - 1) {
  17826. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  17827. }
  17828. else {
  17829. if (targetTexture) {
  17830. engine.bindFramebuffer(targetTexture);
  17831. }
  17832. else {
  17833. engine.restoreDefaultFramebuffer();
  17834. }
  17835. }
  17836. var pp = postProcesses[index];
  17837. var effect = pp.apply();
  17838. if (effect) {
  17839. if (pp.onBeforeRender) {
  17840. pp.onBeforeRender(effect);
  17841. }
  17842. // VBOs
  17843. this._prepareBuffers();
  17844. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17845. // Draw order
  17846. engine.draw(true, 0, 6);
  17847. }
  17848. }
  17849. // Restore depth buffer
  17850. engine.setDepthBuffer(true);
  17851. engine.setDepthWrite(true);
  17852. };
  17853. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  17854. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  17855. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17856. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17857. return;
  17858. }
  17859. var engine = this._scene.getEngine();
  17860. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  17861. if (index < postProcessesTakenIndices.length - 1) {
  17862. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  17863. }
  17864. else {
  17865. if (targetTexture) {
  17866. engine.bindFramebuffer(targetTexture);
  17867. }
  17868. else {
  17869. engine.restoreDefaultFramebuffer();
  17870. }
  17871. }
  17872. if (doNotPresent) {
  17873. break;
  17874. }
  17875. var pp = postProcesses[postProcessesTakenIndices[index]];
  17876. var effect = pp.apply();
  17877. if (effect) {
  17878. if (pp.onBeforeRender) {
  17879. pp.onBeforeRender(effect);
  17880. }
  17881. // VBOs
  17882. this._prepareBuffers();
  17883. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17884. // Draw order
  17885. engine.draw(true, 0, 6);
  17886. }
  17887. }
  17888. // Restore depth buffer
  17889. engine.setDepthBuffer(true);
  17890. engine.setDepthWrite(true);
  17891. };
  17892. PostProcessManager.prototype.dispose = function () {
  17893. if (this._vertexBuffer) {
  17894. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17895. this._vertexBuffer = null;
  17896. }
  17897. if (this._indexBuffer) {
  17898. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17899. this._indexBuffer = null;
  17900. }
  17901. };
  17902. return PostProcessManager;
  17903. })();
  17904. BABYLON.PostProcessManager = PostProcessManager;
  17905. })(BABYLON || (BABYLON = {}));
  17906. //# sourceMappingURL=babylon.postProcessManager.js.map
  17907. var BABYLON;
  17908. (function (BABYLON) {
  17909. var PassPostProcess = (function (_super) {
  17910. __extends(PassPostProcess, _super);
  17911. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17912. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  17913. }
  17914. return PassPostProcess;
  17915. })(BABYLON.PostProcess);
  17916. BABYLON.PassPostProcess = PassPostProcess;
  17917. })(BABYLON || (BABYLON = {}));
  17918. //# sourceMappingURL=babylon.passPostProcess.js.map
  17919. var BABYLON;
  17920. (function (BABYLON) {
  17921. var BlurPostProcess = (function (_super) {
  17922. __extends(BlurPostProcess, _super);
  17923. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  17924. var _this = this;
  17925. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  17926. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  17927. this.direction = direction;
  17928. this.blurWidth = blurWidth;
  17929. this.onApply = function (effect) {
  17930. effect.setFloat2("screenSize", _this.width, _this.height);
  17931. effect.setVector2("direction", _this.direction);
  17932. effect.setFloat("blurWidth", _this.blurWidth);
  17933. };
  17934. }
  17935. return BlurPostProcess;
  17936. })(BABYLON.PostProcess);
  17937. BABYLON.BlurPostProcess = BlurPostProcess;
  17938. })(BABYLON || (BABYLON = {}));
  17939. //# sourceMappingURL=babylon.blurPostProcess.js.map
  17940. var BABYLON;
  17941. (function (BABYLON) {
  17942. var FilterPostProcess = (function (_super) {
  17943. __extends(FilterPostProcess, _super);
  17944. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  17945. var _this = this;
  17946. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  17947. this.kernelMatrix = kernelMatrix;
  17948. this.onApply = function (effect) {
  17949. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  17950. };
  17951. }
  17952. return FilterPostProcess;
  17953. })(BABYLON.PostProcess);
  17954. BABYLON.FilterPostProcess = FilterPostProcess;
  17955. })(BABYLON || (BABYLON = {}));
  17956. //# sourceMappingURL=babylon.filterPostProcess.js.map
  17957. var BABYLON;
  17958. (function (BABYLON) {
  17959. var RefractionPostProcess = (function (_super) {
  17960. __extends(RefractionPostProcess, _super);
  17961. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  17962. var _this = this;
  17963. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  17964. this.color = color;
  17965. this.depth = depth;
  17966. this.colorLevel = colorLevel;
  17967. this.onActivate = function (cam) {
  17968. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  17969. };
  17970. this.onApply = function (effect) {
  17971. effect.setColor3("baseColor", _this.color);
  17972. effect.setFloat("depth", _this.depth);
  17973. effect.setFloat("colorLevel", _this.colorLevel);
  17974. effect.setTexture("refractionSampler", _this._refRexture);
  17975. };
  17976. }
  17977. // Methods
  17978. RefractionPostProcess.prototype.dispose = function (camera) {
  17979. if (this._refRexture) {
  17980. this._refRexture.dispose();
  17981. }
  17982. _super.prototype.dispose.call(this, camera);
  17983. };
  17984. return RefractionPostProcess;
  17985. })(BABYLON.PostProcess);
  17986. BABYLON.RefractionPostProcess = RefractionPostProcess;
  17987. })(BABYLON || (BABYLON = {}));
  17988. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  17989. var BABYLON;
  17990. (function (BABYLON) {
  17991. var BlackAndWhitePostProcess = (function (_super) {
  17992. __extends(BlackAndWhitePostProcess, _super);
  17993. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17994. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  17995. }
  17996. return BlackAndWhitePostProcess;
  17997. })(BABYLON.PostProcess);
  17998. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  17999. })(BABYLON || (BABYLON = {}));
  18000. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  18001. var BABYLON;
  18002. (function (BABYLON) {
  18003. var ConvolutionPostProcess = (function (_super) {
  18004. __extends(ConvolutionPostProcess, _super);
  18005. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  18006. var _this = this;
  18007. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  18008. this.kernel = kernel;
  18009. this.onApply = function (effect) {
  18010. effect.setFloat2("screenSize", _this.width, _this.height);
  18011. effect.setArray("kernel", _this.kernel);
  18012. };
  18013. }
  18014. // Statics
  18015. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  18016. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  18017. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  18018. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  18019. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  18020. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  18021. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  18022. return ConvolutionPostProcess;
  18023. })(BABYLON.PostProcess);
  18024. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  18025. })(BABYLON || (BABYLON = {}));
  18026. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  18027. var BABYLON;
  18028. (function (BABYLON) {
  18029. var FxaaPostProcess = (function (_super) {
  18030. __extends(FxaaPostProcess, _super);
  18031. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  18032. var _this = this;
  18033. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  18034. this.onSizeChanged = function () {
  18035. _this.texelWidth = 1.0 / _this.width;
  18036. _this.texelHeight = 1.0 / _this.height;
  18037. };
  18038. this.onApply = function (effect) {
  18039. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  18040. };
  18041. }
  18042. return FxaaPostProcess;
  18043. })(BABYLON.PostProcess);
  18044. BABYLON.FxaaPostProcess = FxaaPostProcess;
  18045. })(BABYLON || (BABYLON = {}));
  18046. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  18047. (function (BABYLON) {
  18048. var LensFlare = (function () {
  18049. function LensFlare(size, position, color, imgUrl, system) {
  18050. this.size = size;
  18051. this.position = position;
  18052. this.dispose = function () {
  18053. if (this.texture) {
  18054. this.texture.dispose();
  18055. }
  18056. // Remove from scene
  18057. var index = this._system.lensFlares.indexOf(this);
  18058. this._system.lensFlares.splice(index, 1);
  18059. };
  18060. this.color = color || new BABYLON.Color3(1, 1, 1);
  18061. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  18062. this._system = system;
  18063. system.lensFlares.push(this);
  18064. }
  18065. return LensFlare;
  18066. })();
  18067. BABYLON.LensFlare = LensFlare;
  18068. })(BABYLON || (BABYLON = {}));
  18069. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  18070. (function (BABYLON) {
  18071. var LensFlareSystem = (function () {
  18072. function LensFlareSystem(name, emitter, scene) {
  18073. this.name = name;
  18074. this.lensFlares = new Array();
  18075. this.borderLimit = 300;
  18076. this._vertexDeclaration = [2];
  18077. this._vertexStrideSize = 2 * 4;
  18078. this._isEnabled = true;
  18079. this._scene = scene;
  18080. this._emitter = emitter;
  18081. scene.lensFlareSystems.push(this);
  18082. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  18083. // VBO
  18084. var vertices = [];
  18085. vertices.push(1, 1);
  18086. vertices.push(-1, 1);
  18087. vertices.push(-1, -1);
  18088. vertices.push(1, -1);
  18089. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  18090. // Indices
  18091. var indices = [];
  18092. indices.push(0);
  18093. indices.push(1);
  18094. indices.push(2);
  18095. indices.push(0);
  18096. indices.push(2);
  18097. indices.push(3);
  18098. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  18099. // Effects
  18100. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  18101. }
  18102. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  18103. get: function () {
  18104. return this._isEnabled;
  18105. },
  18106. set: function (value) {
  18107. this._isEnabled = value;
  18108. },
  18109. enumerable: true,
  18110. configurable: true
  18111. });
  18112. LensFlareSystem.prototype.getScene = function () {
  18113. return this._scene;
  18114. };
  18115. LensFlareSystem.prototype.getEmitter = function () {
  18116. return this._emitter;
  18117. };
  18118. LensFlareSystem.prototype.getEmitterPosition = function () {
  18119. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  18120. };
  18121. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  18122. var position = this.getEmitterPosition();
  18123. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  18124. this._positionX = position.x;
  18125. this._positionY = position.y;
  18126. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  18127. if (position.z > 0) {
  18128. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  18129. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  18130. return true;
  18131. }
  18132. }
  18133. return false;
  18134. };
  18135. LensFlareSystem.prototype._isVisible = function () {
  18136. if (!this._isEnabled) {
  18137. return false;
  18138. }
  18139. var emitterPosition = this.getEmitterPosition();
  18140. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  18141. var distance = direction.length();
  18142. direction.normalize();
  18143. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  18144. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  18145. return !pickInfo.hit || pickInfo.distance > distance;
  18146. };
  18147. LensFlareSystem.prototype.render = function () {
  18148. if (!this._effect.isReady())
  18149. return false;
  18150. var engine = this._scene.getEngine();
  18151. var viewport = this._scene.activeCamera.viewport;
  18152. var globalViewport = viewport.toGlobal(engine);
  18153. // Position
  18154. if (!this.computeEffectivePosition(globalViewport)) {
  18155. return false;
  18156. }
  18157. // Visibility
  18158. if (!this._isVisible()) {
  18159. return false;
  18160. }
  18161. // Intensity
  18162. var awayX;
  18163. var awayY;
  18164. if (this._positionX < this.borderLimit + globalViewport.x) {
  18165. awayX = this.borderLimit + globalViewport.x - this._positionX;
  18166. }
  18167. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  18168. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  18169. }
  18170. else {
  18171. awayX = 0;
  18172. }
  18173. if (this._positionY < this.borderLimit + globalViewport.y) {
  18174. awayY = this.borderLimit + globalViewport.y - this._positionY;
  18175. }
  18176. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  18177. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  18178. }
  18179. else {
  18180. awayY = 0;
  18181. }
  18182. var away = (awayX > awayY) ? awayX : awayY;
  18183. if (away > this.borderLimit) {
  18184. away = this.borderLimit;
  18185. }
  18186. var intensity = 1.0 - (away / this.borderLimit);
  18187. if (intensity < 0) {
  18188. return false;
  18189. }
  18190. if (intensity > 1.0) {
  18191. intensity = 1.0;
  18192. }
  18193. // Position
  18194. var centerX = globalViewport.x + globalViewport.width / 2;
  18195. var centerY = globalViewport.y + globalViewport.height / 2;
  18196. var distX = centerX - this._positionX;
  18197. var distY = centerY - this._positionY;
  18198. // Effects
  18199. engine.enableEffect(this._effect);
  18200. engine.setState(false);
  18201. engine.setDepthBuffer(false);
  18202. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  18203. // VBOs
  18204. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  18205. for (var index = 0; index < this.lensFlares.length; index++) {
  18206. var flare = this.lensFlares[index];
  18207. var x = centerX - (distX * flare.position);
  18208. var y = centerY - (distY * flare.position);
  18209. var cw = flare.size;
  18210. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  18211. var cx = 2 * (x / globalViewport.width) - 1.0;
  18212. var cy = 1.0 - 2 * (y / globalViewport.height);
  18213. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  18214. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  18215. // Texture
  18216. this._effect.setTexture("textureSampler", flare.texture);
  18217. // Color
  18218. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  18219. // Draw order
  18220. engine.draw(true, 0, 6);
  18221. }
  18222. engine.setDepthBuffer(true);
  18223. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18224. return true;
  18225. };
  18226. LensFlareSystem.prototype.dispose = function () {
  18227. if (this._vertexBuffer) {
  18228. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  18229. this._vertexBuffer = null;
  18230. }
  18231. if (this._indexBuffer) {
  18232. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  18233. this._indexBuffer = null;
  18234. }
  18235. while (this.lensFlares.length) {
  18236. this.lensFlares[0].dispose();
  18237. }
  18238. // Remove from scene
  18239. var index = this._scene.lensFlareSystems.indexOf(this);
  18240. this._scene.lensFlareSystems.splice(index, 1);
  18241. };
  18242. return LensFlareSystem;
  18243. })();
  18244. BABYLON.LensFlareSystem = LensFlareSystem;
  18245. })(BABYLON || (BABYLON = {}));
  18246. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  18247. (function (BABYLON) {
  18248. var IntersectionInfo = (function () {
  18249. function IntersectionInfo(bu, bv, distance) {
  18250. this.bu = bu;
  18251. this.bv = bv;
  18252. this.distance = distance;
  18253. this.faceId = 0;
  18254. this.subMeshId = 0;
  18255. }
  18256. return IntersectionInfo;
  18257. })();
  18258. BABYLON.IntersectionInfo = IntersectionInfo;
  18259. var PickingInfo = (function () {
  18260. function PickingInfo() {
  18261. this.hit = false;
  18262. this.distance = 0;
  18263. this.pickedPoint = null;
  18264. this.pickedMesh = null;
  18265. this.bu = 0;
  18266. this.bv = 0;
  18267. this.faceId = -1;
  18268. this.subMeshId = 0;
  18269. }
  18270. // Methods
  18271. PickingInfo.prototype.getNormal = function (useWorldCoordinates) {
  18272. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  18273. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18274. return null;
  18275. }
  18276. var indices = this.pickedMesh.getIndices();
  18277. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18278. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  18279. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  18280. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  18281. normal0 = normal0.scale(this.bu);
  18282. normal1 = normal1.scale(this.bv);
  18283. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  18284. var result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  18285. if (useWorldCoordinates) {
  18286. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  18287. }
  18288. return result;
  18289. };
  18290. PickingInfo.prototype.getTextureCoordinates = function () {
  18291. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18292. return null;
  18293. }
  18294. var indices = this.pickedMesh.getIndices();
  18295. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18296. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  18297. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  18298. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  18299. uv0 = uv0.scale(this.bu);
  18300. uv1 = uv1.scale(this.bv);
  18301. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  18302. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  18303. };
  18304. return PickingInfo;
  18305. })();
  18306. BABYLON.PickingInfo = PickingInfo;
  18307. })(BABYLON || (BABYLON = {}));
  18308. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  18309. (function (BABYLON) {
  18310. var FilesInput = (function () {
  18311. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  18312. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  18313. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  18314. this._engine = p_engine;
  18315. this._canvas = p_canvas;
  18316. this._currentScene = p_scene;
  18317. this._sceneLoadedCallback = p_sceneLoadedCallback;
  18318. this._progressCallback = p_progressCallback;
  18319. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  18320. this._textureLoadingCallback = p_textureLoadingCallback;
  18321. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  18322. }
  18323. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  18324. var _this = this;
  18325. if (p_elementToMonitor) {
  18326. this._elementToMonitor = p_elementToMonitor;
  18327. this._elementToMonitor.addEventListener("dragenter", function (e) {
  18328. _this.drag(e);
  18329. }, false);
  18330. this._elementToMonitor.addEventListener("dragover", function (e) {
  18331. _this.drag(e);
  18332. }, false);
  18333. this._elementToMonitor.addEventListener("drop", function (e) {
  18334. _this.drop(e);
  18335. }, false);
  18336. }
  18337. };
  18338. FilesInput.prototype.renderFunction = function () {
  18339. if (this._additionnalRenderLoopLogicCallback) {
  18340. this._additionnalRenderLoopLogicCallback();
  18341. }
  18342. if (this._currentScene) {
  18343. if (this._textureLoadingCallback) {
  18344. var remaining = this._currentScene.getWaitingItemsCount();
  18345. if (remaining > 0) {
  18346. this._textureLoadingCallback(remaining);
  18347. }
  18348. }
  18349. this._currentScene.render();
  18350. }
  18351. };
  18352. FilesInput.prototype.drag = function (e) {
  18353. e.stopPropagation();
  18354. e.preventDefault();
  18355. };
  18356. FilesInput.prototype.drop = function (eventDrop) {
  18357. eventDrop.stopPropagation();
  18358. eventDrop.preventDefault();
  18359. this.loadFiles(eventDrop);
  18360. };
  18361. FilesInput.prototype.loadFiles = function (event) {
  18362. if (this._startingProcessingFilesCallback)
  18363. this._startingProcessingFilesCallback();
  18364. // Handling data transfer via drag'n'drop
  18365. if (event && event.dataTransfer && event.dataTransfer.files) {
  18366. this._filesToLoad = event.dataTransfer.files;
  18367. }
  18368. // Handling files from input files
  18369. if (event && event.target && event.target.files) {
  18370. this._filesToLoad = event.target.files;
  18371. }
  18372. if (this._filesToLoad && this._filesToLoad.length > 0) {
  18373. for (var i = 0; i < this._filesToLoad.length; i++) {
  18374. switch (this._filesToLoad[i].type) {
  18375. case "image/jpeg":
  18376. case "image/png":
  18377. case "image/bmp":
  18378. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  18379. break;
  18380. case "image/targa":
  18381. case "image/vnd.ms-dds":
  18382. case "audio/wav":
  18383. case "audio/x-wav":
  18384. case "audio/mp3":
  18385. case "audio/mpeg":
  18386. case "audio/mpeg3":
  18387. case "audio/x-mpeg-3":
  18388. case "audio/ogg":
  18389. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  18390. break;
  18391. default:
  18392. 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) {
  18393. this._sceneFileToLoad = this._filesToLoad[i];
  18394. }
  18395. break;
  18396. }
  18397. }
  18398. this.reload();
  18399. }
  18400. };
  18401. FilesInput.prototype.reload = function () {
  18402. var _this = this;
  18403. var that = this;
  18404. // If a ".babylon" file has been provided
  18405. if (this._sceneFileToLoad) {
  18406. if (this._currentScene) {
  18407. this._engine.stopRenderLoop();
  18408. this._currentScene.dispose();
  18409. }
  18410. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  18411. that._currentScene = newScene;
  18412. // Wait for textures and shaders to be ready
  18413. that._currentScene.executeWhenReady(function () {
  18414. // Attach camera to canvas inputs
  18415. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  18416. that._currentScene.createDefaultCameraOrLight();
  18417. }
  18418. that._currentScene.activeCamera.attachControl(that._canvas);
  18419. if (that._sceneLoadedCallback) {
  18420. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  18421. }
  18422. that._engine.runRenderLoop(function () {
  18423. that.renderFunction();
  18424. });
  18425. });
  18426. }, function (progress) {
  18427. if (_this._progressCallback) {
  18428. _this._progressCallback(progress);
  18429. }
  18430. });
  18431. }
  18432. else {
  18433. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  18434. }
  18435. };
  18436. FilesInput.FilesTextures = new Array();
  18437. FilesInput.FilesToLoad = new Array();
  18438. return FilesInput;
  18439. })();
  18440. BABYLON.FilesInput = FilesInput;
  18441. })(BABYLON || (BABYLON = {}));
  18442. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  18443. (function (BABYLON) {
  18444. var OimoJSPlugin = (function () {
  18445. function OimoJSPlugin() {
  18446. this._registeredMeshes = [];
  18447. /**
  18448. * Update the body position according to the mesh position
  18449. * @param mesh
  18450. */
  18451. this.updateBodyPosition = function (mesh) {
  18452. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18453. var registeredMesh = this._registeredMeshes[index];
  18454. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18455. var body = registeredMesh.body.body;
  18456. mesh.computeWorldMatrix(true);
  18457. var center = mesh.getBoundingInfo().boundingBox.center;
  18458. body.setPosition(center.x, center.y, center.z);
  18459. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  18460. return;
  18461. }
  18462. // Case where the parent has been updated
  18463. if (registeredMesh.mesh.parent === mesh) {
  18464. mesh.computeWorldMatrix(true);
  18465. registeredMesh.mesh.computeWorldMatrix(true);
  18466. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  18467. var absoluteRotation = mesh.rotation;
  18468. body = registeredMesh.body.body;
  18469. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  18470. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  18471. return;
  18472. }
  18473. }
  18474. };
  18475. }
  18476. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  18477. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  18478. };
  18479. OimoJSPlugin.prototype.initialize = function (iterations) {
  18480. this._world = new OIMO.World();
  18481. this._world.clear();
  18482. };
  18483. OimoJSPlugin.prototype.setGravity = function (gravity) {
  18484. this._world.gravity = gravity;
  18485. };
  18486. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  18487. var body = null;
  18488. this.unregisterMesh(mesh);
  18489. mesh.computeWorldMatrix(true);
  18490. var initialRotation = null;
  18491. if (mesh.rotationQuaternion) {
  18492. initialRotation = mesh.rotationQuaternion.clone();
  18493. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18494. mesh.computeWorldMatrix(true);
  18495. }
  18496. var bbox = mesh.getBoundingInfo().boundingBox;
  18497. // The delta between the mesh position and the mesh bounding box center
  18498. var deltaPosition = mesh.position.subtract(bbox.center);
  18499. // Transform delta position with the rotation
  18500. if (initialRotation) {
  18501. var m = new BABYLON.Matrix();
  18502. initialRotation.toRotationMatrix(m);
  18503. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  18504. }
  18505. switch (impostor) {
  18506. case BABYLON.PhysicsEngine.SphereImpostor:
  18507. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18508. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18509. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18510. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  18511. body = new OIMO.Body({
  18512. type: 'sphere',
  18513. size: [size],
  18514. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  18515. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  18516. move: options.mass != 0,
  18517. config: [options.mass, options.friction, options.restitution],
  18518. world: this._world
  18519. });
  18520. break;
  18521. case BABYLON.PhysicsEngine.PlaneImpostor:
  18522. case BABYLON.PhysicsEngine.CylinderImpostor:
  18523. case BABYLON.PhysicsEngine.BoxImpostor:
  18524. var min = bbox.minimumWorld;
  18525. var max = bbox.maximumWorld;
  18526. var box = max.subtract(min);
  18527. var sizeX = this._checkWithEpsilon(box.x);
  18528. var sizeY = this._checkWithEpsilon(box.y);
  18529. var sizeZ = this._checkWithEpsilon(box.z);
  18530. body = new OIMO.Body({
  18531. type: 'box',
  18532. size: [sizeX, sizeY, sizeZ],
  18533. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  18534. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  18535. move: options.mass != 0,
  18536. config: [options.mass, options.friction, options.restitution],
  18537. world: this._world
  18538. });
  18539. break;
  18540. }
  18541. //If quaternion was set as the rotation of the object
  18542. if (initialRotation) {
  18543. //We have to access the rigid body's properties to set the quaternion.
  18544. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  18545. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  18546. //update the internal rotation matrix
  18547. body.body.syncShapes();
  18548. }
  18549. this._registeredMeshes.push({
  18550. mesh: mesh,
  18551. body: body,
  18552. delta: deltaPosition
  18553. });
  18554. return body;
  18555. };
  18556. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  18557. var types = [], sizes = [], positions = [], rotations = [];
  18558. var initialMesh = parts[0].mesh;
  18559. for (var index = 0; index < parts.length; index++) {
  18560. var part = parts[index];
  18561. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  18562. types.push(bodyParameters.type);
  18563. sizes.push.apply(sizes, bodyParameters.size);
  18564. positions.push.apply(positions, bodyParameters.pos);
  18565. rotations.push.apply(rotations, bodyParameters.rot);
  18566. }
  18567. var body = new OIMO.Body({
  18568. type: types,
  18569. size: sizes,
  18570. pos: positions,
  18571. rot: rotations,
  18572. move: options.mass != 0,
  18573. config: [options.mass, options.friction, options.restitution],
  18574. world: this._world
  18575. });
  18576. this._registeredMeshes.push({
  18577. mesh: initialMesh,
  18578. body: body
  18579. });
  18580. return body;
  18581. };
  18582. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  18583. var bodyParameters = null;
  18584. var mesh = part.mesh;
  18585. // We need the bounding box/sphere info to compute the physics body
  18586. mesh.computeWorldMatrix();
  18587. switch (part.impostor) {
  18588. case BABYLON.PhysicsEngine.SphereImpostor:
  18589. var bbox = mesh.getBoundingInfo().boundingBox;
  18590. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18591. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18592. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18593. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  18594. bodyParameters = {
  18595. type: 'sphere',
  18596. /* bug with oimo : sphere needs 3 sizes in this case */
  18597. size: [size, -1, -1],
  18598. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  18599. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  18600. };
  18601. break;
  18602. case BABYLON.PhysicsEngine.PlaneImpostor:
  18603. case BABYLON.PhysicsEngine.BoxImpostor:
  18604. bbox = mesh.getBoundingInfo().boundingBox;
  18605. var min = bbox.minimumWorld;
  18606. var max = bbox.maximumWorld;
  18607. var box = max.subtract(min);
  18608. var sizeX = this._checkWithEpsilon(box.x);
  18609. var sizeY = this._checkWithEpsilon(box.y);
  18610. var sizeZ = this._checkWithEpsilon(box.z);
  18611. var relativePosition = mesh.position;
  18612. bodyParameters = {
  18613. type: 'box',
  18614. size: [sizeX, sizeY, sizeZ],
  18615. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  18616. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  18617. };
  18618. break;
  18619. }
  18620. return bodyParameters;
  18621. };
  18622. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  18623. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18624. var registeredMesh = this._registeredMeshes[index];
  18625. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18626. if (registeredMesh.body) {
  18627. this._world.removeRigidBody(registeredMesh.body.body);
  18628. this._unbindBody(registeredMesh.body);
  18629. }
  18630. this._registeredMeshes.splice(index, 1);
  18631. return;
  18632. }
  18633. }
  18634. };
  18635. OimoJSPlugin.prototype._unbindBody = function (body) {
  18636. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18637. var registeredMesh = this._registeredMeshes[index];
  18638. if (registeredMesh.body === body) {
  18639. registeredMesh.body = null;
  18640. }
  18641. }
  18642. };
  18643. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  18644. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18645. var registeredMesh = this._registeredMeshes[index];
  18646. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18647. // Get object mass to have a behaviour similar to cannon.js
  18648. var mass = registeredMesh.body.body.massInfo.mass;
  18649. // The force is scaled with the mass of object
  18650. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  18651. return;
  18652. }
  18653. }
  18654. };
  18655. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  18656. var body1 = null, body2 = null;
  18657. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18658. var registeredMesh = this._registeredMeshes[index];
  18659. if (registeredMesh.mesh === mesh1) {
  18660. body1 = registeredMesh.body.body;
  18661. }
  18662. else if (registeredMesh.mesh === mesh2) {
  18663. body2 = registeredMesh.body.body;
  18664. }
  18665. }
  18666. if (!body1 || !body2) {
  18667. return false;
  18668. }
  18669. if (!options) {
  18670. options = {};
  18671. }
  18672. new OIMO.Link({
  18673. type: options.type,
  18674. body1: body1,
  18675. body2: body2,
  18676. min: options.min,
  18677. max: options.max,
  18678. axe1: options.axe1,
  18679. axe2: options.axe2,
  18680. pos1: [pivot1.x, pivot1.y, pivot1.z],
  18681. pos2: [pivot2.x, pivot2.y, pivot2.z],
  18682. collision: options.collision,
  18683. spring: options.spring,
  18684. world: this._world
  18685. });
  18686. return true;
  18687. };
  18688. OimoJSPlugin.prototype.dispose = function () {
  18689. this._world.clear();
  18690. while (this._registeredMeshes.length) {
  18691. this.unregisterMesh(this._registeredMeshes[0].mesh);
  18692. }
  18693. };
  18694. OimoJSPlugin.prototype.isSupported = function () {
  18695. return OIMO !== undefined;
  18696. };
  18697. OimoJSPlugin.prototype._getLastShape = function (body) {
  18698. var lastShape = body.shapes;
  18699. while (lastShape.next) {
  18700. lastShape = lastShape.next;
  18701. }
  18702. return lastShape;
  18703. };
  18704. OimoJSPlugin.prototype.runOneStep = function (time) {
  18705. this._world.step();
  18706. // Update the position of all registered meshes
  18707. var i = this._registeredMeshes.length;
  18708. var m;
  18709. while (i--) {
  18710. var body = this._registeredMeshes[i].body.body;
  18711. var mesh = this._registeredMeshes[i].mesh;
  18712. var delta = this._registeredMeshes[i].delta;
  18713. if (!body.sleeping) {
  18714. if (body.shapes.next) {
  18715. var parentShape = this._getLastShape(body);
  18716. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  18717. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  18718. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  18719. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  18720. if (!mesh.rotationQuaternion) {
  18721. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18722. }
  18723. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  18724. mesh.computeWorldMatrix();
  18725. }
  18726. else {
  18727. m = body.getMatrix();
  18728. mtx = BABYLON.Matrix.FromArray(m);
  18729. // Body position
  18730. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  18731. if (!delta) {
  18732. mesh.position.x = bodyX;
  18733. mesh.position.y = bodyY;
  18734. mesh.position.z = bodyZ;
  18735. }
  18736. else {
  18737. mesh.position.x = bodyX + delta.x;
  18738. mesh.position.y = bodyY + delta.y;
  18739. mesh.position.z = bodyZ + delta.z;
  18740. }
  18741. if (!mesh.rotationQuaternion) {
  18742. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18743. }
  18744. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  18745. mesh.computeWorldMatrix();
  18746. }
  18747. }
  18748. }
  18749. };
  18750. return OimoJSPlugin;
  18751. })();
  18752. BABYLON.OimoJSPlugin = OimoJSPlugin;
  18753. })(BABYLON || (BABYLON = {}));
  18754. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  18755. (function (BABYLON) {
  18756. var PhysicsEngine = (function () {
  18757. function PhysicsEngine(plugin) {
  18758. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  18759. }
  18760. PhysicsEngine.prototype._initialize = function (gravity) {
  18761. this._currentPlugin.initialize();
  18762. this._setGravity(gravity);
  18763. };
  18764. PhysicsEngine.prototype._runOneStep = function (delta) {
  18765. if (delta > 0.1) {
  18766. delta = 0.1;
  18767. }
  18768. else if (delta <= 0) {
  18769. delta = 1.0 / 60.0;
  18770. }
  18771. this._currentPlugin.runOneStep(delta);
  18772. };
  18773. PhysicsEngine.prototype._setGravity = function (gravity) {
  18774. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  18775. this._currentPlugin.setGravity(this.gravity);
  18776. };
  18777. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  18778. return this._currentPlugin.registerMesh(mesh, impostor, options);
  18779. };
  18780. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  18781. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  18782. };
  18783. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  18784. this._currentPlugin.unregisterMesh(mesh);
  18785. };
  18786. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  18787. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  18788. };
  18789. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  18790. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  18791. };
  18792. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  18793. this._currentPlugin.updateBodyPosition(mesh);
  18794. };
  18795. PhysicsEngine.prototype.dispose = function () {
  18796. this._currentPlugin.dispose();
  18797. };
  18798. PhysicsEngine.prototype.isSupported = function () {
  18799. return this._currentPlugin.isSupported();
  18800. };
  18801. // Statics
  18802. PhysicsEngine.NoImpostor = 0;
  18803. PhysicsEngine.SphereImpostor = 1;
  18804. PhysicsEngine.BoxImpostor = 2;
  18805. PhysicsEngine.PlaneImpostor = 3;
  18806. PhysicsEngine.MeshImpostor = 4;
  18807. PhysicsEngine.CapsuleImpostor = 5;
  18808. PhysicsEngine.ConeImpostor = 6;
  18809. PhysicsEngine.CylinderImpostor = 7;
  18810. PhysicsEngine.ConvexHullImpostor = 8;
  18811. PhysicsEngine.Epsilon = 0.001;
  18812. return PhysicsEngine;
  18813. })();
  18814. BABYLON.PhysicsEngine = PhysicsEngine;
  18815. })(BABYLON || (BABYLON = {}));
  18816. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  18817. (function (BABYLON) {
  18818. var serializeLight = function (light) {
  18819. var serializationObject = {};
  18820. serializationObject.name = light.name;
  18821. serializationObject.id = light.id;
  18822. serializationObject.tags = BABYLON.Tags.GetTags(light);
  18823. if (light instanceof BABYLON.PointLight) {
  18824. serializationObject.type = 0;
  18825. serializationObject.position = light.position.asArray();
  18826. }
  18827. else if (light instanceof BABYLON.DirectionalLight) {
  18828. serializationObject.type = 1;
  18829. var directionalLight = light;
  18830. serializationObject.position = directionalLight.position.asArray();
  18831. serializationObject.direction = directionalLight.direction.asArray();
  18832. }
  18833. else if (light instanceof BABYLON.SpotLight) {
  18834. serializationObject.type = 2;
  18835. var spotLight = light;
  18836. serializationObject.position = spotLight.position.asArray();
  18837. serializationObject.direction = spotLight.position.asArray();
  18838. serializationObject.angle = spotLight.angle;
  18839. serializationObject.exponent = spotLight.exponent;
  18840. }
  18841. else if (light instanceof BABYLON.HemisphericLight) {
  18842. serializationObject.type = 3;
  18843. var hemisphericLight = light;
  18844. serializationObject.direction = hemisphericLight.direction.asArray();
  18845. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  18846. }
  18847. if (light.intensity) {
  18848. serializationObject.intensity = light.intensity;
  18849. }
  18850. serializationObject.range = light.range;
  18851. serializationObject.diffuse = light.diffuse.asArray();
  18852. serializationObject.specular = light.specular.asArray();
  18853. return serializationObject;
  18854. };
  18855. var serializeFresnelParameter = function (fresnelParameter) {
  18856. var serializationObject = {};
  18857. serializationObject.isEnabled = fresnelParameter.isEnabled;
  18858. serializationObject.leftColor = fresnelParameter.leftColor;
  18859. serializationObject.rightColor = fresnelParameter.rightColor;
  18860. serializationObject.bias = fresnelParameter.bias;
  18861. serializationObject.power = fresnelParameter.power;
  18862. return serializationObject;
  18863. };
  18864. var appendAnimations = function (source, destination) {
  18865. if (source.animations) {
  18866. destination.animations = [];
  18867. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  18868. var animation = source.animations[animationIndex];
  18869. destination.animations.push(serializeAnimation(animation));
  18870. }
  18871. }
  18872. };
  18873. var serializeCamera = function (camera) {
  18874. var serializationObject = {};
  18875. serializationObject.name = camera.name;
  18876. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  18877. serializationObject.id = camera.id;
  18878. serializationObject.position = camera.position.asArray();
  18879. // Parent
  18880. if (camera.parent) {
  18881. serializationObject.parentId = camera.parent.id;
  18882. }
  18883. serializationObject.fov = camera.fov;
  18884. serializationObject.minZ = camera.minZ;
  18885. serializationObject.maxZ = camera.maxZ;
  18886. serializationObject.inertia = camera.inertia;
  18887. //setting the type
  18888. if (camera instanceof BABYLON.FreeCamera) {
  18889. serializationObject.type = "FreeCamera";
  18890. }
  18891. else if (camera instanceof BABYLON.ArcRotateCamera) {
  18892. serializationObject.type = "ArcRotateCamera";
  18893. }
  18894. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18895. serializationObject.type = "AnaglyphArcRotateCamera";
  18896. }
  18897. else if (camera instanceof BABYLON.GamepadCamera) {
  18898. serializationObject.type = "GamepadCamera";
  18899. }
  18900. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  18901. serializationObject.type = "AnaglyphFreeCamera";
  18902. }
  18903. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  18904. serializationObject.type = "DeviceOrientationCamera";
  18905. }
  18906. else if (camera instanceof BABYLON.FollowCamera) {
  18907. serializationObject.type = "FollowCamera";
  18908. }
  18909. else if (camera instanceof BABYLON.OculusCamera) {
  18910. serializationObject.type = "OculusCamera";
  18911. }
  18912. else if (camera instanceof BABYLON.OculusGamepadCamera) {
  18913. serializationObject.type = "OculusGamepadCamera";
  18914. }
  18915. else if (camera instanceof BABYLON.TouchCamera) {
  18916. serializationObject.type = "TouchCamera";
  18917. }
  18918. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  18919. serializationObject.type = "VirtualJoysticksCamera";
  18920. }
  18921. else if (camera instanceof BABYLON.WebVRCamera) {
  18922. serializationObject.type = "WebVRCamera";
  18923. }
  18924. else if (camera instanceof BABYLON.VRDeviceOrientationCamera) {
  18925. serializationObject.type = "VRDeviceOrientationCamera";
  18926. }
  18927. //special properties of specific cameras
  18928. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18929. var arcCamera = camera;
  18930. serializationObject.alpha = arcCamera.alpha;
  18931. serializationObject.beta = arcCamera.beta;
  18932. serializationObject.radius = arcCamera.radius;
  18933. if (arcCamera.target && arcCamera.target.id) {
  18934. serializationObject.lockedTargetId = arcCamera.target.id;
  18935. }
  18936. }
  18937. else if (camera instanceof BABYLON.FollowCamera) {
  18938. var followCam = camera;
  18939. serializationObject.radius = followCam.radius;
  18940. serializationObject.heightOffset = followCam.heightOffset;
  18941. serializationObject.rotationOffset = followCam.rotationOffset;
  18942. }
  18943. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18944. //eye space is a private member and can only be access like this. Without changing the implementation this is the best way to get it.
  18945. if (camera['_eyeSpace'] !== undefined) {
  18946. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  18947. }
  18948. }
  18949. //general properties that not all cameras have. The [] is due to typescript's type safety
  18950. if (camera['speed'] !== undefined) {
  18951. serializationObject.speed = camera['speed'];
  18952. }
  18953. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  18954. serializationObject.target = camera['target'].asArray();
  18955. }
  18956. // Target
  18957. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  18958. serializationObject.rotation = camera['rotation'].asArray();
  18959. }
  18960. // Locked target
  18961. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  18962. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  18963. }
  18964. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  18965. serializationObject.applyGravity = camera['applyGravity'] || false;
  18966. if (camera['ellipsoid']) {
  18967. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  18968. }
  18969. // Animations
  18970. appendAnimations(camera, serializationObject);
  18971. // Layer mask
  18972. serializationObject.layerMask = camera.layerMask;
  18973. return serializationObject;
  18974. };
  18975. var serializeAnimation = function (animation) {
  18976. var serializationObject = {};
  18977. serializationObject.name = animation.name;
  18978. serializationObject.property = animation.targetProperty;
  18979. serializationObject.framePerSecond = animation.framePerSecond;
  18980. serializationObject.dataType = animation.dataType;
  18981. serializationObject.loopBehavior = animation.loopMode;
  18982. var dataType = animation.dataType;
  18983. serializationObject.keys = [];
  18984. var keys = animation.getKeys();
  18985. for (var index = 0; index < keys.length; index++) {
  18986. var animationKey = keys[index];
  18987. var key = {};
  18988. key.frame = animationKey.frame;
  18989. switch (dataType) {
  18990. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18991. key.values = [animationKey.value];
  18992. break;
  18993. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18994. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18995. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18996. key.values = animationKey.value.asArray();
  18997. break;
  18998. }
  18999. serializationObject.keys.push(key);
  19000. }
  19001. return serializationObject;
  19002. };
  19003. var serializeMultiMaterial = function (material) {
  19004. var serializationObject = {};
  19005. serializationObject.name = material.name;
  19006. serializationObject.id = material.id;
  19007. serializationObject.tags = BABYLON.Tags.GetTags(material);
  19008. serializationObject.materials = [];
  19009. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  19010. var subMat = material.subMaterials[matIndex];
  19011. if (subMat) {
  19012. serializationObject.materials.push(subMat.id);
  19013. }
  19014. else {
  19015. serializationObject.materials.push(null);
  19016. }
  19017. }
  19018. return serializationObject;
  19019. };
  19020. var serializeMaterial = function (material) {
  19021. var serializationObject = {};
  19022. serializationObject.name = material.name;
  19023. serializationObject.ambient = material.ambientColor.asArray();
  19024. serializationObject.diffuse = material.diffuseColor.asArray();
  19025. serializationObject.specular = material.specularColor.asArray();
  19026. serializationObject.specularPower = material.specularPower;
  19027. serializationObject.emissive = material.emissiveColor.asArray();
  19028. serializationObject.alpha = material.alpha;
  19029. serializationObject.id = material.id;
  19030. serializationObject.tags = BABYLON.Tags.GetTags(material);
  19031. serializationObject.backFaceCulling = material.backFaceCulling;
  19032. if (material.diffuseTexture) {
  19033. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  19034. }
  19035. if (material.diffuseFresnelParameters) {
  19036. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  19037. }
  19038. if (material.ambientTexture) {
  19039. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  19040. }
  19041. if (material.opacityTexture) {
  19042. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  19043. }
  19044. if (material.opacityFresnelParameters) {
  19045. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  19046. }
  19047. if (material.reflectionTexture) {
  19048. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  19049. }
  19050. if (material.reflectionFresnelParameters) {
  19051. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  19052. }
  19053. if (material.emissiveTexture) {
  19054. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  19055. }
  19056. if (material.emissiveFresnelParameters) {
  19057. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  19058. }
  19059. if (material.specularTexture) {
  19060. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  19061. }
  19062. if (material.bumpTexture) {
  19063. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  19064. }
  19065. return serializationObject;
  19066. };
  19067. var serializeTexture = function (texture) {
  19068. var serializationObject = {};
  19069. if (!texture.name) {
  19070. return null;
  19071. }
  19072. if (texture instanceof BABYLON.CubeTexture) {
  19073. serializationObject.name = texture.name;
  19074. serializationObject.hasAlpha = texture.hasAlpha;
  19075. serializationObject.level = texture.level;
  19076. serializationObject.coordinatesMode = texture.coordinatesMode;
  19077. return serializationObject;
  19078. }
  19079. if (texture instanceof BABYLON.MirrorTexture) {
  19080. var mirrorTexture = texture;
  19081. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  19082. serializationObject.renderList = [];
  19083. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  19084. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  19085. }
  19086. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  19087. }
  19088. else if (texture instanceof BABYLON.RenderTargetTexture) {
  19089. var renderTargetTexture = texture;
  19090. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  19091. serializationObject.renderList = [];
  19092. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  19093. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  19094. }
  19095. }
  19096. var regularTexture = texture;
  19097. serializationObject.name = texture.name;
  19098. serializationObject.hasAlpha = texture.hasAlpha;
  19099. serializationObject.level = texture.level;
  19100. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  19101. serializationObject.coordinatesMode = texture.coordinatesMode;
  19102. serializationObject.uOffset = regularTexture.uOffset;
  19103. serializationObject.vOffset = regularTexture.vOffset;
  19104. serializationObject.uScale = regularTexture.uScale;
  19105. serializationObject.vScale = regularTexture.vScale;
  19106. serializationObject.uAng = regularTexture.uAng;
  19107. serializationObject.vAng = regularTexture.vAng;
  19108. serializationObject.wAng = regularTexture.wAng;
  19109. serializationObject.wrapU = texture.wrapU;
  19110. serializationObject.wrapV = texture.wrapV;
  19111. // Animations
  19112. appendAnimations(texture, serializationObject);
  19113. return serializationObject;
  19114. };
  19115. var serializeSkeleton = function (skeleton) {
  19116. var serializationObject = {};
  19117. serializationObject.name = skeleton.name;
  19118. serializationObject.id = skeleton.id;
  19119. serializationObject.bones = [];
  19120. for (var index = 0; index < skeleton.bones.length; index++) {
  19121. var bone = skeleton.bones[index];
  19122. var serializedBone = {
  19123. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  19124. name: bone.name,
  19125. matrix: bone.getLocalMatrix().toArray()
  19126. };
  19127. serializationObject.bones.push(serializedBone);
  19128. if (bone.animations && bone.animations.length > 0) {
  19129. serializedBone.animation = serializeAnimation(bone.animations[0]);
  19130. }
  19131. }
  19132. return serializationObject;
  19133. };
  19134. var serializeParticleSystem = function (particleSystem) {
  19135. var serializationObject = {};
  19136. serializationObject.emitterId = particleSystem.emitter.id;
  19137. serializationObject.capacity = particleSystem.getCapacity();
  19138. if (particleSystem.particleTexture) {
  19139. serializationObject.textureName = particleSystem.particleTexture.name;
  19140. }
  19141. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  19142. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  19143. serializationObject.minSize = particleSystem.minSize;
  19144. serializationObject.maxSize = particleSystem.maxSize;
  19145. serializationObject.minLifeTime = particleSystem.minLifeTime;
  19146. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  19147. serializationObject.emitRate = particleSystem.emitRate;
  19148. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  19149. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  19150. serializationObject.gravity = particleSystem.gravity.asArray();
  19151. serializationObject.direction1 = particleSystem.direction1.asArray();
  19152. serializationObject.direction2 = particleSystem.direction2.asArray();
  19153. serializationObject.color1 = particleSystem.color1.asArray();
  19154. serializationObject.color2 = particleSystem.color2.asArray();
  19155. serializationObject.colorDead = particleSystem.colorDead.asArray();
  19156. serializationObject.updateSpeed = particleSystem.updateSpeed;
  19157. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  19158. serializationObject.textureMask = particleSystem.textureMask.asArray();
  19159. serializationObject.blendMode = particleSystem.blendMode;
  19160. return serializationObject;
  19161. };
  19162. var serializeLensFlareSystem = function (lensFlareSystem) {
  19163. var serializationObject = {};
  19164. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  19165. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  19166. serializationObject.flares = [];
  19167. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  19168. var flare = lensFlareSystem.lensFlares[index];
  19169. serializationObject.flares.push({
  19170. size: flare.size,
  19171. position: flare.position,
  19172. color: flare.color.asArray(),
  19173. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  19174. });
  19175. }
  19176. return serializationObject;
  19177. };
  19178. var serializeShadowGenerator = function (light) {
  19179. var serializationObject = {};
  19180. var shadowGenerator = light.getShadowGenerator();
  19181. serializationObject.lightId = light.id;
  19182. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  19183. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  19184. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  19185. serializationObject.renderList = [];
  19186. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  19187. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  19188. serializationObject.renderList.push(mesh.id);
  19189. }
  19190. return serializationObject;
  19191. };
  19192. var serializedGeometries = [];
  19193. var serializeGeometry = function (geometry, serializationGeometries) {
  19194. if (serializedGeometries[geometry.id]) {
  19195. return;
  19196. }
  19197. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  19198. serializationGeometries.boxes.push(serializeBox(geometry));
  19199. }
  19200. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  19201. serializationGeometries.spheres.push(serializeSphere(geometry));
  19202. }
  19203. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  19204. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  19205. }
  19206. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  19207. serializationGeometries.toruses.push(serializeTorus(geometry));
  19208. }
  19209. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  19210. serializationGeometries.grounds.push(serializeGround(geometry));
  19211. }
  19212. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  19213. serializationGeometries.planes.push(serializePlane(geometry));
  19214. }
  19215. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  19216. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  19217. }
  19218. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  19219. throw new Error("Unknow primitive type");
  19220. }
  19221. else {
  19222. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  19223. }
  19224. serializedGeometries[geometry.id] = true;
  19225. };
  19226. var serializeGeometryBase = function (geometry) {
  19227. var serializationObject = {};
  19228. serializationObject.id = geometry.id;
  19229. if (BABYLON.Tags.HasTags(geometry)) {
  19230. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  19231. }
  19232. return serializationObject;
  19233. };
  19234. var serializeVertexData = function (vertexData) {
  19235. var serializationObject = serializeGeometryBase(vertexData);
  19236. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19237. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19238. }
  19239. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19240. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19241. }
  19242. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19243. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19244. }
  19245. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19246. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  19247. }
  19248. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19249. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  19250. }
  19251. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  19252. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  19253. serializationObject.matricesIndices._isExpanded = true;
  19254. }
  19255. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19256. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  19257. }
  19258. serializationObject.indices = vertexData.getIndices();
  19259. return serializationObject;
  19260. };
  19261. var serializePrimitive = function (primitive) {
  19262. var serializationObject = serializeGeometryBase(primitive);
  19263. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  19264. return serializationObject;
  19265. };
  19266. var serializeBox = function (box) {
  19267. var serializationObject = serializePrimitive(box);
  19268. serializationObject.size = box.size;
  19269. return serializationObject;
  19270. };
  19271. var serializeSphere = function (sphere) {
  19272. var serializationObject = serializePrimitive(sphere);
  19273. serializationObject.segments = sphere.segments;
  19274. serializationObject.diameter = sphere.diameter;
  19275. return serializationObject;
  19276. };
  19277. var serializeCylinder = function (cylinder) {
  19278. var serializationObject = serializePrimitive(cylinder);
  19279. serializationObject.height = cylinder.height;
  19280. serializationObject.diameterTop = cylinder.diameterTop;
  19281. serializationObject.diameterBottom = cylinder.diameterBottom;
  19282. serializationObject.tessellation = cylinder.tessellation;
  19283. return serializationObject;
  19284. };
  19285. var serializeTorus = function (torus) {
  19286. var serializationObject = serializePrimitive(torus);
  19287. serializationObject.diameter = torus.diameter;
  19288. serializationObject.thickness = torus.thickness;
  19289. serializationObject.tessellation = torus.tessellation;
  19290. return serializationObject;
  19291. };
  19292. var serializeGround = function (ground) {
  19293. var serializationObject = serializePrimitive(ground);
  19294. serializationObject.width = ground.width;
  19295. serializationObject.height = ground.height;
  19296. serializationObject.subdivisions = ground.subdivisions;
  19297. return serializationObject;
  19298. };
  19299. var serializePlane = function (plane) {
  19300. var serializationObject = serializePrimitive(plane);
  19301. serializationObject.size = plane.size;
  19302. return serializationObject;
  19303. };
  19304. var serializeTorusKnot = function (torusKnot) {
  19305. var serializationObject = serializePrimitive(torusKnot);
  19306. serializationObject.radius = torusKnot.radius;
  19307. serializationObject.tube = torusKnot.tube;
  19308. serializationObject.radialSegments = torusKnot.radialSegments;
  19309. serializationObject.tubularSegments = torusKnot.tubularSegments;
  19310. serializationObject.p = torusKnot.p;
  19311. serializationObject.q = torusKnot.q;
  19312. return serializationObject;
  19313. };
  19314. var serializeMesh = function (mesh, serializationScene) {
  19315. var serializationObject = {};
  19316. serializationObject.name = mesh.name;
  19317. serializationObject.id = mesh.id;
  19318. if (BABYLON.Tags.HasTags(mesh)) {
  19319. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  19320. }
  19321. serializationObject.position = mesh.position.asArray();
  19322. if (mesh.rotationQuaternion) {
  19323. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  19324. }
  19325. else if (mesh.rotation) {
  19326. serializationObject.rotation = mesh.rotation.asArray();
  19327. }
  19328. serializationObject.scaling = mesh.scaling.asArray();
  19329. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  19330. serializationObject.isEnabled = mesh.isEnabled();
  19331. serializationObject.isVisible = mesh.isVisible;
  19332. serializationObject.infiniteDistance = mesh.infiniteDistance;
  19333. serializationObject.pickable = mesh.isPickable;
  19334. serializationObject.receiveShadows = mesh.receiveShadows;
  19335. serializationObject.billboardMode = mesh.billboardMode;
  19336. serializationObject.visibility = mesh.visibility;
  19337. serializationObject.checkCollisions = mesh.checkCollisions;
  19338. // Parent
  19339. if (mesh.parent) {
  19340. serializationObject.parentId = mesh.parent.id;
  19341. }
  19342. // Geometry
  19343. var geometry = mesh._geometry;
  19344. if (geometry) {
  19345. var geometryId = geometry.id;
  19346. serializationObject.geometryId = geometryId;
  19347. if (!mesh.getScene().getGeometryByID(geometryId)) {
  19348. // 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
  19349. serializeGeometry(geometry, serializationScene.geometries);
  19350. }
  19351. // SubMeshes
  19352. serializationObject.subMeshes = [];
  19353. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  19354. var subMesh = mesh.subMeshes[subIndex];
  19355. serializationObject.subMeshes.push({
  19356. materialIndex: subMesh.materialIndex,
  19357. verticesStart: subMesh.verticesStart,
  19358. verticesCount: subMesh.verticesCount,
  19359. indexStart: subMesh.indexStart,
  19360. indexCount: subMesh.indexCount
  19361. });
  19362. }
  19363. }
  19364. // Material
  19365. if (mesh.material) {
  19366. serializationObject.materialId = mesh.material.id;
  19367. }
  19368. else {
  19369. mesh.material = null;
  19370. }
  19371. // Skeleton
  19372. if (mesh.skeleton) {
  19373. serializationObject.skeletonId = mesh.skeleton.id;
  19374. }
  19375. // Physics
  19376. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  19377. serializationObject.physicsMass = mesh.getPhysicsMass();
  19378. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  19379. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  19380. switch (mesh.getPhysicsImpostor()) {
  19381. case BABYLON.PhysicsEngine.BoxImpostor:
  19382. serializationObject.physicsImpostor = 1;
  19383. break;
  19384. case BABYLON.PhysicsEngine.SphereImpostor:
  19385. serializationObject.physicsImpostor = 2;
  19386. break;
  19387. }
  19388. }
  19389. // Instances
  19390. serializationObject.instances = [];
  19391. for (var index = 0; index < mesh.instances.length; index++) {
  19392. var instance = mesh.instances[index];
  19393. var serializationInstance = {
  19394. name: instance.name,
  19395. position: instance.position,
  19396. rotation: instance.rotation,
  19397. rotationQuaternion: instance.rotationQuaternion,
  19398. scaling: instance.scaling
  19399. };
  19400. serializationObject.instances.push(serializationInstance);
  19401. // Animations
  19402. appendAnimations(instance, serializationInstance);
  19403. }
  19404. // Animations
  19405. appendAnimations(mesh, serializationObject);
  19406. // Layer mask
  19407. serializationObject.layerMask = mesh.layerMask;
  19408. return serializationObject;
  19409. };
  19410. var SceneSerializer = (function () {
  19411. function SceneSerializer() {
  19412. }
  19413. SceneSerializer.Serialize = function (scene) {
  19414. var serializationObject = {};
  19415. // Scene
  19416. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  19417. serializationObject.autoClear = scene.autoClear;
  19418. serializationObject.clearColor = scene.clearColor.asArray();
  19419. serializationObject.ambientColor = scene.ambientColor.asArray();
  19420. serializationObject.gravity = scene.gravity.asArray();
  19421. // Fog
  19422. if (scene.fogMode && scene.fogMode !== 0) {
  19423. serializationObject.fogMode = scene.fogMode;
  19424. serializationObject.fogColor = scene.fogColor.asArray();
  19425. serializationObject.fogStart = scene.fogStart;
  19426. serializationObject.fogEnd = scene.fogEnd;
  19427. serializationObject.fogDensity = scene.fogDensity;
  19428. }
  19429. // Lights
  19430. serializationObject.lights = [];
  19431. for (var index = 0; index < scene.lights.length; index++) {
  19432. var light = scene.lights[index];
  19433. serializationObject.lights.push(serializeLight(light));
  19434. }
  19435. // Cameras
  19436. serializationObject.cameras = [];
  19437. for (index = 0; index < scene.cameras.length; index++) {
  19438. var camera = scene.cameras[index];
  19439. serializationObject.cameras.push(serializeCamera(camera));
  19440. }
  19441. if (scene.activeCamera) {
  19442. serializationObject.activeCameraID = scene.activeCamera.id;
  19443. }
  19444. // Materials
  19445. serializationObject.materials = [];
  19446. serializationObject.multiMaterials = [];
  19447. for (index = 0; index < scene.materials.length; index++) {
  19448. var material = scene.materials[index];
  19449. if (material instanceof BABYLON.StandardMaterial) {
  19450. serializationObject.materials.push(serializeMaterial(material));
  19451. }
  19452. else if (material instanceof BABYLON.MultiMaterial) {
  19453. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  19454. }
  19455. }
  19456. // Skeletons
  19457. serializationObject.skeletons = [];
  19458. for (index = 0; index < scene.skeletons.length; index++) {
  19459. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  19460. }
  19461. // Geometries
  19462. serializationObject.geometries = {};
  19463. serializationObject.geometries.boxes = [];
  19464. serializationObject.geometries.spheres = [];
  19465. serializationObject.geometries.cylinders = [];
  19466. serializationObject.geometries.toruses = [];
  19467. serializationObject.geometries.grounds = [];
  19468. serializationObject.geometries.planes = [];
  19469. serializationObject.geometries.torusKnots = [];
  19470. serializationObject.geometries.vertexData = [];
  19471. serializedGeometries = [];
  19472. var geometries = scene.getGeometries();
  19473. for (index = 0; index < geometries.length; index++) {
  19474. var geometry = geometries[index];
  19475. if (geometry.isReady()) {
  19476. serializeGeometry(geometry, serializationObject.geometries);
  19477. }
  19478. }
  19479. // Meshes
  19480. serializationObject.meshes = [];
  19481. for (index = 0; index < scene.meshes.length; index++) {
  19482. var abstractMesh = scene.meshes[index];
  19483. if (abstractMesh instanceof BABYLON.Mesh) {
  19484. var mesh = abstractMesh;
  19485. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  19486. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  19487. }
  19488. }
  19489. }
  19490. // Particles Systems
  19491. serializationObject.particleSystems = [];
  19492. for (index = 0; index < scene.particleSystems.length; index++) {
  19493. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  19494. }
  19495. // Lens flares
  19496. serializationObject.lensFlareSystems = [];
  19497. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  19498. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  19499. }
  19500. // Shadows
  19501. serializationObject.shadowGenerators = [];
  19502. for (index = 0; index < scene.lights.length; index++) {
  19503. light = scene.lights[index];
  19504. if (light.getShadowGenerator()) {
  19505. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  19506. }
  19507. }
  19508. return serializationObject;
  19509. };
  19510. return SceneSerializer;
  19511. })();
  19512. BABYLON.SceneSerializer = SceneSerializer;
  19513. })(BABYLON || (BABYLON = {}));
  19514. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  19515. (function (BABYLON) {
  19516. var SceneLoader = (function () {
  19517. function SceneLoader() {
  19518. }
  19519. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19520. get: function () {
  19521. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19522. },
  19523. set: function (value) {
  19524. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19525. },
  19526. enumerable: true,
  19527. configurable: true
  19528. });
  19529. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19530. get: function () {
  19531. return SceneLoader._ShowLoadingScreen;
  19532. },
  19533. set: function (value) {
  19534. SceneLoader._ShowLoadingScreen = value;
  19535. },
  19536. enumerable: true,
  19537. configurable: true
  19538. });
  19539. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19540. var dotPosition = sceneFilename.lastIndexOf(".");
  19541. var queryStringPosition = sceneFilename.indexOf("?");
  19542. if (queryStringPosition === -1) {
  19543. queryStringPosition = sceneFilename.length;
  19544. }
  19545. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19546. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19547. var plugin = this._registeredPlugins[index];
  19548. if (plugin.extensions.indexOf(extension) !== -1) {
  19549. return plugin;
  19550. }
  19551. }
  19552. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19553. };
  19554. // Public functions
  19555. SceneLoader.RegisterPlugin = function (plugin) {
  19556. plugin.extensions = plugin.extensions.toLowerCase();
  19557. SceneLoader._registeredPlugins.push(plugin);
  19558. };
  19559. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19560. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19561. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19562. return;
  19563. }
  19564. var manifestChecked = function (success) {
  19565. scene.database = database;
  19566. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19567. var importMeshFromData = function (data) {
  19568. var meshes = [];
  19569. var particleSystems = [];
  19570. var skeletons = [];
  19571. try {
  19572. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19573. if (onerror) {
  19574. onerror(scene, 'unable to load the scene');
  19575. }
  19576. return;
  19577. }
  19578. }
  19579. catch (e) {
  19580. if (onerror) {
  19581. onerror(scene, e);
  19582. }
  19583. return;
  19584. }
  19585. if (onsuccess) {
  19586. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19587. onsuccess(meshes, particleSystems, skeletons);
  19588. }
  19589. };
  19590. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19591. // Direct load
  19592. importMeshFromData(sceneFilename.substr(5));
  19593. return;
  19594. }
  19595. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19596. importMeshFromData(data);
  19597. }, progressCallBack, database);
  19598. };
  19599. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19600. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19601. };
  19602. /**
  19603. * Load a scene
  19604. * @param rootUrl a string that defines the root url for scene and resources
  19605. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19606. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19607. */
  19608. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19609. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19610. };
  19611. /**
  19612. * Append a scene
  19613. * @param rootUrl a string that defines the root url for scene and resources
  19614. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19615. * @param scene is the instance of BABYLON.Scene to append to
  19616. */
  19617. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19618. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19619. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19620. return;
  19621. }
  19622. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19623. var database;
  19624. if (SceneLoader.ShowLoadingScreen) {
  19625. scene.getEngine().displayLoadingUI();
  19626. }
  19627. var loadSceneFromData = function (data) {
  19628. scene.database = database;
  19629. if (!plugin.load(scene, data, rootUrl)) {
  19630. if (onerror) {
  19631. onerror(scene);
  19632. }
  19633. scene.getEngine().hideLoadingUI();
  19634. return;
  19635. }
  19636. if (onsuccess) {
  19637. onsuccess(scene);
  19638. }
  19639. if (SceneLoader.ShowLoadingScreen) {
  19640. scene.executeWhenReady(function () {
  19641. scene.getEngine().hideLoadingUI();
  19642. });
  19643. }
  19644. };
  19645. var manifestChecked = function (success) {
  19646. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19647. };
  19648. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19649. // Direct load
  19650. loadSceneFromData(sceneFilename.substr(5));
  19651. return;
  19652. }
  19653. if (rootUrl.indexOf("file:") === -1) {
  19654. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19655. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19656. }
  19657. else {
  19658. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19659. }
  19660. };
  19661. // Flags
  19662. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19663. SceneLoader._ShowLoadingScreen = true;
  19664. // Members
  19665. SceneLoader._registeredPlugins = new Array();
  19666. return SceneLoader;
  19667. })();
  19668. BABYLON.SceneLoader = SceneLoader;
  19669. ;
  19670. })(BABYLON || (BABYLON = {}));
  19671. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  19672. (function (BABYLON) {
  19673. var Internals;
  19674. (function (Internals) {
  19675. var checkColors4 = function (colors, count) {
  19676. // Check if color3 was used
  19677. if (colors.length === count * 3) {
  19678. var colors4 = [];
  19679. for (var index = 0; index < colors.length; index += 3) {
  19680. var newIndex = (index / 3) * 4;
  19681. colors4[newIndex] = colors[index];
  19682. colors4[newIndex + 1] = colors[index + 1];
  19683. colors4[newIndex + 2] = colors[index + 2];
  19684. colors4[newIndex + 3] = 1.0;
  19685. }
  19686. return colors4;
  19687. }
  19688. return colors;
  19689. };
  19690. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19691. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  19692. texture.name = parsedTexture.name;
  19693. texture.hasAlpha = parsedTexture.hasAlpha;
  19694. texture.level = parsedTexture.level;
  19695. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19696. return texture;
  19697. };
  19698. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19699. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19700. return null;
  19701. }
  19702. if (parsedTexture.isCube) {
  19703. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19704. }
  19705. var texture;
  19706. if (parsedTexture.mirrorPlane) {
  19707. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19708. texture._waitingRenderList = parsedTexture.renderList;
  19709. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19710. }
  19711. else if (parsedTexture.isRenderTarget) {
  19712. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19713. texture._waitingRenderList = parsedTexture.renderList;
  19714. }
  19715. else {
  19716. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19717. }
  19718. texture.name = parsedTexture.name;
  19719. texture.hasAlpha = parsedTexture.hasAlpha;
  19720. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19721. texture.level = parsedTexture.level;
  19722. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19723. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19724. texture.uOffset = parsedTexture.uOffset;
  19725. texture.vOffset = parsedTexture.vOffset;
  19726. texture.uScale = parsedTexture.uScale;
  19727. texture.vScale = parsedTexture.vScale;
  19728. texture.uAng = parsedTexture.uAng;
  19729. texture.vAng = parsedTexture.vAng;
  19730. texture.wAng = parsedTexture.wAng;
  19731. texture.wrapU = parsedTexture.wrapU;
  19732. texture.wrapV = parsedTexture.wrapV;
  19733. // Animations
  19734. if (parsedTexture.animations) {
  19735. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19736. var parsedAnimation = parsedTexture.animations[animationIndex];
  19737. texture.animations.push(parseAnimation(parsedAnimation));
  19738. }
  19739. }
  19740. return texture;
  19741. };
  19742. var parseSkeleton = function (parsedSkeleton, scene) {
  19743. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19744. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19745. var parsedBone = parsedSkeleton.bones[index];
  19746. var parentBone = null;
  19747. if (parsedBone.parentBoneIndex > -1) {
  19748. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19749. }
  19750. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19751. if (parsedBone.animation) {
  19752. bone.animations.push(parseAnimation(parsedBone.animation));
  19753. }
  19754. }
  19755. return skeleton;
  19756. };
  19757. var parseFresnelParameters = function (parsedFresnelParameters) {
  19758. var fresnelParameters = new BABYLON.FresnelParameters();
  19759. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19760. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19761. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19762. fresnelParameters.bias = parsedFresnelParameters.bias;
  19763. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19764. return fresnelParameters;
  19765. };
  19766. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19767. var material;
  19768. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19769. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19770. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19771. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19772. material.specularPower = parsedMaterial.specularPower;
  19773. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19774. material.alpha = parsedMaterial.alpha;
  19775. material.id = parsedMaterial.id;
  19776. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19777. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19778. material.wireframe = parsedMaterial.wireframe;
  19779. if (parsedMaterial.diffuseTexture) {
  19780. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19781. }
  19782. if (parsedMaterial.diffuseFresnelParameters) {
  19783. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19784. }
  19785. if (parsedMaterial.ambientTexture) {
  19786. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19787. }
  19788. if (parsedMaterial.opacityTexture) {
  19789. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19790. }
  19791. if (parsedMaterial.opacityFresnelParameters) {
  19792. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19793. }
  19794. if (parsedMaterial.reflectionTexture) {
  19795. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19796. }
  19797. if (parsedMaterial.reflectionFresnelParameters) {
  19798. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19799. }
  19800. if (parsedMaterial.emissiveTexture) {
  19801. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19802. }
  19803. if (parsedMaterial.emissiveFresnelParameters) {
  19804. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19805. }
  19806. if (parsedMaterial.specularTexture) {
  19807. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19808. }
  19809. if (parsedMaterial.bumpTexture) {
  19810. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19811. }
  19812. return material;
  19813. };
  19814. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19815. for (var index = 0; index < parsedData.materials.length; index++) {
  19816. var parsedMaterial = parsedData.materials[index];
  19817. if (parsedMaterial.id === id) {
  19818. return parseMaterial(parsedMaterial, scene, rootUrl);
  19819. }
  19820. }
  19821. return null;
  19822. };
  19823. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19824. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19825. multiMaterial.id = parsedMultiMaterial.id;
  19826. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19827. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19828. var subMatId = parsedMultiMaterial.materials[matIndex];
  19829. if (subMatId) {
  19830. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19831. }
  19832. else {
  19833. multiMaterial.subMaterials.push(null);
  19834. }
  19835. }
  19836. return multiMaterial;
  19837. };
  19838. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19839. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19840. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19841. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19842. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19843. var parsedFlare = parsedLensFlareSystem.flares[index];
  19844. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19845. }
  19846. return lensFlareSystem;
  19847. };
  19848. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19849. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19850. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19851. if (parsedParticleSystem.textureName) {
  19852. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19853. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19854. }
  19855. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19856. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19857. particleSystem.minSize = parsedParticleSystem.minSize;
  19858. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19859. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19860. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19861. particleSystem.emitter = emitter;
  19862. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19863. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19864. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19865. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19866. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19867. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19868. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19869. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19870. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19871. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19872. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19873. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19874. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19875. particleSystem.start();
  19876. return particleSystem;
  19877. };
  19878. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19879. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19880. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19881. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19882. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19883. shadowGenerator.getShadowMap().renderList.push(mesh);
  19884. }
  19885. if (parsedShadowGenerator.usePoissonSampling) {
  19886. shadowGenerator.usePoissonSampling = true;
  19887. }
  19888. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19889. shadowGenerator.useVarianceShadowMap = true;
  19890. }
  19891. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19892. shadowGenerator.useBlurVarianceShadowMap = true;
  19893. if (parsedShadowGenerator.blurScale) {
  19894. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19895. }
  19896. if (parsedShadowGenerator.blurBoxOffset) {
  19897. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19898. }
  19899. }
  19900. if (parsedShadowGenerator.bias !== undefined) {
  19901. shadowGenerator.bias = parsedShadowGenerator.bias;
  19902. }
  19903. return shadowGenerator;
  19904. };
  19905. var parseAnimation = function (parsedAnimation) {
  19906. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19907. var dataType = parsedAnimation.dataType;
  19908. var keys = [];
  19909. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19910. var key = parsedAnimation.keys[index];
  19911. var data;
  19912. switch (dataType) {
  19913. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19914. data = key.values[0];
  19915. break;
  19916. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19917. data = BABYLON.Quaternion.FromArray(key.values);
  19918. break;
  19919. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19920. data = BABYLON.Matrix.FromArray(key.values);
  19921. break;
  19922. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19923. default:
  19924. data = BABYLON.Vector3.FromArray(key.values);
  19925. break;
  19926. }
  19927. keys.push({
  19928. frame: key.frame,
  19929. value: data
  19930. });
  19931. }
  19932. animation.setKeys(keys);
  19933. return animation;
  19934. };
  19935. var parseLight = function (parsedLight, scene) {
  19936. var light;
  19937. switch (parsedLight.type) {
  19938. case 0:
  19939. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19940. break;
  19941. case 1:
  19942. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19943. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19944. break;
  19945. case 2:
  19946. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19947. break;
  19948. case 3:
  19949. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19950. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19951. break;
  19952. }
  19953. light.id = parsedLight.id;
  19954. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19955. if (parsedLight.intensity !== undefined) {
  19956. light.intensity = parsedLight.intensity;
  19957. }
  19958. if (parsedLight.range) {
  19959. light.range = parsedLight.range;
  19960. }
  19961. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19962. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19963. if (parsedLight.excludedMeshesIds) {
  19964. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19965. }
  19966. // Parent
  19967. if (parsedLight.parentId) {
  19968. light._waitingParentId = parsedLight.parentId;
  19969. }
  19970. if (parsedLight.includedOnlyMeshesIds) {
  19971. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19972. }
  19973. // Animations
  19974. if (parsedLight.animations) {
  19975. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19976. var parsedAnimation = parsedLight.animations[animationIndex];
  19977. light.animations.push(parseAnimation(parsedAnimation));
  19978. }
  19979. }
  19980. if (parsedLight.autoAnimate) {
  19981. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19982. }
  19983. };
  19984. var parseCamera = function (parsedCamera, scene) {
  19985. var camera;
  19986. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19987. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19988. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19989. var alpha = parsedCamera.alpha;
  19990. var beta = parsedCamera.beta;
  19991. var radius = parsedCamera.radius;
  19992. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19993. var eye_space = parsedCamera.eye_space;
  19994. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  19995. }
  19996. else {
  19997. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19998. }
  19999. }
  20000. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  20001. eye_space = parsedCamera.eye_space;
  20002. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  20003. }
  20004. else if (parsedCamera.type === "DeviceOrientationCamera") {
  20005. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  20006. }
  20007. else if (parsedCamera.type === "FollowCamera") {
  20008. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  20009. camera.heightOffset = parsedCamera.heightOffset;
  20010. camera.radius = parsedCamera.radius;
  20011. camera.rotationOffset = parsedCamera.rotationOffset;
  20012. if (lockedTargetMesh)
  20013. camera.target = lockedTargetMesh;
  20014. }
  20015. else if (parsedCamera.type === "GamepadCamera") {
  20016. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  20017. }
  20018. else if (parsedCamera.type === "OculusCamera") {
  20019. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  20020. }
  20021. else if (parsedCamera.type === "OculusGamepadCamera") {
  20022. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  20023. }
  20024. else if (parsedCamera.type === "TouchCamera") {
  20025. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  20026. }
  20027. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  20028. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  20029. }
  20030. else if (parsedCamera.type === "WebVRCamera") {
  20031. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  20032. }
  20033. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  20034. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  20035. }
  20036. else {
  20037. // Free Camera is the default value
  20038. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  20039. }
  20040. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  20041. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  20042. camera.lockedTarget = lockedTargetMesh;
  20043. }
  20044. camera.id = parsedCamera.id;
  20045. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  20046. // Parent
  20047. if (parsedCamera.parentId) {
  20048. camera._waitingParentId = parsedCamera.parentId;
  20049. }
  20050. // Target
  20051. if (parsedCamera.target) {
  20052. if (camera.setTarget) {
  20053. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20054. }
  20055. else {
  20056. //For ArcRotate
  20057. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  20058. }
  20059. }
  20060. else {
  20061. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  20062. }
  20063. camera.fov = parsedCamera.fov;
  20064. camera.minZ = parsedCamera.minZ;
  20065. camera.maxZ = parsedCamera.maxZ;
  20066. camera.speed = parsedCamera.speed;
  20067. camera.inertia = parsedCamera.inertia;
  20068. camera.checkCollisions = parsedCamera.checkCollisions;
  20069. camera.applyGravity = parsedCamera.applyGravity;
  20070. if (parsedCamera.ellipsoid) {
  20071. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  20072. }
  20073. // Animations
  20074. if (parsedCamera.animations) {
  20075. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20076. var parsedAnimation = parsedCamera.animations[animationIndex];
  20077. camera.animations.push(parseAnimation(parsedAnimation));
  20078. }
  20079. }
  20080. if (parsedCamera.autoAnimate) {
  20081. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  20082. }
  20083. // Layer Mask
  20084. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  20085. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  20086. }
  20087. else {
  20088. camera.layerMask = 0xFFFFFFFF;
  20089. }
  20090. return camera;
  20091. };
  20092. var parseGeometry = function (parsedGeometry, scene) {
  20093. var id = parsedGeometry.id;
  20094. return scene.getGeometryByID(id);
  20095. };
  20096. var parseBox = function (parsedBox, scene) {
  20097. if (parseGeometry(parsedBox, scene)) {
  20098. return null; // null since geometry could be something else than a box...
  20099. }
  20100. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  20101. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  20102. scene.pushGeometry(box, true);
  20103. return box;
  20104. };
  20105. var parseSphere = function (parsedSphere, scene) {
  20106. if (parseGeometry(parsedSphere, scene)) {
  20107. return null; // null since geometry could be something else than a sphere...
  20108. }
  20109. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  20110. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  20111. scene.pushGeometry(sphere, true);
  20112. return sphere;
  20113. };
  20114. var parseCylinder = function (parsedCylinder, scene) {
  20115. if (parseGeometry(parsedCylinder, scene)) {
  20116. return null; // null since geometry could be something else than a cylinder...
  20117. }
  20118. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  20119. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  20120. scene.pushGeometry(cylinder, true);
  20121. return cylinder;
  20122. };
  20123. var parseTorus = function (parsedTorus, scene) {
  20124. if (parseGeometry(parsedTorus, scene)) {
  20125. return null; // null since geometry could be something else than a torus...
  20126. }
  20127. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  20128. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  20129. scene.pushGeometry(torus, true);
  20130. return torus;
  20131. };
  20132. var parseGround = function (parsedGround, scene) {
  20133. if (parseGeometry(parsedGround, scene)) {
  20134. return null; // null since geometry could be something else than a ground...
  20135. }
  20136. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  20137. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  20138. scene.pushGeometry(ground, true);
  20139. return ground;
  20140. };
  20141. var parsePlane = function (parsedPlane, scene) {
  20142. if (parseGeometry(parsedPlane, scene)) {
  20143. return null; // null since geometry could be something else than a plane...
  20144. }
  20145. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  20146. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  20147. scene.pushGeometry(plane, true);
  20148. return plane;
  20149. };
  20150. var parseTorusKnot = function (parsedTorusKnot, scene) {
  20151. if (parseGeometry(parsedTorusKnot, scene)) {
  20152. return null; // null since geometry could be something else than a torusKnot...
  20153. }
  20154. 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);
  20155. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  20156. scene.pushGeometry(torusKnot, true);
  20157. return torusKnot;
  20158. };
  20159. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  20160. if (parseGeometry(parsedVertexData, scene)) {
  20161. return null; // null since geometry could be a primitive
  20162. }
  20163. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  20164. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  20165. if (parsedVertexData.delayLoadingFile) {
  20166. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20167. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  20168. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  20169. geometry._delayInfo = [];
  20170. if (parsedVertexData.hasUVs) {
  20171. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20172. }
  20173. if (parsedVertexData.hasUVs2) {
  20174. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20175. }
  20176. if (parsedVertexData.hasColors) {
  20177. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20178. }
  20179. if (parsedVertexData.hasMatricesIndices) {
  20180. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20181. }
  20182. if (parsedVertexData.hasMatricesWeights) {
  20183. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20184. }
  20185. geometry._delayLoadingFunction = importVertexData;
  20186. }
  20187. else {
  20188. importVertexData(parsedVertexData, geometry);
  20189. }
  20190. scene.pushGeometry(geometry, true);
  20191. return geometry;
  20192. };
  20193. var parseMesh = function (parsedMesh, scene, rootUrl) {
  20194. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  20195. mesh.id = parsedMesh.id;
  20196. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20197. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20198. if (parsedMesh.rotationQuaternion) {
  20199. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20200. }
  20201. else if (parsedMesh.rotation) {
  20202. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20203. }
  20204. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20205. if (parsedMesh.localMatrix) {
  20206. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20207. }
  20208. else if (parsedMesh.pivotMatrix) {
  20209. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20210. }
  20211. mesh.setEnabled(parsedMesh.isEnabled);
  20212. mesh.isVisible = parsedMesh.isVisible;
  20213. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20214. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20215. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20216. if (parsedMesh.applyFog !== undefined) {
  20217. mesh.applyFog = parsedMesh.applyFog;
  20218. }
  20219. if (parsedMesh.pickable !== undefined) {
  20220. mesh.isPickable = parsedMesh.pickable;
  20221. }
  20222. if (parsedMesh.alphaIndex !== undefined) {
  20223. mesh.alphaIndex = parsedMesh.alphaIndex;
  20224. }
  20225. mesh.receiveShadows = parsedMesh.receiveShadows;
  20226. mesh.billboardMode = parsedMesh.billboardMode;
  20227. if (parsedMesh.visibility !== undefined) {
  20228. mesh.visibility = parsedMesh.visibility;
  20229. }
  20230. mesh.checkCollisions = parsedMesh.checkCollisions;
  20231. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20232. // Parent
  20233. if (parsedMesh.parentId) {
  20234. mesh._waitingParentId = parsedMesh.parentId;
  20235. }
  20236. // Actions
  20237. if (parsedMesh.actions !== undefined) {
  20238. mesh._waitingActions = parsedMesh.actions;
  20239. }
  20240. // Geometry
  20241. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20242. if (parsedMesh.delayLoadingFile) {
  20243. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20244. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20245. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20246. if (parsedMesh._binaryInfo) {
  20247. mesh._binaryInfo = parsedMesh._binaryInfo;
  20248. }
  20249. mesh._delayInfo = [];
  20250. if (parsedMesh.hasUVs) {
  20251. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20252. }
  20253. if (parsedMesh.hasUVs2) {
  20254. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20255. }
  20256. if (parsedMesh.hasColors) {
  20257. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20258. }
  20259. if (parsedMesh.hasMatricesIndices) {
  20260. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20261. }
  20262. if (parsedMesh.hasMatricesWeights) {
  20263. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20264. }
  20265. mesh._delayLoadingFunction = importGeometry;
  20266. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20267. mesh._checkDelayState();
  20268. }
  20269. }
  20270. else {
  20271. importGeometry(parsedMesh, mesh);
  20272. }
  20273. // Material
  20274. if (parsedMesh.materialId) {
  20275. mesh.setMaterialByID(parsedMesh.materialId);
  20276. }
  20277. else {
  20278. mesh.material = null;
  20279. }
  20280. // Skeleton
  20281. if (parsedMesh.skeletonId > -1) {
  20282. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20283. }
  20284. // Physics
  20285. if (parsedMesh.physicsImpostor) {
  20286. if (!scene.isPhysicsEnabled()) {
  20287. scene.enablePhysics();
  20288. }
  20289. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  20290. }
  20291. // Animations
  20292. if (parsedMesh.animations) {
  20293. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20294. var parsedAnimation = parsedMesh.animations[animationIndex];
  20295. mesh.animations.push(parseAnimation(parsedAnimation));
  20296. }
  20297. }
  20298. if (parsedMesh.autoAnimate) {
  20299. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  20300. }
  20301. // Layer Mask
  20302. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20303. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20304. }
  20305. else {
  20306. mesh.layerMask = 0xFFFFFFFF;
  20307. }
  20308. // Instances
  20309. if (parsedMesh.instances) {
  20310. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20311. var parsedInstance = parsedMesh.instances[index];
  20312. var instance = mesh.createInstance(parsedInstance.name);
  20313. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20314. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20315. if (parsedInstance.rotationQuaternion) {
  20316. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20317. }
  20318. else if (parsedInstance.rotation) {
  20319. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20320. }
  20321. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20322. instance.checkCollisions = mesh.checkCollisions;
  20323. if (parsedMesh.animations) {
  20324. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20325. parsedAnimation = parsedMesh.animations[animationIndex];
  20326. instance.animations.push(parseAnimation(parsedAnimation));
  20327. }
  20328. }
  20329. }
  20330. }
  20331. return mesh;
  20332. };
  20333. var parseActions = function (parsedActions, object, scene) {
  20334. var actionManager = new BABYLON.ActionManager(scene);
  20335. if (object === null)
  20336. scene.actionManager = actionManager;
  20337. else
  20338. object.actionManager = actionManager;
  20339. // instanciate a new object
  20340. var instanciate = function (name, params) {
  20341. var newInstance = Object.create(BABYLON[name].prototype);
  20342. newInstance.constructor.apply(newInstance, params);
  20343. return newInstance;
  20344. };
  20345. var parseParameter = function (name, value, target, propertyPath) {
  20346. if (propertyPath === null) {
  20347. // String, boolean or float
  20348. var floatValue = parseFloat(value);
  20349. if (value === "true" || value === "false")
  20350. return value === "true";
  20351. else
  20352. return isNaN(floatValue) ? value : floatValue;
  20353. }
  20354. var effectiveTarget = propertyPath.split(".");
  20355. var values = value.split(",");
  20356. for (var i = 0; i < effectiveTarget.length; i++) {
  20357. target = target[effectiveTarget[i]];
  20358. }
  20359. // Return appropriate value with its type
  20360. if (target instanceof Boolean)
  20361. return values[0] === "true";
  20362. if (target instanceof String)
  20363. return values[0];
  20364. // Parameters with multiple values such as Vector3 etc.
  20365. var split = new Array();
  20366. for (var i = 0; i < values.length; i++)
  20367. split.push(parseFloat(values[i]));
  20368. if (target instanceof BABYLON.Vector3)
  20369. return BABYLON.Vector3.FromArray(split);
  20370. if (target instanceof BABYLON.Vector4)
  20371. return BABYLON.Vector4.FromArray(split);
  20372. if (target instanceof BABYLON.Color3)
  20373. return BABYLON.Color3.FromArray(split);
  20374. if (target instanceof BABYLON.Color4)
  20375. return BABYLON.Color4.FromArray(split);
  20376. return parseFloat(values[0]);
  20377. };
  20378. // traverse graph per trigger
  20379. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  20380. if (combineArray === void 0) { combineArray = null; }
  20381. if (parsedAction.detached)
  20382. return;
  20383. var parameters = new Array();
  20384. var target = null;
  20385. var propertyPath = null;
  20386. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  20387. // Parameters
  20388. if (parsedAction.type === 2)
  20389. parameters.push(actionManager);
  20390. else
  20391. parameters.push(trigger);
  20392. if (combine) {
  20393. var actions = new Array();
  20394. for (var j = 0; j < parsedAction.combine.length; j++) {
  20395. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  20396. }
  20397. parameters.push(actions);
  20398. }
  20399. else {
  20400. for (var i = 0; i < parsedAction.properties.length; i++) {
  20401. var value = parsedAction.properties[i].value;
  20402. var name = parsedAction.properties[i].name;
  20403. if (name === "target")
  20404. value = target = scene.getNodeByName(value);
  20405. else if (name === "parent")
  20406. value = scene.getNodeByName(value);
  20407. else if (name === "sound")
  20408. value = scene.getSoundByName(value);
  20409. else if (name !== "propertyPath") {
  20410. if (parsedAction.type === 2 && name === "operator")
  20411. value = BABYLON.ValueCondition[value];
  20412. else
  20413. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  20414. }
  20415. else {
  20416. propertyPath = value;
  20417. }
  20418. parameters.push(value);
  20419. }
  20420. }
  20421. parameters.push(condition);
  20422. // If interpolate value action
  20423. if (parsedAction.name === "InterpolateValueAction") {
  20424. var param = parameters[parameters.length - 2];
  20425. parameters[parameters.length - 1] = param;
  20426. parameters[parameters.length - 2] = condition;
  20427. }
  20428. // Action or condition(s) and not CombineAction
  20429. var newAction = instanciate(parsedAction.name, parameters);
  20430. if (combineArray === null) {
  20431. if (newAction instanceof BABYLON.Condition) {
  20432. condition = newAction;
  20433. newAction = action;
  20434. }
  20435. else {
  20436. condition = null;
  20437. if (action)
  20438. action.then(newAction);
  20439. else
  20440. actionManager.registerAction(newAction);
  20441. }
  20442. }
  20443. else {
  20444. combineArray.push(newAction);
  20445. }
  20446. for (var i = 0; i < parsedAction.children.length; i++)
  20447. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  20448. };
  20449. for (var i = 0; i < parsedActions.children.length; i++) {
  20450. var triggerParams;
  20451. var trigger = parsedActions.children[i];
  20452. if (trigger.properties.length > 0) {
  20453. var param = trigger.properties[0].value;
  20454. var value = trigger.properties[0].targetType == null ? param : scene.getMeshByName(param);
  20455. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  20456. }
  20457. else
  20458. triggerParams = BABYLON.ActionManager[trigger.name];
  20459. for (var j = 0; j < trigger.children.length; j++) {
  20460. if (!trigger.detached)
  20461. traverse(trigger.children[j], triggerParams, null, null);
  20462. }
  20463. }
  20464. };
  20465. var parseSound = function (parsedSound, scene, rootUrl) {
  20466. var soundName = parsedSound.name;
  20467. var soundUrl = rootUrl + soundName;
  20468. var options = {
  20469. autoplay: parsedSound.autoplay,
  20470. loop: parsedSound.loop,
  20471. volume: parsedSound.volume,
  20472. spatialSound: parsedSound.spatialSound,
  20473. maxDistance: parsedSound.maxDistance,
  20474. rolloffFactor: parsedSound.rolloffFactor,
  20475. refDistance: parsedSound.refDistance,
  20476. distanceModel: parsedSound.distanceModel,
  20477. playbackRate: parsedSound.playbackRate
  20478. };
  20479. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  20480. scene._removePendingData(newSound);
  20481. }, options);
  20482. scene._addPendingData(newSound);
  20483. if (parsedSound.position) {
  20484. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20485. newSound.setPosition(soundPosition);
  20486. }
  20487. if (parsedSound.isDirectional) {
  20488. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20489. if (parsedSound.localDirectionToMesh) {
  20490. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20491. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20492. }
  20493. }
  20494. if (parsedSound.connectedMeshId) {
  20495. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20496. if (connectedMesh) {
  20497. newSound.attachToMesh(connectedMesh);
  20498. }
  20499. }
  20500. };
  20501. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20502. names = (names instanceof Array) ? names : [names];
  20503. for (var i in names) {
  20504. if (mesh.name === names[i]) {
  20505. hierarchyIds.push(mesh.id);
  20506. return true;
  20507. }
  20508. }
  20509. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20510. hierarchyIds.push(mesh.id);
  20511. return true;
  20512. }
  20513. return false;
  20514. };
  20515. var importVertexData = function (parsedVertexData, geometry) {
  20516. var vertexData = new BABYLON.VertexData();
  20517. // positions
  20518. var positions = parsedVertexData.positions;
  20519. if (positions) {
  20520. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20521. }
  20522. // normals
  20523. var normals = parsedVertexData.normals;
  20524. if (normals) {
  20525. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20526. }
  20527. // uvs
  20528. var uvs = parsedVertexData.uvs;
  20529. if (uvs) {
  20530. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20531. }
  20532. // uv2s
  20533. var uv2s = parsedVertexData.uv2s;
  20534. if (uv2s) {
  20535. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20536. }
  20537. // colors
  20538. var colors = parsedVertexData.colors;
  20539. if (colors) {
  20540. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20541. }
  20542. // matricesIndices
  20543. var matricesIndices = parsedVertexData.matricesIndices;
  20544. if (matricesIndices) {
  20545. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20546. }
  20547. // matricesWeights
  20548. var matricesWeights = parsedVertexData.matricesWeights;
  20549. if (matricesWeights) {
  20550. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20551. }
  20552. // indices
  20553. var indices = parsedVertexData.indices;
  20554. if (indices) {
  20555. vertexData.indices = indices;
  20556. }
  20557. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20558. };
  20559. var importGeometry = function (parsedGeometry, mesh) {
  20560. var scene = mesh.getScene();
  20561. // Geometry
  20562. var geometryId = parsedGeometry.geometryId;
  20563. if (geometryId) {
  20564. var geometry = scene.getGeometryByID(geometryId);
  20565. if (geometry) {
  20566. geometry.applyToMesh(mesh);
  20567. }
  20568. }
  20569. else if (parsedGeometry instanceof ArrayBuffer) {
  20570. var binaryInfo = mesh._binaryInfo;
  20571. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20572. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20573. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20574. }
  20575. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20576. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20577. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20578. }
  20579. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20580. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20581. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20582. }
  20583. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20584. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20585. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20586. }
  20587. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20588. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20589. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  20590. }
  20591. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20592. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20593. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20594. }
  20595. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20596. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20597. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20598. }
  20599. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20600. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20601. mesh.setIndices(indicesData);
  20602. }
  20603. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20604. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20605. mesh.subMeshes = [];
  20606. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20607. var materialIndex = subMeshesData[(i * 5) + 0];
  20608. var verticesStart = subMeshesData[(i * 5) + 1];
  20609. var verticesCount = subMeshesData[(i * 5) + 2];
  20610. var indexStart = subMeshesData[(i * 5) + 3];
  20611. var indexCount = subMeshesData[(i * 5) + 4];
  20612. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20613. }
  20614. }
  20615. }
  20616. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20617. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20618. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20619. if (parsedGeometry.uvs) {
  20620. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20621. }
  20622. if (parsedGeometry.uvs2) {
  20623. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20624. }
  20625. if (parsedGeometry.colors) {
  20626. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20627. }
  20628. if (parsedGeometry.matricesIndices) {
  20629. if (!parsedGeometry.matricesIndices._isExpanded) {
  20630. var floatIndices = [];
  20631. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20632. var matricesIndex = parsedGeometry.matricesIndices[i];
  20633. floatIndices.push(matricesIndex & 0x000000FF);
  20634. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20635. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20636. floatIndices.push(matricesIndex >> 24);
  20637. }
  20638. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20639. }
  20640. else {
  20641. delete parsedGeometry.matricesIndices._isExpanded;
  20642. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20643. }
  20644. }
  20645. if (parsedGeometry.matricesWeights) {
  20646. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20647. }
  20648. mesh.setIndices(parsedGeometry.indices);
  20649. // SubMeshes
  20650. if (parsedGeometry.subMeshes) {
  20651. mesh.subMeshes = [];
  20652. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20653. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20654. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20655. }
  20656. }
  20657. }
  20658. // Flat shading
  20659. if (mesh._shouldGenerateFlatShading) {
  20660. mesh.convertToFlatShadedMesh();
  20661. delete mesh._shouldGenerateFlatShading;
  20662. }
  20663. // Update
  20664. mesh.computeWorldMatrix(true);
  20665. // Octree
  20666. if (scene._selectionOctree) {
  20667. scene._selectionOctree.addMesh(mesh);
  20668. }
  20669. };
  20670. BABYLON.SceneLoader.RegisterPlugin({
  20671. extensions: ".babylon",
  20672. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20673. var parsedData = JSON.parse(data);
  20674. var loadedSkeletonsIds = [];
  20675. var loadedMaterialsIds = [];
  20676. var hierarchyIds = [];
  20677. for (var index = 0; index < parsedData.meshes.length; index++) {
  20678. var parsedMesh = parsedData.meshes[index];
  20679. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20680. if (meshesNames instanceof Array) {
  20681. // Remove found mesh name from list.
  20682. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20683. }
  20684. // Material ?
  20685. if (parsedMesh.materialId) {
  20686. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20687. if (!materialFound) {
  20688. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20689. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20690. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20691. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20692. var subMatId = parsedMultiMaterial.materials[matIndex];
  20693. loadedMaterialsIds.push(subMatId);
  20694. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20695. }
  20696. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20697. parseMultiMaterial(parsedMultiMaterial, scene);
  20698. materialFound = true;
  20699. break;
  20700. }
  20701. }
  20702. }
  20703. if (!materialFound) {
  20704. loadedMaterialsIds.push(parsedMesh.materialId);
  20705. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  20706. }
  20707. }
  20708. // Skeleton ?
  20709. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20710. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20711. if (!skeletonAlreadyLoaded) {
  20712. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20713. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20714. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20715. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20716. loadedSkeletonsIds.push(parsedSkeleton.id);
  20717. }
  20718. }
  20719. }
  20720. }
  20721. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20722. meshes.push(mesh);
  20723. }
  20724. }
  20725. for (index = 0; index < scene.meshes.length; index++) {
  20726. var currentMesh = scene.meshes[index];
  20727. if (currentMesh._waitingParentId) {
  20728. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20729. currentMesh._waitingParentId = undefined;
  20730. }
  20731. }
  20732. // Particles
  20733. if (parsedData.particleSystems) {
  20734. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20735. var parsedParticleSystem = parsedData.particleSystems[index];
  20736. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20737. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20738. }
  20739. }
  20740. }
  20741. return true;
  20742. },
  20743. load: function (scene, data, rootUrl) {
  20744. var parsedData = JSON.parse(data);
  20745. // Scene
  20746. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20747. scene.autoClear = parsedData.autoClear;
  20748. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20749. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20750. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20751. // Fog
  20752. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20753. scene.fogMode = parsedData.fogMode;
  20754. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20755. scene.fogStart = parsedData.fogStart;
  20756. scene.fogEnd = parsedData.fogEnd;
  20757. scene.fogDensity = parsedData.fogDensity;
  20758. }
  20759. for (var index = 0; index < parsedData.lights.length; index++) {
  20760. var parsedLight = parsedData.lights[index];
  20761. parseLight(parsedLight, scene);
  20762. }
  20763. // Materials
  20764. if (parsedData.materials) {
  20765. for (index = 0; index < parsedData.materials.length; index++) {
  20766. var parsedMaterial = parsedData.materials[index];
  20767. parseMaterial(parsedMaterial, scene, rootUrl);
  20768. }
  20769. }
  20770. if (parsedData.multiMaterials) {
  20771. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20772. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20773. parseMultiMaterial(parsedMultiMaterial, scene);
  20774. }
  20775. }
  20776. // Skeletons
  20777. if (parsedData.skeletons) {
  20778. for (index = 0; index < parsedData.skeletons.length; index++) {
  20779. var parsedSkeleton = parsedData.skeletons[index];
  20780. parseSkeleton(parsedSkeleton, scene);
  20781. }
  20782. }
  20783. // Geometries
  20784. var geometries = parsedData.geometries;
  20785. if (geometries) {
  20786. // Boxes
  20787. var boxes = geometries.boxes;
  20788. if (boxes) {
  20789. for (index = 0; index < boxes.length; index++) {
  20790. var parsedBox = boxes[index];
  20791. parseBox(parsedBox, scene);
  20792. }
  20793. }
  20794. // Spheres
  20795. var spheres = geometries.spheres;
  20796. if (spheres) {
  20797. for (index = 0; index < spheres.length; index++) {
  20798. var parsedSphere = spheres[index];
  20799. parseSphere(parsedSphere, scene);
  20800. }
  20801. }
  20802. // Cylinders
  20803. var cylinders = geometries.cylinders;
  20804. if (cylinders) {
  20805. for (index = 0; index < cylinders.length; index++) {
  20806. var parsedCylinder = cylinders[index];
  20807. parseCylinder(parsedCylinder, scene);
  20808. }
  20809. }
  20810. // Toruses
  20811. var toruses = geometries.toruses;
  20812. if (toruses) {
  20813. for (index = 0; index < toruses.length; index++) {
  20814. var parsedTorus = toruses[index];
  20815. parseTorus(parsedTorus, scene);
  20816. }
  20817. }
  20818. // Grounds
  20819. var grounds = geometries.grounds;
  20820. if (grounds) {
  20821. for (index = 0; index < grounds.length; index++) {
  20822. var parsedGround = grounds[index];
  20823. parseGround(parsedGround, scene);
  20824. }
  20825. }
  20826. // Planes
  20827. var planes = geometries.planes;
  20828. if (planes) {
  20829. for (index = 0; index < planes.length; index++) {
  20830. var parsedPlane = planes[index];
  20831. parsePlane(parsedPlane, scene);
  20832. }
  20833. }
  20834. // TorusKnots
  20835. var torusKnots = geometries.torusKnots;
  20836. if (torusKnots) {
  20837. for (index = 0; index < torusKnots.length; index++) {
  20838. var parsedTorusKnot = torusKnots[index];
  20839. parseTorusKnot(parsedTorusKnot, scene);
  20840. }
  20841. }
  20842. // VertexData
  20843. var vertexData = geometries.vertexData;
  20844. if (vertexData) {
  20845. for (index = 0; index < vertexData.length; index++) {
  20846. var parsedVertexData = vertexData[index];
  20847. parseVertexData(parsedVertexData, scene, rootUrl);
  20848. }
  20849. }
  20850. }
  20851. for (index = 0; index < parsedData.meshes.length; index++) {
  20852. var parsedMesh = parsedData.meshes[index];
  20853. parseMesh(parsedMesh, scene, rootUrl);
  20854. }
  20855. for (index = 0; index < parsedData.cameras.length; index++) {
  20856. var parsedCamera = parsedData.cameras[index];
  20857. parseCamera(parsedCamera, scene);
  20858. }
  20859. if (parsedData.activeCameraID) {
  20860. scene.setActiveCameraByID(parsedData.activeCameraID);
  20861. }
  20862. for (index = 0; index < scene.cameras.length; index++) {
  20863. var camera = scene.cameras[index];
  20864. if (camera._waitingParentId) {
  20865. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20866. camera._waitingParentId = undefined;
  20867. }
  20868. }
  20869. for (index = 0; index < scene.lights.length; index++) {
  20870. var light = scene.lights[index];
  20871. if (light._waitingParentId) {
  20872. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20873. light._waitingParentId = undefined;
  20874. }
  20875. }
  20876. // Sounds
  20877. if (parsedData.sounds) {
  20878. for (index = 0; index < parsedData.sounds.length; index++) {
  20879. var parsedSound = parsedData.sounds[index];
  20880. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20881. parseSound(parsedSound, scene, rootUrl);
  20882. }
  20883. else {
  20884. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20885. }
  20886. }
  20887. }
  20888. for (index = 0; index < scene.meshes.length; index++) {
  20889. var mesh = scene.meshes[index];
  20890. if (mesh._waitingParentId) {
  20891. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20892. mesh._waitingParentId = undefined;
  20893. }
  20894. if (mesh._waitingActions) {
  20895. parseActions(mesh._waitingActions, mesh, scene);
  20896. mesh._waitingActions = undefined;
  20897. }
  20898. }
  20899. // Particles Systems
  20900. if (parsedData.particleSystems) {
  20901. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20902. var parsedParticleSystem = parsedData.particleSystems[index];
  20903. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20904. }
  20905. }
  20906. // Lens flares
  20907. if (parsedData.lensFlareSystems) {
  20908. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20909. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20910. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20911. }
  20912. }
  20913. // Shadows
  20914. if (parsedData.shadowGenerators) {
  20915. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20916. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20917. parseShadowGenerator(parsedShadowGenerator, scene);
  20918. }
  20919. }
  20920. // Actions (scene)
  20921. if (parsedData.actions) {
  20922. parseActions(parsedData.actions, null, scene);
  20923. }
  20924. // Finish
  20925. return true;
  20926. }
  20927. });
  20928. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20929. })(BABYLON || (BABYLON = {}));
  20930. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  20931. (function (BABYLON) {
  20932. // Unique ID when we import meshes from Babylon to CSG
  20933. var currentCSGMeshId = 0;
  20934. // # class Vertex
  20935. // Represents a vertex of a polygon. Use your own vertex class instead of this
  20936. // one to provide additional features like texture coordinates and vertex
  20937. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  20938. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  20939. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  20940. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  20941. // is not used anywhere else.
  20942. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  20943. var Vertex = (function () {
  20944. function Vertex(pos, normal, uv) {
  20945. this.pos = pos;
  20946. this.normal = normal;
  20947. this.uv = uv;
  20948. }
  20949. Vertex.prototype.clone = function () {
  20950. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  20951. };
  20952. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  20953. // orientation of a polygon is flipped.
  20954. Vertex.prototype.flip = function () {
  20955. this.normal = this.normal.scale(-1);
  20956. };
  20957. // Create a new vertex between this vertex and `other` by linearly
  20958. // interpolating all properties using a parameter of `t`. Subclasses should
  20959. // override this to interpolate additional properties.
  20960. Vertex.prototype.interpolate = function (other, t) {
  20961. 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));
  20962. };
  20963. return Vertex;
  20964. })();
  20965. // # class Plane
  20966. // Represents a plane in 3D space.
  20967. var Plane = (function () {
  20968. function Plane(normal, w) {
  20969. this.normal = normal;
  20970. this.w = w;
  20971. }
  20972. Plane.FromPoints = function (a, b, c) {
  20973. var v0 = c.subtract(a);
  20974. var v1 = b.subtract(a);
  20975. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  20976. return null;
  20977. }
  20978. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  20979. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  20980. };
  20981. Plane.prototype.clone = function () {
  20982. return new Plane(this.normal.clone(), this.w);
  20983. };
  20984. Plane.prototype.flip = function () {
  20985. this.normal.scaleInPlace(-1);
  20986. this.w = -this.w;
  20987. };
  20988. // Split `polygon` by this plane if needed, then put the polygon or polygon
  20989. // fragments in the appropriate lists. Coplanar polygons go into either
  20990. // `coplanarFront` or `coplanarBack` depending on their orientation with
  20991. // respect to this plane. Polygons in front or in back of this plane go into
  20992. // either `front` or `back`.
  20993. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  20994. var COPLANAR = 0;
  20995. var FRONT = 1;
  20996. var BACK = 2;
  20997. var SPANNING = 3;
  20998. // Classify each point as well as the entire polygon into one of the above
  20999. // four classes.
  21000. var polygonType = 0;
  21001. var types = [];
  21002. for (var i = 0; i < polygon.vertices.length; i++) {
  21003. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  21004. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  21005. polygonType |= type;
  21006. types.push(type);
  21007. }
  21008. switch (polygonType) {
  21009. case COPLANAR:
  21010. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  21011. break;
  21012. case FRONT:
  21013. front.push(polygon);
  21014. break;
  21015. case BACK:
  21016. back.push(polygon);
  21017. break;
  21018. case SPANNING:
  21019. var f = [], b = [];
  21020. for (i = 0; i < polygon.vertices.length; i++) {
  21021. var j = (i + 1) % polygon.vertices.length;
  21022. var ti = types[i], tj = types[j];
  21023. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  21024. if (ti != BACK)
  21025. f.push(vi);
  21026. if (ti != FRONT)
  21027. b.push(ti != BACK ? vi.clone() : vi);
  21028. if ((ti | tj) == SPANNING) {
  21029. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  21030. var v = vi.interpolate(vj, t);
  21031. f.push(v);
  21032. b.push(v.clone());
  21033. }
  21034. }
  21035. if (f.length >= 3) {
  21036. var poly = new Polygon(f, polygon.shared);
  21037. if (poly.plane)
  21038. front.push(poly);
  21039. }
  21040. if (b.length >= 3) {
  21041. poly = new Polygon(b, polygon.shared);
  21042. if (poly.plane)
  21043. back.push(poly);
  21044. }
  21045. break;
  21046. }
  21047. };
  21048. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  21049. // point is on the plane.
  21050. Plane.EPSILON = 1e-5;
  21051. return Plane;
  21052. })();
  21053. // # class Polygon
  21054. // Represents a convex polygon. The vertices used to initialize a polygon must
  21055. // be coplanar and form a convex loop.
  21056. //
  21057. // Each convex polygon has a `shared` property, which is shared between all
  21058. // polygons that are clones of each other or were split from the same polygon.
  21059. // This can be used to define per-polygon properties (such as surface color).
  21060. var Polygon = (function () {
  21061. function Polygon(vertices, shared) {
  21062. this.vertices = vertices;
  21063. this.shared = shared;
  21064. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  21065. }
  21066. Polygon.prototype.clone = function () {
  21067. var vertices = this.vertices.map(function (v) { return v.clone(); });
  21068. return new Polygon(vertices, this.shared);
  21069. };
  21070. Polygon.prototype.flip = function () {
  21071. this.vertices.reverse().map(function (v) {
  21072. v.flip();
  21073. });
  21074. this.plane.flip();
  21075. };
  21076. return Polygon;
  21077. })();
  21078. // # class Node
  21079. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  21080. // by picking a polygon to split along. That polygon (and all other coplanar
  21081. // polygons) are added directly to that node and the other polygons are added to
  21082. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  21083. // no distinction between internal and leaf nodes.
  21084. var Node = (function () {
  21085. function Node(polygons) {
  21086. this.plane = null;
  21087. this.front = null;
  21088. this.back = null;
  21089. this.polygons = [];
  21090. if (polygons) {
  21091. this.build(polygons);
  21092. }
  21093. }
  21094. Node.prototype.clone = function () {
  21095. var node = new Node();
  21096. node.plane = this.plane && this.plane.clone();
  21097. node.front = this.front && this.front.clone();
  21098. node.back = this.back && this.back.clone();
  21099. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  21100. return node;
  21101. };
  21102. // Convert solid space to empty space and empty space to solid space.
  21103. Node.prototype.invert = function () {
  21104. for (var i = 0; i < this.polygons.length; i++) {
  21105. this.polygons[i].flip();
  21106. }
  21107. if (this.plane) {
  21108. this.plane.flip();
  21109. }
  21110. if (this.front) {
  21111. this.front.invert();
  21112. }
  21113. if (this.back) {
  21114. this.back.invert();
  21115. }
  21116. var temp = this.front;
  21117. this.front = this.back;
  21118. this.back = temp;
  21119. };
  21120. // Recursively remove all polygons in `polygons` that are inside this BSP
  21121. // tree.
  21122. Node.prototype.clipPolygons = function (polygons) {
  21123. if (!this.plane)
  21124. return polygons.slice();
  21125. var front = [], back = [];
  21126. for (var i = 0; i < polygons.length; i++) {
  21127. this.plane.splitPolygon(polygons[i], front, back, front, back);
  21128. }
  21129. if (this.front) {
  21130. front = this.front.clipPolygons(front);
  21131. }
  21132. if (this.back) {
  21133. back = this.back.clipPolygons(back);
  21134. }
  21135. else {
  21136. back = [];
  21137. }
  21138. return front.concat(back);
  21139. };
  21140. // Remove all polygons in this BSP tree that are inside the other BSP tree
  21141. // `bsp`.
  21142. Node.prototype.clipTo = function (bsp) {
  21143. this.polygons = bsp.clipPolygons(this.polygons);
  21144. if (this.front)
  21145. this.front.clipTo(bsp);
  21146. if (this.back)
  21147. this.back.clipTo(bsp);
  21148. };
  21149. // Return a list of all polygons in this BSP tree.
  21150. Node.prototype.allPolygons = function () {
  21151. var polygons = this.polygons.slice();
  21152. if (this.front)
  21153. polygons = polygons.concat(this.front.allPolygons());
  21154. if (this.back)
  21155. polygons = polygons.concat(this.back.allPolygons());
  21156. return polygons;
  21157. };
  21158. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  21159. // new polygons are filtered down to the bottom of the tree and become new
  21160. // nodes there. Each set of polygons is partitioned using the first polygon
  21161. // (no heuristic is used to pick a good split).
  21162. Node.prototype.build = function (polygons) {
  21163. if (!polygons.length)
  21164. return;
  21165. if (!this.plane)
  21166. this.plane = polygons[0].plane.clone();
  21167. var front = [], back = [];
  21168. for (var i = 0; i < polygons.length; i++) {
  21169. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  21170. }
  21171. if (front.length) {
  21172. if (!this.front)
  21173. this.front = new Node();
  21174. this.front.build(front);
  21175. }
  21176. if (back.length) {
  21177. if (!this.back)
  21178. this.back = new Node();
  21179. this.back.build(back);
  21180. }
  21181. };
  21182. return Node;
  21183. })();
  21184. var CSG = (function () {
  21185. function CSG() {
  21186. this.polygons = new Array();
  21187. }
  21188. // Convert BABYLON.Mesh to BABYLON.CSG
  21189. CSG.FromMesh = function (mesh) {
  21190. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  21191. if (mesh instanceof BABYLON.Mesh) {
  21192. mesh.computeWorldMatrix(true);
  21193. var matrix = mesh.getWorldMatrix();
  21194. var meshPosition = mesh.position.clone();
  21195. var meshRotation = mesh.rotation.clone();
  21196. var meshScaling = mesh.scaling.clone();
  21197. }
  21198. else {
  21199. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  21200. }
  21201. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21202. var subMeshes = mesh.subMeshes;
  21203. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  21204. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  21205. vertices = [];
  21206. for (var j = 0; j < 3; j++) {
  21207. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  21208. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  21209. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  21210. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  21211. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  21212. vertex = new Vertex(position, normal, uv);
  21213. vertices.push(vertex);
  21214. }
  21215. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  21216. // To handle the case of degenerated triangle
  21217. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  21218. if (polygon.plane)
  21219. polygons.push(polygon);
  21220. }
  21221. }
  21222. var csg = CSG.FromPolygons(polygons);
  21223. csg.matrix = matrix;
  21224. csg.position = meshPosition;
  21225. csg.rotation = meshRotation;
  21226. csg.scaling = meshScaling;
  21227. currentCSGMeshId++;
  21228. return csg;
  21229. };
  21230. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  21231. CSG.FromPolygons = function (polygons) {
  21232. var csg = new BABYLON.CSG();
  21233. csg.polygons = polygons;
  21234. return csg;
  21235. };
  21236. CSG.prototype.clone = function () {
  21237. var csg = new BABYLON.CSG();
  21238. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  21239. csg.copyTransformAttributes(this);
  21240. return csg;
  21241. };
  21242. CSG.prototype.toPolygons = function () {
  21243. return this.polygons;
  21244. };
  21245. CSG.prototype.union = function (csg) {
  21246. var a = new Node(this.clone().polygons);
  21247. var b = new Node(csg.clone().polygons);
  21248. a.clipTo(b);
  21249. b.clipTo(a);
  21250. b.invert();
  21251. b.clipTo(a);
  21252. b.invert();
  21253. a.build(b.allPolygons());
  21254. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  21255. };
  21256. CSG.prototype.unionInPlace = function (csg) {
  21257. var a = new Node(this.polygons);
  21258. var b = new Node(csg.polygons);
  21259. a.clipTo(b);
  21260. b.clipTo(a);
  21261. b.invert();
  21262. b.clipTo(a);
  21263. b.invert();
  21264. a.build(b.allPolygons());
  21265. this.polygons = a.allPolygons();
  21266. };
  21267. CSG.prototype.subtract = function (csg) {
  21268. var a = new Node(this.clone().polygons);
  21269. var b = new Node(csg.clone().polygons);
  21270. a.invert();
  21271. a.clipTo(b);
  21272. b.clipTo(a);
  21273. b.invert();
  21274. b.clipTo(a);
  21275. b.invert();
  21276. a.build(b.allPolygons());
  21277. a.invert();
  21278. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  21279. };
  21280. CSG.prototype.subtractInPlace = function (csg) {
  21281. var a = new Node(this.polygons);
  21282. var b = new Node(csg.polygons);
  21283. a.invert();
  21284. a.clipTo(b);
  21285. b.clipTo(a);
  21286. b.invert();
  21287. b.clipTo(a);
  21288. b.invert();
  21289. a.build(b.allPolygons());
  21290. a.invert();
  21291. this.polygons = a.allPolygons();
  21292. };
  21293. CSG.prototype.intersect = function (csg) {
  21294. var a = new Node(this.clone().polygons);
  21295. var b = new Node(csg.clone().polygons);
  21296. a.invert();
  21297. b.clipTo(a);
  21298. b.invert();
  21299. a.clipTo(b);
  21300. b.clipTo(a);
  21301. a.build(b.allPolygons());
  21302. a.invert();
  21303. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  21304. };
  21305. CSG.prototype.intersectInPlace = function (csg) {
  21306. var a = new Node(this.polygons);
  21307. var b = new Node(csg.polygons);
  21308. a.invert();
  21309. b.clipTo(a);
  21310. b.invert();
  21311. a.clipTo(b);
  21312. b.clipTo(a);
  21313. a.build(b.allPolygons());
  21314. a.invert();
  21315. this.polygons = a.allPolygons();
  21316. };
  21317. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  21318. // not modified.
  21319. CSG.prototype.inverse = function () {
  21320. var csg = this.clone();
  21321. csg.inverseInPlace();
  21322. return csg;
  21323. };
  21324. CSG.prototype.inverseInPlace = function () {
  21325. this.polygons.map(function (p) {
  21326. p.flip();
  21327. });
  21328. };
  21329. // This is used to keep meshes transformations so they can be restored
  21330. // when we build back a Babylon Mesh
  21331. // NB : All CSG operations are performed in world coordinates
  21332. CSG.prototype.copyTransformAttributes = function (csg) {
  21333. this.matrix = csg.matrix;
  21334. this.position = csg.position;
  21335. this.rotation = csg.rotation;
  21336. this.scaling = csg.scaling;
  21337. return this;
  21338. };
  21339. // Build Raw mesh from CSG
  21340. // Coordinates here are in world space
  21341. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  21342. var matrix = this.matrix.clone();
  21343. matrix.invert();
  21344. 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;
  21345. if (keepSubMeshes) {
  21346. // Sort Polygons, since subMeshes are indices range
  21347. polygons.sort(function (a, b) {
  21348. if (a.shared.meshId === b.shared.meshId) {
  21349. return a.shared.subMeshId - b.shared.subMeshId;
  21350. }
  21351. else {
  21352. return a.shared.meshId - b.shared.meshId;
  21353. }
  21354. });
  21355. }
  21356. for (var i = 0, il = polygons.length; i < il; i++) {
  21357. polygon = polygons[i];
  21358. // Building SubMeshes
  21359. if (!subMesh_dict[polygon.shared.meshId]) {
  21360. subMesh_dict[polygon.shared.meshId] = {};
  21361. }
  21362. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  21363. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  21364. indexStart: +Infinity,
  21365. indexEnd: -Infinity,
  21366. materialIndex: polygon.shared.materialIndex
  21367. };
  21368. }
  21369. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  21370. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  21371. polygonIndices[0] = 0;
  21372. polygonIndices[1] = j - 1;
  21373. polygonIndices[2] = j;
  21374. for (var k = 0; k < 3; k++) {
  21375. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  21376. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  21377. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  21378. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  21379. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  21380. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  21381. // Check if 2 points can be merged
  21382. 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)) {
  21383. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  21384. uvs.push(uv.x, uv.y);
  21385. normals.push(normal.x, normal.y, normal.z);
  21386. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  21387. }
  21388. indices.push(vertex_idx);
  21389. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  21390. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  21391. currentIndex++;
  21392. }
  21393. }
  21394. }
  21395. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  21396. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  21397. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  21398. mesh.setIndices(indices);
  21399. if (keepSubMeshes) {
  21400. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  21401. var materialIndexOffset = 0, materialMaxIndex;
  21402. mesh.subMeshes.length = 0;
  21403. for (var m in subMesh_dict) {
  21404. materialMaxIndex = -1;
  21405. for (var sm in subMesh_dict[m]) {
  21406. subMesh_obj = subMesh_dict[m][sm];
  21407. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  21408. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  21409. }
  21410. materialIndexOffset += ++materialMaxIndex;
  21411. }
  21412. }
  21413. return mesh;
  21414. };
  21415. // Build Mesh from CSG taking material and transforms into account
  21416. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  21417. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  21418. mesh.material = material;
  21419. mesh.position.copyFrom(this.position);
  21420. mesh.rotation.copyFrom(this.rotation);
  21421. mesh.scaling.copyFrom(this.scaling);
  21422. mesh.computeWorldMatrix(true);
  21423. return mesh;
  21424. };
  21425. return CSG;
  21426. })();
  21427. BABYLON.CSG = CSG;
  21428. })(BABYLON || (BABYLON = {}));
  21429. //# sourceMappingURL=babylon.csg.js.map
  21430. var BABYLON;
  21431. (function (BABYLON) {
  21432. var OculusDistortionCorrectionPostProcess = (function (_super) {
  21433. __extends(OculusDistortionCorrectionPostProcess, _super);
  21434. //ANY
  21435. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  21436. var _this = this;
  21437. _super.call(this, name, "oculusDistortionCorrection", [
  21438. 'LensCenter',
  21439. 'Scale',
  21440. 'ScaleIn',
  21441. 'HmdWarpParam'
  21442. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  21443. this._isRightEye = isRightEye;
  21444. this._distortionFactors = cameraSettings.DistortionK;
  21445. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  21446. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  21447. this.onSizeChanged = function () {
  21448. _this.aspectRatio = _this.width * .5 / _this.height;
  21449. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  21450. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  21451. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  21452. };
  21453. this.onApply = function (effect) {
  21454. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  21455. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  21456. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  21457. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  21458. };
  21459. }
  21460. return OculusDistortionCorrectionPostProcess;
  21461. })(BABYLON.PostProcess);
  21462. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  21463. })(BABYLON || (BABYLON = {}));
  21464. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  21465. // 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
  21466. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  21467. var BABYLON;
  21468. (function (BABYLON) {
  21469. (function (JoystickAxis) {
  21470. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  21471. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  21472. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  21473. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  21474. var JoystickAxis = BABYLON.JoystickAxis;
  21475. var VirtualJoystick = (function () {
  21476. function VirtualJoystick(leftJoystick) {
  21477. var _this = this;
  21478. if (leftJoystick) {
  21479. this._leftJoystick = true;
  21480. }
  21481. else {
  21482. this._leftJoystick = false;
  21483. }
  21484. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  21485. VirtualJoystick._globalJoystickIndex++;
  21486. // By default left & right arrow keys are moving the X
  21487. // and up & down keys are moving the Y
  21488. this._axisTargetedByLeftAndRight = 0 /* X */;
  21489. this._axisTargetedByUpAndDown = 1 /* Y */;
  21490. this.reverseLeftRight = false;
  21491. this.reverseUpDown = false;
  21492. // collections of pointers
  21493. this._touches = new BABYLON.SmartCollection();
  21494. this.deltaPosition = BABYLON.Vector3.Zero();
  21495. this._joystickSensibility = 25;
  21496. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  21497. this._rotationSpeed = 25;
  21498. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  21499. this._rotateOnAxisRelativeToMesh = false;
  21500. // injecting a canvas element on top of the canvas 3D game
  21501. if (!VirtualJoystick.vjCanvas) {
  21502. window.addEventListener("resize", function () {
  21503. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  21504. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  21505. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  21506. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  21507. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  21508. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  21509. }, false);
  21510. VirtualJoystick.vjCanvas = document.createElement("canvas");
  21511. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  21512. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  21513. VirtualJoystick.vjCanvas.width = window.innerWidth;
  21514. VirtualJoystick.vjCanvas.height = window.innerHeight;
  21515. VirtualJoystick.vjCanvas.style.width = "100%";
  21516. VirtualJoystick.vjCanvas.style.height = "100%";
  21517. VirtualJoystick.vjCanvas.style.position = "absolute";
  21518. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  21519. VirtualJoystick.vjCanvas.style.top = "0px";
  21520. VirtualJoystick.vjCanvas.style.left = "0px";
  21521. VirtualJoystick.vjCanvas.style.zIndex = "5";
  21522. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  21523. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  21524. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  21525. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  21526. document.body.appendChild(VirtualJoystick.vjCanvas);
  21527. }
  21528. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  21529. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  21530. this.pressed = false;
  21531. // default joystick color
  21532. this._joystickColor = "cyan";
  21533. this._joystickPointerID = -1;
  21534. // current joystick position
  21535. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  21536. // origin joystick position
  21537. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  21538. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  21539. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  21540. _this._onPointerDown(evt);
  21541. }, false);
  21542. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  21543. _this._onPointerMove(evt);
  21544. }, false);
  21545. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  21546. _this._onPointerUp(evt);
  21547. }, false);
  21548. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  21549. _this._onPointerUp(evt);
  21550. }, false);
  21551. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  21552. evt.preventDefault(); // Disables system menu
  21553. }, false);
  21554. requestAnimationFrame(function () {
  21555. _this._drawVirtualJoystick();
  21556. });
  21557. }
  21558. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  21559. this._joystickSensibility = newJoystickSensibility;
  21560. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  21561. };
  21562. VirtualJoystick.prototype._onPointerDown = function (e) {
  21563. var positionOnScreenCondition;
  21564. e.preventDefault();
  21565. if (this._leftJoystick === true) {
  21566. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  21567. }
  21568. else {
  21569. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  21570. }
  21571. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  21572. // First contact will be dedicated to the virtual joystick
  21573. this._joystickPointerID = e.pointerId;
  21574. this._joystickPointerStartPos.x = e.clientX;
  21575. this._joystickPointerStartPos.y = e.clientY;
  21576. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  21577. this._deltaJoystickVector.x = 0;
  21578. this._deltaJoystickVector.y = 0;
  21579. this.pressed = true;
  21580. this._touches.add(e.pointerId.toString(), e);
  21581. }
  21582. else {
  21583. // You can only trigger the action buttons with a joystick declared
  21584. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  21585. this._action();
  21586. this._touches.add(e.pointerId.toString(), e);
  21587. }
  21588. }
  21589. };
  21590. VirtualJoystick.prototype._onPointerMove = function (e) {
  21591. // If the current pointer is the one associated to the joystick (first touch contact)
  21592. if (this._joystickPointerID == e.pointerId) {
  21593. this._joystickPointerPos.x = e.clientX;
  21594. this._joystickPointerPos.y = e.clientY;
  21595. this._deltaJoystickVector = this._joystickPointerPos.clone();
  21596. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  21597. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  21598. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  21599. switch (this._axisTargetedByLeftAndRight) {
  21600. case 0 /* X */:
  21601. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  21602. break;
  21603. case 1 /* Y */:
  21604. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  21605. break;
  21606. case 2 /* Z */:
  21607. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  21608. break;
  21609. }
  21610. var directionUpDown = this.reverseUpDown ? 1 : -1;
  21611. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  21612. switch (this._axisTargetedByUpAndDown) {
  21613. case 0 /* X */:
  21614. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  21615. break;
  21616. case 1 /* Y */:
  21617. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  21618. break;
  21619. case 2 /* Z */:
  21620. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  21621. break;
  21622. }
  21623. }
  21624. else {
  21625. if (this._touches.item(e.pointerId.toString())) {
  21626. this._touches.item(e.pointerId.toString()).x = e.clientX;
  21627. this._touches.item(e.pointerId.toString()).y = e.clientY;
  21628. }
  21629. }
  21630. };
  21631. VirtualJoystick.prototype._onPointerUp = function (e) {
  21632. this._clearCanvas();
  21633. if (this._joystickPointerID == e.pointerId) {
  21634. this._joystickPointerID = -1;
  21635. this.pressed = false;
  21636. }
  21637. this._deltaJoystickVector.x = 0;
  21638. this._deltaJoystickVector.y = 0;
  21639. this._touches.remove(e.pointerId.toString());
  21640. };
  21641. /**
  21642. * Change the color of the virtual joystick
  21643. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  21644. */
  21645. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  21646. this._joystickColor = newColor;
  21647. };
  21648. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  21649. this._action = action;
  21650. };
  21651. // Define which axis you'd like to control for left & right
  21652. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  21653. switch (axis) {
  21654. case 0 /* X */:
  21655. case 1 /* Y */:
  21656. case 2 /* Z */:
  21657. this._axisTargetedByLeftAndRight = axis;
  21658. break;
  21659. default:
  21660. this._axisTargetedByLeftAndRight = 0 /* X */;
  21661. break;
  21662. }
  21663. };
  21664. // Define which axis you'd like to control for up & down
  21665. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  21666. switch (axis) {
  21667. case 0 /* X */:
  21668. case 1 /* Y */:
  21669. case 2 /* Z */:
  21670. this._axisTargetedByUpAndDown = axis;
  21671. break;
  21672. default:
  21673. this._axisTargetedByUpAndDown = 1 /* Y */;
  21674. break;
  21675. }
  21676. };
  21677. VirtualJoystick.prototype._clearCanvas = function () {
  21678. if (this._leftJoystick) {
  21679. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  21680. }
  21681. else {
  21682. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  21683. }
  21684. };
  21685. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  21686. var _this = this;
  21687. if (this.pressed) {
  21688. this._clearCanvas();
  21689. this._touches.forEach(function (touch) {
  21690. if (touch.pointerId === _this._joystickPointerID) {
  21691. VirtualJoystick.vjCanvasContext.beginPath();
  21692. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21693. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  21694. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  21695. VirtualJoystick.vjCanvasContext.stroke();
  21696. VirtualJoystick.vjCanvasContext.beginPath();
  21697. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21698. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  21699. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  21700. VirtualJoystick.vjCanvasContext.stroke();
  21701. VirtualJoystick.vjCanvasContext.beginPath();
  21702. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21703. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  21704. VirtualJoystick.vjCanvasContext.stroke();
  21705. }
  21706. else {
  21707. VirtualJoystick.vjCanvasContext.beginPath();
  21708. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  21709. VirtualJoystick.vjCanvasContext.beginPath();
  21710. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  21711. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  21712. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  21713. VirtualJoystick.vjCanvasContext.stroke();
  21714. }
  21715. ;
  21716. });
  21717. }
  21718. requestAnimationFrame(function () {
  21719. _this._drawVirtualJoystick();
  21720. });
  21721. };
  21722. VirtualJoystick.prototype.releaseCanvas = function () {
  21723. if (VirtualJoystick.vjCanvas) {
  21724. document.body.removeChild(VirtualJoystick.vjCanvas);
  21725. VirtualJoystick.vjCanvas = null;
  21726. }
  21727. };
  21728. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  21729. VirtualJoystick._globalJoystickIndex = 0;
  21730. return VirtualJoystick;
  21731. })();
  21732. BABYLON.VirtualJoystick = VirtualJoystick;
  21733. })(BABYLON || (BABYLON = {}));
  21734. //# sourceMappingURL=babylon.virtualJoystick.js.map
  21735. var BABYLON;
  21736. (function (BABYLON) {
  21737. var OculusRiftDevKit2013_Metric = {
  21738. HResolution: 1280,
  21739. VResolution: 800,
  21740. HScreenSize: 0.149759993,
  21741. VScreenSize: 0.0935999975,
  21742. VScreenCenter: 0.0467999987,
  21743. EyeToScreenDistance: 0.0410000011,
  21744. LensSeparationDistance: 0.0635000020,
  21745. InterpupillaryDistance: 0.0640000030,
  21746. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21747. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21748. PostProcessScaleFactor: 1.714605507808412,
  21749. LensCenterOffset: 0.151976421
  21750. };
  21751. var _OculusInnerCamera = (function (_super) {
  21752. __extends(_OculusInnerCamera, _super);
  21753. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  21754. _super.call(this, name, position, scene);
  21755. this._workMatrix = new BABYLON.Matrix();
  21756. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21757. // Constants
  21758. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21759. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21760. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21761. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21762. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21763. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21764. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21765. // Postprocess
  21766. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21767. }
  21768. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  21769. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21770. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21771. return this._projectionMatrix;
  21772. };
  21773. _OculusInnerCamera.prototype._getViewMatrix = function () {
  21774. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21775. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21776. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21777. // Computing target and final matrix
  21778. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21779. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21780. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21781. return this._viewMatrix;
  21782. };
  21783. return _OculusInnerCamera;
  21784. })(BABYLON.FreeCamera);
  21785. var OculusCamera = (function (_super) {
  21786. __extends(OculusCamera, _super);
  21787. function OculusCamera(name, position, scene) {
  21788. _super.call(this, name, position, scene);
  21789. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  21790. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  21791. this.subCameras.push(this._leftCamera);
  21792. this.subCameras.push(this._rightCamera);
  21793. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21794. }
  21795. OculusCamera.prototype._update = function () {
  21796. this._leftCamera.position.copyFrom(this.position);
  21797. this._rightCamera.position.copyFrom(this.position);
  21798. this._updateCamera(this._leftCamera);
  21799. this._updateCamera(this._rightCamera);
  21800. _super.prototype._update.call(this);
  21801. };
  21802. OculusCamera.prototype._updateCamera = function (camera) {
  21803. camera.minZ = this.minZ;
  21804. camera.maxZ = this.maxZ;
  21805. camera.rotation.x = this.rotation.x;
  21806. camera.rotation.y = this.rotation.y;
  21807. camera.rotation.z = this.rotation.z;
  21808. };
  21809. // Oculus events
  21810. OculusCamera.prototype._onOrientationEvent = function (evt) {
  21811. var yaw = evt.alpha / 180 * Math.PI;
  21812. var pitch = evt.beta / 180 * Math.PI;
  21813. var roll = evt.gamma / 180 * Math.PI;
  21814. if (!this._offsetOrientation) {
  21815. this._offsetOrientation = {
  21816. yaw: yaw,
  21817. pitch: pitch,
  21818. roll: roll
  21819. };
  21820. return;
  21821. }
  21822. else {
  21823. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21824. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21825. this.rotation.z += this._offsetOrientation.roll - roll;
  21826. this._offsetOrientation.yaw = yaw;
  21827. this._offsetOrientation.pitch = pitch;
  21828. this._offsetOrientation.roll = roll;
  21829. }
  21830. };
  21831. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  21832. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21833. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21834. };
  21835. OculusCamera.prototype.detachControl = function (element) {
  21836. _super.prototype.detachControl.call(this, element);
  21837. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21838. };
  21839. return OculusCamera;
  21840. })(BABYLON.FreeCamera);
  21841. BABYLON.OculusCamera = OculusCamera;
  21842. })(BABYLON || (BABYLON = {}));
  21843. //# sourceMappingURL=babylon.oculusCamera.js.map
  21844. var BABYLON;
  21845. (function (BABYLON) {
  21846. var OculusRiftDevKit2013_Metric = {
  21847. HResolution: 1280,
  21848. VResolution: 800,
  21849. HScreenSize: 0.149759993,
  21850. VScreenSize: 0.0935999975,
  21851. VScreenCenter: 0.0467999987,
  21852. EyeToScreenDistance: 0.0410000011,
  21853. LensSeparationDistance: 0.0635000020,
  21854. InterpupillaryDistance: 0.0640000030,
  21855. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21856. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21857. PostProcessScaleFactor: 1.714605507808412,
  21858. LensCenterOffset: 0.151976421
  21859. };
  21860. var _OculusInnerGamepadCamera = (function (_super) {
  21861. __extends(_OculusInnerGamepadCamera, _super);
  21862. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  21863. _super.call(this, name, position, scene);
  21864. this._workMatrix = new BABYLON.Matrix();
  21865. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21866. // Constants
  21867. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21868. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21869. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21870. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21871. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21872. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21873. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21874. // Postprocess
  21875. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21876. }
  21877. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  21878. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21879. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21880. return this._projectionMatrix;
  21881. };
  21882. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  21883. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21884. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21885. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21886. // Computing target and final matrix
  21887. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21888. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21889. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21890. return this._viewMatrix;
  21891. };
  21892. return _OculusInnerGamepadCamera;
  21893. })(BABYLON.FreeCamera);
  21894. var OculusGamepadCamera = (function (_super) {
  21895. __extends(OculusGamepadCamera, _super);
  21896. function OculusGamepadCamera(name, position, scene) {
  21897. var _this = this;
  21898. _super.call(this, name, position, scene);
  21899. this.angularSensibility = 200;
  21900. this.moveSensibility = 75;
  21901. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  21902. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  21903. this.subCameras.push(this._leftCamera);
  21904. this.subCameras.push(this._rightCamera);
  21905. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21906. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  21907. _this._onNewGameConnected(gamepad);
  21908. });
  21909. }
  21910. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  21911. // Only the first gamepad can control the camera
  21912. if (gamepad.index === 0) {
  21913. this._gamepad = gamepad;
  21914. }
  21915. };
  21916. OculusGamepadCamera.prototype._update = function () {
  21917. this._leftCamera.position.copyFrom(this.position);
  21918. this._rightCamera.position.copyFrom(this.position);
  21919. this._updateCamera(this._leftCamera);
  21920. this._updateCamera(this._rightCamera);
  21921. _super.prototype._update.call(this);
  21922. };
  21923. OculusGamepadCamera.prototype._checkInputs = function () {
  21924. if (!this._gamepad) {
  21925. return;
  21926. }
  21927. var LSValues = this._gamepad.leftStick;
  21928. var normalizedLX = LSValues.x / this.moveSensibility;
  21929. var normalizedLY = LSValues.y / this.moveSensibility;
  21930. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  21931. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  21932. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21933. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  21934. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21935. };
  21936. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  21937. camera.minZ = this.minZ;
  21938. camera.maxZ = this.maxZ;
  21939. camera.rotation.x = this.rotation.x;
  21940. camera.rotation.y = this.rotation.y;
  21941. camera.rotation.z = this.rotation.z;
  21942. };
  21943. // Oculus events
  21944. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  21945. var yaw = evt.alpha / 180 * Math.PI;
  21946. var pitch = evt.beta / 180 * Math.PI;
  21947. var roll = evt.gamma / 180 * Math.PI;
  21948. if (!this._offsetOrientation) {
  21949. this._offsetOrientation = {
  21950. yaw: yaw,
  21951. pitch: pitch,
  21952. roll: roll
  21953. };
  21954. return;
  21955. }
  21956. else {
  21957. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21958. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21959. this.rotation.z += this._offsetOrientation.roll - roll;
  21960. this._offsetOrientation.yaw = yaw;
  21961. this._offsetOrientation.pitch = pitch;
  21962. this._offsetOrientation.roll = roll;
  21963. }
  21964. };
  21965. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  21966. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21967. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21968. };
  21969. OculusGamepadCamera.prototype.detachControl = function (element) {
  21970. _super.prototype.detachControl.call(this, element);
  21971. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21972. };
  21973. OculusGamepadCamera.prototype.dispose = function () {
  21974. this._gamepads.dispose();
  21975. _super.prototype.dispose.call(this);
  21976. };
  21977. return OculusGamepadCamera;
  21978. })(BABYLON.FreeCamera);
  21979. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  21980. })(BABYLON || (BABYLON = {}));
  21981. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  21982. var BABYLON;
  21983. (function (BABYLON) {
  21984. // We're mainly based on the logic defined into the FreeCamera code
  21985. var VirtualJoysticksCamera = (function (_super) {
  21986. __extends(VirtualJoysticksCamera, _super);
  21987. function VirtualJoysticksCamera(name, position, scene) {
  21988. _super.call(this, name, position, scene);
  21989. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  21990. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  21991. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  21992. this._leftjoystick.setJoystickSensibility(0.15);
  21993. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  21994. this._rightjoystick.setAxisForUpDown(0 /* X */);
  21995. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  21996. this._rightjoystick.reverseUpDown = true;
  21997. this._rightjoystick.setJoystickSensibility(0.05);
  21998. this._rightjoystick.setJoystickColor("yellow");
  21999. }
  22000. VirtualJoysticksCamera.prototype._checkInputs = function () {
  22001. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  22002. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  22003. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  22004. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  22005. if (!this._leftjoystick.pressed) {
  22006. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  22007. }
  22008. if (!this._rightjoystick.pressed) {
  22009. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  22010. }
  22011. };
  22012. VirtualJoysticksCamera.prototype.dispose = function () {
  22013. this._leftjoystick.releaseCanvas();
  22014. _super.prototype.dispose.call(this);
  22015. };
  22016. return VirtualJoysticksCamera;
  22017. })(BABYLON.FreeCamera);
  22018. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  22019. })(BABYLON || (BABYLON = {}));
  22020. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  22021. var BABYLON;
  22022. (function (BABYLON) {
  22023. var ShaderMaterial = (function (_super) {
  22024. __extends(ShaderMaterial, _super);
  22025. function ShaderMaterial(name, scene, shaderPath, options) {
  22026. _super.call(this, name, scene);
  22027. this._textures = new Array();
  22028. this._floats = new Array();
  22029. this._floatsArrays = {};
  22030. this._colors3 = new Array();
  22031. this._colors4 = new Array();
  22032. this._vectors2 = new Array();
  22033. this._vectors3 = new Array();
  22034. this._matrices = new Array();
  22035. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  22036. this._shaderPath = shaderPath;
  22037. options.needAlphaBlending = options.needAlphaBlending || false;
  22038. options.needAlphaTesting = options.needAlphaTesting || false;
  22039. options.attributes = options.attributes || ["position", "normal", "uv"];
  22040. options.uniforms = options.uniforms || ["worldViewProjection"];
  22041. options.samplers = options.samplers || [];
  22042. this._options = options;
  22043. }
  22044. ShaderMaterial.prototype.needAlphaBlending = function () {
  22045. return this._options.needAlphaBlending;
  22046. };
  22047. ShaderMaterial.prototype.needAlphaTesting = function () {
  22048. return this._options.needAlphaTesting;
  22049. };
  22050. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  22051. if (this._options.uniforms.indexOf(uniformName) === -1) {
  22052. this._options.uniforms.push(uniformName);
  22053. }
  22054. };
  22055. ShaderMaterial.prototype.setTexture = function (name, texture) {
  22056. if (this._options.samplers.indexOf(name) === -1) {
  22057. this._options.samplers.push(name);
  22058. }
  22059. this._textures[name] = texture;
  22060. return this;
  22061. };
  22062. ShaderMaterial.prototype.setFloat = function (name, value) {
  22063. this._checkUniform(name);
  22064. this._floats[name] = value;
  22065. return this;
  22066. };
  22067. ShaderMaterial.prototype.setFloats = function (name, value) {
  22068. this._checkUniform(name);
  22069. this._floatsArrays[name] = value;
  22070. return this;
  22071. };
  22072. ShaderMaterial.prototype.setColor3 = function (name, value) {
  22073. this._checkUniform(name);
  22074. this._colors3[name] = value;
  22075. return this;
  22076. };
  22077. ShaderMaterial.prototype.setColor4 = function (name, value) {
  22078. this._checkUniform(name);
  22079. this._colors4[name] = value;
  22080. return this;
  22081. };
  22082. ShaderMaterial.prototype.setVector2 = function (name, value) {
  22083. this._checkUniform(name);
  22084. this._vectors2[name] = value;
  22085. return this;
  22086. };
  22087. ShaderMaterial.prototype.setVector3 = function (name, value) {
  22088. this._checkUniform(name);
  22089. this._vectors3[name] = value;
  22090. return this;
  22091. };
  22092. ShaderMaterial.prototype.setMatrix = function (name, value) {
  22093. this._checkUniform(name);
  22094. this._matrices[name] = value;
  22095. return this;
  22096. };
  22097. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  22098. var scene = this.getScene();
  22099. var engine = scene.getEngine();
  22100. if (!this.checkReadyOnEveryCall) {
  22101. if (this._renderId === scene.getRenderId()) {
  22102. return true;
  22103. }
  22104. }
  22105. // Instances
  22106. var defines = [];
  22107. var fallbacks = new BABYLON.EffectFallbacks();
  22108. if (useInstances) {
  22109. defines.push("#define INSTANCES");
  22110. }
  22111. // Bones
  22112. if (mesh && mesh.useBones) {
  22113. defines.push("#define BONES");
  22114. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  22115. defines.push("#define BONES4");
  22116. fallbacks.addFallback(0, "BONES4");
  22117. }
  22118. // Alpha test
  22119. if (engine.getAlphaTesting()) {
  22120. defines.push("#define ALPHATEST");
  22121. }
  22122. var previousEffect = this._effect;
  22123. var join = defines.join("\n");
  22124. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  22125. if (!this._effect.isReady()) {
  22126. return false;
  22127. }
  22128. if (previousEffect !== this._effect) {
  22129. scene.resetCachedMaterial();
  22130. }
  22131. this._renderId = scene.getRenderId();
  22132. return true;
  22133. };
  22134. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  22135. var scene = this.getScene();
  22136. if (this._options.uniforms.indexOf("world") !== -1) {
  22137. this._effect.setMatrix("world", world);
  22138. }
  22139. if (this._options.uniforms.indexOf("worldView") !== -1) {
  22140. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  22141. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  22142. }
  22143. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  22144. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  22145. }
  22146. };
  22147. ShaderMaterial.prototype.bind = function (world, mesh) {
  22148. // Std values
  22149. this.bindOnlyWorldMatrix(world);
  22150. if (this.getScene().getCachedMaterial() !== this) {
  22151. if (this._options.uniforms.indexOf("view") !== -1) {
  22152. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  22153. }
  22154. if (this._options.uniforms.indexOf("projection") !== -1) {
  22155. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  22156. }
  22157. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  22158. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  22159. }
  22160. // Bones
  22161. if (mesh && mesh.useBones) {
  22162. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  22163. }
  22164. for (var name in this._textures) {
  22165. this._effect.setTexture(name, this._textures[name]);
  22166. }
  22167. for (name in this._floats) {
  22168. this._effect.setFloat(name, this._floats[name]);
  22169. }
  22170. for (name in this._floatsArrays) {
  22171. this._effect.setArray(name, this._floatsArrays[name]);
  22172. }
  22173. for (name in this._colors3) {
  22174. this._effect.setColor3(name, this._colors3[name]);
  22175. }
  22176. for (name in this._colors4) {
  22177. var color = this._colors4[name];
  22178. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  22179. }
  22180. for (name in this._vectors2) {
  22181. this._effect.setVector2(name, this._vectors2[name]);
  22182. }
  22183. for (name in this._vectors3) {
  22184. this._effect.setVector3(name, this._vectors3[name]);
  22185. }
  22186. for (name in this._matrices) {
  22187. this._effect.setMatrix(name, this._matrices[name]);
  22188. }
  22189. }
  22190. _super.prototype.bind.call(this, world, mesh);
  22191. };
  22192. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  22193. for (var name in this._textures) {
  22194. this._textures[name].dispose();
  22195. }
  22196. this._textures = [];
  22197. _super.prototype.dispose.call(this, forceDisposeEffect);
  22198. };
  22199. return ShaderMaterial;
  22200. })(BABYLON.Material);
  22201. BABYLON.ShaderMaterial = ShaderMaterial;
  22202. })(BABYLON || (BABYLON = {}));
  22203. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  22204. (function (BABYLON) {
  22205. var VertexData = (function () {
  22206. function VertexData() {
  22207. }
  22208. VertexData.prototype.set = function (data, kind) {
  22209. switch (kind) {
  22210. case BABYLON.VertexBuffer.PositionKind:
  22211. this.positions = data;
  22212. break;
  22213. case BABYLON.VertexBuffer.NormalKind:
  22214. this.normals = data;
  22215. break;
  22216. case BABYLON.VertexBuffer.UVKind:
  22217. this.uvs = data;
  22218. break;
  22219. case BABYLON.VertexBuffer.UV2Kind:
  22220. this.uv2s = data;
  22221. break;
  22222. case BABYLON.VertexBuffer.ColorKind:
  22223. this.colors = data;
  22224. break;
  22225. case BABYLON.VertexBuffer.MatricesIndicesKind:
  22226. this.matricesIndices = data;
  22227. break;
  22228. case BABYLON.VertexBuffer.MatricesWeightsKind:
  22229. this.matricesWeights = data;
  22230. break;
  22231. }
  22232. };
  22233. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  22234. this._applyTo(mesh, updatable);
  22235. };
  22236. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  22237. this._applyTo(geometry, updatable);
  22238. };
  22239. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  22240. this._update(mesh);
  22241. };
  22242. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  22243. this._update(geometry);
  22244. };
  22245. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  22246. if (this.positions) {
  22247. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  22248. }
  22249. if (this.normals) {
  22250. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  22251. }
  22252. if (this.uvs) {
  22253. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  22254. }
  22255. if (this.uv2s) {
  22256. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  22257. }
  22258. if (this.colors) {
  22259. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  22260. }
  22261. if (this.matricesIndices) {
  22262. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  22263. }
  22264. if (this.matricesWeights) {
  22265. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  22266. }
  22267. if (this.indices) {
  22268. meshOrGeometry.setIndices(this.indices);
  22269. }
  22270. };
  22271. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  22272. if (this.positions) {
  22273. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  22274. }
  22275. if (this.normals) {
  22276. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  22277. }
  22278. if (this.uvs) {
  22279. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  22280. }
  22281. if (this.uv2s) {
  22282. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  22283. }
  22284. if (this.colors) {
  22285. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  22286. }
  22287. if (this.matricesIndices) {
  22288. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  22289. }
  22290. if (this.matricesWeights) {
  22291. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  22292. }
  22293. if (this.indices) {
  22294. meshOrGeometry.setIndices(this.indices);
  22295. }
  22296. };
  22297. VertexData.prototype.transform = function (matrix) {
  22298. var transformed = BABYLON.Vector3.Zero();
  22299. if (this.positions) {
  22300. var position = BABYLON.Vector3.Zero();
  22301. for (var index = 0; index < this.positions.length; index += 3) {
  22302. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  22303. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  22304. this.positions[index] = transformed.x;
  22305. this.positions[index + 1] = transformed.y;
  22306. this.positions[index + 2] = transformed.z;
  22307. }
  22308. }
  22309. if (this.normals) {
  22310. var normal = BABYLON.Vector3.Zero();
  22311. for (index = 0; index < this.normals.length; index += 3) {
  22312. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  22313. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  22314. this.normals[index] = transformed.x;
  22315. this.normals[index + 1] = transformed.y;
  22316. this.normals[index + 2] = transformed.z;
  22317. }
  22318. }
  22319. };
  22320. VertexData.prototype.merge = function (other) {
  22321. if (other.indices) {
  22322. if (!this.indices) {
  22323. this.indices = [];
  22324. }
  22325. var offset = this.positions ? this.positions.length / 3 : 0;
  22326. for (var index = 0; index < other.indices.length; index++) {
  22327. this.indices.push(other.indices[index] + offset);
  22328. }
  22329. }
  22330. if (other.positions) {
  22331. if (!this.positions) {
  22332. this.positions = [];
  22333. }
  22334. for (index = 0; index < other.positions.length; index++) {
  22335. this.positions.push(other.positions[index]);
  22336. }
  22337. }
  22338. if (other.normals) {
  22339. if (!this.normals) {
  22340. this.normals = [];
  22341. }
  22342. for (index = 0; index < other.normals.length; index++) {
  22343. this.normals.push(other.normals[index]);
  22344. }
  22345. }
  22346. if (other.uvs) {
  22347. if (!this.uvs) {
  22348. this.uvs = [];
  22349. }
  22350. for (index = 0; index < other.uvs.length; index++) {
  22351. this.uvs.push(other.uvs[index]);
  22352. }
  22353. }
  22354. if (other.uv2s) {
  22355. if (!this.uv2s) {
  22356. this.uv2s = [];
  22357. }
  22358. for (index = 0; index < other.uv2s.length; index++) {
  22359. this.uv2s.push(other.uv2s[index]);
  22360. }
  22361. }
  22362. if (other.matricesIndices) {
  22363. if (!this.matricesIndices) {
  22364. this.matricesIndices = [];
  22365. }
  22366. for (index = 0; index < other.matricesIndices.length; index++) {
  22367. this.matricesIndices.push(other.matricesIndices[index]);
  22368. }
  22369. }
  22370. if (other.matricesWeights) {
  22371. if (!this.matricesWeights) {
  22372. this.matricesWeights = [];
  22373. }
  22374. for (index = 0; index < other.matricesWeights.length; index++) {
  22375. this.matricesWeights.push(other.matricesWeights[index]);
  22376. }
  22377. }
  22378. if (other.colors) {
  22379. if (!this.colors) {
  22380. this.colors = [];
  22381. }
  22382. for (index = 0; index < other.colors.length; index++) {
  22383. this.colors.push(other.colors[index]);
  22384. }
  22385. }
  22386. };
  22387. // Statics
  22388. VertexData.ExtractFromMesh = function (mesh) {
  22389. return VertexData._ExtractFrom(mesh);
  22390. };
  22391. VertexData.ExtractFromGeometry = function (geometry) {
  22392. return VertexData._ExtractFrom(geometry);
  22393. };
  22394. VertexData._ExtractFrom = function (meshOrGeometry) {
  22395. var result = new VertexData();
  22396. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22397. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22398. }
  22399. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22400. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22401. }
  22402. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22403. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22404. }
  22405. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22406. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  22407. }
  22408. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22409. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  22410. }
  22411. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22412. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22413. }
  22414. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22415. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22416. }
  22417. result.indices = meshOrGeometry.getIndices();
  22418. return result;
  22419. };
  22420. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  22421. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22422. closeArray = closeArray || false;
  22423. closePath = closePath || false;
  22424. var defaultOffset = Math.floor(pathArray[0].length / 2);
  22425. offset = offset || defaultOffset;
  22426. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  22427. var positions = [];
  22428. var indices = [];
  22429. var normals = [];
  22430. var uvs = [];
  22431. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  22432. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  22433. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  22434. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  22435. var minlg; // minimal length among all paths from pathArray
  22436. var lg = []; // array of path lengths : nb of vertex per path
  22437. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  22438. var p; // path iterator
  22439. var i; // point iterator
  22440. var j; // point iterator
  22441. // if single path in pathArray
  22442. if (pathArray.length < 2) {
  22443. var ar1 = [];
  22444. var ar2 = [];
  22445. for (i = 0; i < pathArray[0].length - offset; i++) {
  22446. ar1.push(pathArray[0][i]);
  22447. ar2.push(pathArray[0][i + offset]);
  22448. }
  22449. pathArray = [ar1, ar2];
  22450. }
  22451. // positions and horizontal distances (u)
  22452. var idc = 0;
  22453. minlg = pathArray[0].length;
  22454. for (p = 0; p < pathArray.length; p++) {
  22455. uTotalDistance[p] = 0;
  22456. us[p] = [0];
  22457. var path = pathArray[p];
  22458. var l = path.length;
  22459. minlg = (minlg < l) ? minlg : l;
  22460. lg[p] = l;
  22461. idx[p] = idc;
  22462. j = 0;
  22463. while (j < l) {
  22464. positions.push(path[j].x, path[j].y, path[j].z);
  22465. if (j > 0) {
  22466. var vectlg = path[j].subtract(path[j - 1]).length();
  22467. var dist = vectlg + uTotalDistance[p];
  22468. us[p].push(dist);
  22469. uTotalDistance[p] = dist;
  22470. }
  22471. j++;
  22472. }
  22473. if (closePath) {
  22474. vectlg = path[0].subtract(path[j - 1]).length();
  22475. dist = vectlg + uTotalDistance[p];
  22476. uTotalDistance[p] = dist;
  22477. }
  22478. idc += l;
  22479. }
  22480. for (i = 0; i < minlg; i++) {
  22481. vTotalDistance[i] = 0;
  22482. vs[i] = [0];
  22483. var path1;
  22484. var path2;
  22485. for (p = 0; p < pathArray.length - 1; p++) {
  22486. path1 = pathArray[p];
  22487. path2 = pathArray[p + 1];
  22488. vectlg = path2[i].subtract(path1[i]).length();
  22489. dist = vectlg + vTotalDistance[i];
  22490. vs[i].push(dist);
  22491. vTotalDistance[i] = dist;
  22492. }
  22493. if (closeArray) {
  22494. path1 = pathArray[p];
  22495. path2 = pathArray[0];
  22496. vectlg = path2[i].subtract(path1[i]).length();
  22497. dist = vectlg + vTotalDistance[i];
  22498. vTotalDistance[i] = dist;
  22499. }
  22500. }
  22501. // uvs
  22502. var u;
  22503. var v;
  22504. for (p = 0; p < pathArray.length; p++) {
  22505. for (i = 0; i < minlg; i++) {
  22506. u = us[p][i] / uTotalDistance[p];
  22507. v = vs[i][p] / vTotalDistance[i];
  22508. uvs.push(u, v);
  22509. }
  22510. }
  22511. // indices
  22512. p = 0; // path index
  22513. var pi = 0; // positions array index
  22514. var l1 = lg[p] - 1; // path1 length
  22515. var l2 = lg[p + 1] - 1; // path2 length
  22516. var min = (l1 < l2) ? l1 : l2; // current path stop index
  22517. var shft = idx[1] - idx[0]; // shift
  22518. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  22519. var t1; // two consecutive triangles, so 4 points : point1
  22520. var t2; // point2
  22521. var t3; // point3
  22522. var t4; // point4
  22523. while (pi <= min && p < path1nb) {
  22524. // 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
  22525. t1 = pi;
  22526. t2 = pi + shft;
  22527. t3 = pi + 1;
  22528. t4 = pi + shft + 1;
  22529. indices.push(pi, pi + shft, pi + 1);
  22530. indices.push(pi + shft + 1, pi + 1, pi + shft);
  22531. pi += 1;
  22532. if (pi === min) {
  22533. if (closePath) {
  22534. indices.push(pi, pi + shft, idx[p]);
  22535. indices.push(idx[p] + shft, idx[p], pi + shft);
  22536. t3 = idx[p];
  22537. t4 = idx[p] + shft;
  22538. }
  22539. p++;
  22540. if (p === lg.length - 1) {
  22541. shft = idx[0] - idx[p];
  22542. l1 = lg[p] - 1;
  22543. l2 = lg[0] - 1;
  22544. }
  22545. else {
  22546. shft = idx[p + 1] - idx[p];
  22547. l1 = lg[p] - 1;
  22548. l2 = lg[p + 1] - 1;
  22549. }
  22550. pi = idx[p];
  22551. min = (l1 < l2) ? l1 + pi : l2 + pi;
  22552. }
  22553. }
  22554. // normals
  22555. VertexData.ComputeNormals(positions, indices, normals);
  22556. // sides
  22557. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22558. // Result
  22559. var vertexData = new VertexData();
  22560. vertexData.indices = indices;
  22561. vertexData.positions = positions;
  22562. vertexData.normals = normals;
  22563. vertexData.uvs = uvs;
  22564. return vertexData;
  22565. };
  22566. VertexData.CreateBox = function (size, sideOrientation) {
  22567. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22568. var normalsSource = [
  22569. new BABYLON.Vector3(0, 0, 1),
  22570. new BABYLON.Vector3(0, 0, -1),
  22571. new BABYLON.Vector3(1, 0, 0),
  22572. new BABYLON.Vector3(-1, 0, 0),
  22573. new BABYLON.Vector3(0, 1, 0),
  22574. new BABYLON.Vector3(0, -1, 0)
  22575. ];
  22576. var indices = [];
  22577. var positions = [];
  22578. var normals = [];
  22579. var uvs = [];
  22580. size = size || 1;
  22581. for (var index = 0; index < normalsSource.length; index++) {
  22582. var normal = normalsSource[index];
  22583. // Get two vectors perpendicular to the face normal and to each other.
  22584. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  22585. var side2 = BABYLON.Vector3.Cross(normal, side1);
  22586. // Six indices (two triangles) per face.
  22587. var verticesLength = positions.length / 3;
  22588. indices.push(verticesLength);
  22589. indices.push(verticesLength + 1);
  22590. indices.push(verticesLength + 2);
  22591. indices.push(verticesLength);
  22592. indices.push(verticesLength + 2);
  22593. indices.push(verticesLength + 3);
  22594. // Four vertices per face.
  22595. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  22596. positions.push(vertex.x, vertex.y, vertex.z);
  22597. normals.push(normal.x, normal.y, normal.z);
  22598. uvs.push(1.0, 1.0);
  22599. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  22600. positions.push(vertex.x, vertex.y, vertex.z);
  22601. normals.push(normal.x, normal.y, normal.z);
  22602. uvs.push(0.0, 1.0);
  22603. vertex = normal.add(side1).add(side2).scale(size / 2);
  22604. positions.push(vertex.x, vertex.y, vertex.z);
  22605. normals.push(normal.x, normal.y, normal.z);
  22606. uvs.push(0.0, 0.0);
  22607. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  22608. positions.push(vertex.x, vertex.y, vertex.z);
  22609. normals.push(normal.x, normal.y, normal.z);
  22610. uvs.push(1.0, 0.0);
  22611. }
  22612. // sides
  22613. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22614. // Result
  22615. var vertexData = new VertexData();
  22616. vertexData.indices = indices;
  22617. vertexData.positions = positions;
  22618. vertexData.normals = normals;
  22619. vertexData.uvs = uvs;
  22620. return vertexData;
  22621. };
  22622. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  22623. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22624. segments = segments || 32;
  22625. diameter = diameter || 1;
  22626. var radius = diameter / 2;
  22627. var totalZRotationSteps = 2 + segments;
  22628. var totalYRotationSteps = 2 * totalZRotationSteps;
  22629. var indices = [];
  22630. var positions = [];
  22631. var normals = [];
  22632. var uvs = [];
  22633. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  22634. var normalizedZ = zRotationStep / totalZRotationSteps;
  22635. var angleZ = (normalizedZ * Math.PI);
  22636. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  22637. var normalizedY = yRotationStep / totalYRotationSteps;
  22638. var angleY = normalizedY * Math.PI * 2;
  22639. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  22640. var rotationY = BABYLON.Matrix.RotationY(angleY);
  22641. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  22642. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  22643. var vertex = complete.scale(radius);
  22644. var normal = BABYLON.Vector3.Normalize(vertex);
  22645. positions.push(vertex.x, vertex.y, vertex.z);
  22646. normals.push(normal.x, normal.y, normal.z);
  22647. uvs.push(normalizedZ, normalizedY);
  22648. }
  22649. if (zRotationStep > 0) {
  22650. var verticesCount = positions.length / 3;
  22651. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  22652. indices.push((firstIndex));
  22653. indices.push((firstIndex + 1));
  22654. indices.push(firstIndex + totalYRotationSteps + 1);
  22655. indices.push((firstIndex + totalYRotationSteps + 1));
  22656. indices.push((firstIndex + 1));
  22657. indices.push((firstIndex + totalYRotationSteps + 2));
  22658. }
  22659. }
  22660. }
  22661. // Sides
  22662. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22663. // Result
  22664. var vertexData = new VertexData();
  22665. vertexData.indices = indices;
  22666. vertexData.positions = positions;
  22667. vertexData.normals = normals;
  22668. vertexData.uvs = uvs;
  22669. return vertexData;
  22670. };
  22671. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  22672. if (subdivisions === void 0) { subdivisions = 1; }
  22673. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22674. var radiusTop = diameterTop / 2;
  22675. var radiusBottom = diameterBottom / 2;
  22676. var indices = [];
  22677. var positions = [];
  22678. var normals = [];
  22679. var uvs = [];
  22680. height = height || 1;
  22681. diameterTop = diameterTop || 0.5;
  22682. diameterBottom = diameterBottom || 1;
  22683. tessellation = tessellation || 16;
  22684. subdivisions = subdivisions || 1;
  22685. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  22686. var getCircleVector = function (i) {
  22687. var angle = (i * 2.0 * Math.PI / tessellation);
  22688. var dx = Math.cos(angle);
  22689. var dz = Math.sin(angle);
  22690. return new BABYLON.Vector3(dx, 0, dz);
  22691. };
  22692. var createCylinderCap = function (isTop) {
  22693. var radius = isTop ? radiusTop : radiusBottom;
  22694. if (radius === 0) {
  22695. return;
  22696. }
  22697. var vbase = positions.length / 3;
  22698. var offset = new BABYLON.Vector3(0, height / 2, 0);
  22699. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  22700. if (!isTop) {
  22701. offset.scaleInPlace(-1);
  22702. textureScale.x = -textureScale.x;
  22703. }
  22704. for (var i = 0; i < tessellation; i++) {
  22705. var circleVector = getCircleVector(i);
  22706. var position = circleVector.scale(radius).add(offset);
  22707. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  22708. positions.push(position.x, position.y, position.z);
  22709. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22710. }
  22711. for (i = 0; i < tessellation - 2; i++) {
  22712. if (!isTop) {
  22713. indices.push(vbase);
  22714. indices.push(vbase + (i + 2) % tessellation);
  22715. indices.push(vbase + (i + 1) % tessellation);
  22716. }
  22717. else {
  22718. indices.push(vbase);
  22719. indices.push(vbase + (i + 1) % tessellation);
  22720. indices.push(vbase + (i + 2) % tessellation);
  22721. }
  22722. }
  22723. };
  22724. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  22725. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  22726. var stride = tessellation + 1;
  22727. for (var i = 0; i <= tessellation; i++) {
  22728. var circleVector = getCircleVector(i);
  22729. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  22730. var position, radius = radiusBottom;
  22731. for (var s = 0; s <= subdivisions; s++) {
  22732. // Update variables
  22733. position = circleVector.scale(radius);
  22734. position.addInPlace(base.add(offset.scale(s)));
  22735. textureCoordinate.y += 1 / subdivisions;
  22736. radius += (radiusTop - radiusBottom) / subdivisions;
  22737. // Push in arrays
  22738. positions.push(position.x, position.y, position.z);
  22739. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22740. }
  22741. }
  22742. subdivisions += 1;
  22743. for (s = 0; s < subdivisions - 1; s++) {
  22744. for (i = 0; i <= tessellation; i++) {
  22745. indices.push(i * subdivisions + s);
  22746. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  22747. indices.push(i * subdivisions + (s + 1));
  22748. indices.push(i * subdivisions + (s + 1));
  22749. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  22750. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  22751. }
  22752. }
  22753. // Create flat triangle fan caps to seal the top and bottom.
  22754. createCylinderCap(true);
  22755. createCylinderCap(false);
  22756. // Normals
  22757. VertexData.ComputeNormals(positions, indices, normals);
  22758. // Sides
  22759. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22760. // Result
  22761. var vertexData = new VertexData();
  22762. vertexData.indices = indices;
  22763. vertexData.positions = positions;
  22764. vertexData.normals = normals;
  22765. vertexData.uvs = uvs;
  22766. return vertexData;
  22767. };
  22768. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  22769. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22770. var indices = [];
  22771. var positions = [];
  22772. var normals = [];
  22773. var uvs = [];
  22774. diameter = diameter || 1;
  22775. thickness = thickness || 0.5;
  22776. tessellation = tessellation || 16;
  22777. var stride = tessellation + 1;
  22778. for (var i = 0; i <= tessellation; i++) {
  22779. var u = i / tessellation;
  22780. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  22781. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  22782. for (var j = 0; j <= tessellation; j++) {
  22783. var v = 1 - j / tessellation;
  22784. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  22785. var dx = Math.cos(innerAngle);
  22786. var dy = Math.sin(innerAngle);
  22787. // Create a vertex.
  22788. var normal = new BABYLON.Vector3(dx, dy, 0);
  22789. var position = normal.scale(thickness / 2);
  22790. var textureCoordinate = new BABYLON.Vector2(u, v);
  22791. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  22792. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  22793. positions.push(position.x, position.y, position.z);
  22794. normals.push(normal.x, normal.y, normal.z);
  22795. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22796. // And create indices for two triangles.
  22797. var nextI = (i + 1) % stride;
  22798. var nextJ = (j + 1) % stride;
  22799. indices.push(i * stride + j);
  22800. indices.push(i * stride + nextJ);
  22801. indices.push(nextI * stride + j);
  22802. indices.push(i * stride + nextJ);
  22803. indices.push(nextI * stride + nextJ);
  22804. indices.push(nextI * stride + j);
  22805. }
  22806. }
  22807. // Sides
  22808. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22809. // Result
  22810. var vertexData = new VertexData();
  22811. vertexData.indices = indices;
  22812. vertexData.positions = positions;
  22813. vertexData.normals = normals;
  22814. vertexData.uvs = uvs;
  22815. return vertexData;
  22816. };
  22817. VertexData.CreateLines = function (points) {
  22818. var indices = [];
  22819. var positions = [];
  22820. for (var index = 0; index < points.length; index++) {
  22821. positions.push(points[index].x, points[index].y, points[index].z);
  22822. if (index > 0) {
  22823. indices.push(index - 1);
  22824. indices.push(index);
  22825. }
  22826. }
  22827. // Result
  22828. var vertexData = new VertexData();
  22829. vertexData.indices = indices;
  22830. vertexData.positions = positions;
  22831. return vertexData;
  22832. };
  22833. VertexData.CreateGround = function (width, height, subdivisions) {
  22834. var indices = [];
  22835. var positions = [];
  22836. var normals = [];
  22837. var uvs = [];
  22838. var row, col;
  22839. width = width || 1;
  22840. height = height || 1;
  22841. subdivisions = subdivisions || 1;
  22842. for (row = 0; row <= subdivisions; row++) {
  22843. for (col = 0; col <= subdivisions; col++) {
  22844. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22845. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22846. positions.push(position.x, position.y, position.z);
  22847. normals.push(normal.x, normal.y, normal.z);
  22848. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22849. }
  22850. }
  22851. for (row = 0; row < subdivisions; row++) {
  22852. for (col = 0; col < subdivisions; col++) {
  22853. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22854. indices.push(col + 1 + row * (subdivisions + 1));
  22855. indices.push(col + row * (subdivisions + 1));
  22856. indices.push(col + (row + 1) * (subdivisions + 1));
  22857. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22858. indices.push(col + row * (subdivisions + 1));
  22859. }
  22860. }
  22861. // Result
  22862. var vertexData = new VertexData();
  22863. vertexData.indices = indices;
  22864. vertexData.positions = positions;
  22865. vertexData.normals = normals;
  22866. vertexData.uvs = uvs;
  22867. return vertexData;
  22868. };
  22869. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  22870. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  22871. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  22872. var indices = [];
  22873. var positions = [];
  22874. var normals = [];
  22875. var uvs = [];
  22876. var row, col, tileRow, tileCol;
  22877. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  22878. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  22879. precision.w = (precision.w < 1) ? 1 : precision.w;
  22880. precision.h = (precision.h < 1) ? 1 : precision.h;
  22881. var tileSize = {
  22882. 'w': (xmax - xmin) / subdivisions.w,
  22883. 'h': (zmax - zmin) / subdivisions.h
  22884. };
  22885. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  22886. // Indices
  22887. var base = positions.length / 3;
  22888. var rowLength = precision.w + 1;
  22889. for (row = 0; row < precision.h; row++) {
  22890. for (col = 0; col < precision.w; col++) {
  22891. var square = [
  22892. base + col + row * rowLength,
  22893. base + (col + 1) + row * rowLength,
  22894. base + (col + 1) + (row + 1) * rowLength,
  22895. base + col + (row + 1) * rowLength
  22896. ];
  22897. indices.push(square[1]);
  22898. indices.push(square[2]);
  22899. indices.push(square[3]);
  22900. indices.push(square[0]);
  22901. indices.push(square[1]);
  22902. indices.push(square[3]);
  22903. }
  22904. }
  22905. // Position, normals and uvs
  22906. var position = BABYLON.Vector3.Zero();
  22907. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22908. for (row = 0; row <= precision.h; row++) {
  22909. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  22910. for (col = 0; col <= precision.w; col++) {
  22911. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  22912. position.y = 0;
  22913. positions.push(position.x, position.y, position.z);
  22914. normals.push(normal.x, normal.y, normal.z);
  22915. uvs.push(col / precision.w, row / precision.h);
  22916. }
  22917. }
  22918. }
  22919. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  22920. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  22921. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  22922. }
  22923. }
  22924. // Result
  22925. var vertexData = new VertexData();
  22926. vertexData.indices = indices;
  22927. vertexData.positions = positions;
  22928. vertexData.normals = normals;
  22929. vertexData.uvs = uvs;
  22930. return vertexData;
  22931. };
  22932. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  22933. var indices = [];
  22934. var positions = [];
  22935. var normals = [];
  22936. var uvs = [];
  22937. var row, col;
  22938. for (row = 0; row <= subdivisions; row++) {
  22939. for (col = 0; col <= subdivisions; col++) {
  22940. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22941. // Compute height
  22942. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  22943. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  22944. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  22945. var r = buffer[pos] / 255.0;
  22946. var g = buffer[pos + 1] / 255.0;
  22947. var b = buffer[pos + 2] / 255.0;
  22948. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22949. position.y = minHeight + (maxHeight - minHeight) * gradient;
  22950. // Add vertex
  22951. positions.push(position.x, position.y, position.z);
  22952. normals.push(0, 0, 0);
  22953. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22954. }
  22955. }
  22956. for (row = 0; row < subdivisions; row++) {
  22957. for (col = 0; col < subdivisions; col++) {
  22958. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22959. indices.push(col + 1 + row * (subdivisions + 1));
  22960. indices.push(col + row * (subdivisions + 1));
  22961. indices.push(col + (row + 1) * (subdivisions + 1));
  22962. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22963. indices.push(col + row * (subdivisions + 1));
  22964. }
  22965. }
  22966. // Normals
  22967. VertexData.ComputeNormals(positions, indices, normals);
  22968. // Result
  22969. var vertexData = new VertexData();
  22970. vertexData.indices = indices;
  22971. vertexData.positions = positions;
  22972. vertexData.normals = normals;
  22973. vertexData.uvs = uvs;
  22974. return vertexData;
  22975. };
  22976. VertexData.CreatePlane = function (size, sideOrientation) {
  22977. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22978. var indices = [];
  22979. var positions = [];
  22980. var normals = [];
  22981. var uvs = [];
  22982. size = size || 1;
  22983. // Vertices
  22984. var halfSize = size / 2.0;
  22985. positions.push(-halfSize, -halfSize, 0);
  22986. normals.push(0, 0, -1.0);
  22987. uvs.push(0.0, 0.0);
  22988. positions.push(halfSize, -halfSize, 0);
  22989. normals.push(0, 0, -1.0);
  22990. uvs.push(1.0, 0.0);
  22991. positions.push(halfSize, halfSize, 0);
  22992. normals.push(0, 0, -1.0);
  22993. uvs.push(1.0, 1.0);
  22994. positions.push(-halfSize, halfSize, 0);
  22995. normals.push(0, 0, -1.0);
  22996. uvs.push(0.0, 1.0);
  22997. // Indices
  22998. indices.push(0);
  22999. indices.push(1);
  23000. indices.push(2);
  23001. indices.push(0);
  23002. indices.push(2);
  23003. indices.push(3);
  23004. // Sides
  23005. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23006. // Result
  23007. var vertexData = new VertexData();
  23008. vertexData.indices = indices;
  23009. vertexData.positions = positions;
  23010. vertexData.normals = normals;
  23011. vertexData.uvs = uvs;
  23012. return vertexData;
  23013. };
  23014. VertexData.CreateDisc = function (radius, tessellation, sideOrientation) {
  23015. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  23016. var positions = [];
  23017. var indices = [];
  23018. var normals = [];
  23019. var uvs = [];
  23020. // positions and uvs
  23021. positions.push(0, 0, 0); // disc center first
  23022. uvs.push(0.5, 0.5);
  23023. var step = Math.PI * 2 / tessellation;
  23024. for (var a = 0; a < Math.PI * 2; a += step) {
  23025. var x = Math.cos(a);
  23026. var y = Math.sin(a);
  23027. var u = (x + 1) / 2;
  23028. var v = (1 - y) / 2;
  23029. positions.push(radius * x, radius * y, 0);
  23030. uvs.push(u, v);
  23031. }
  23032. positions.push(positions[3], positions[4], positions[5]); // close the circle
  23033. uvs.push(uvs[2], uvs[3]);
  23034. //indices
  23035. var vertexNb = positions.length / 3;
  23036. for (var i = 1; i < vertexNb - 1; i++) {
  23037. indices.push(i + 1, 0, i);
  23038. }
  23039. // result
  23040. VertexData.ComputeNormals(positions, indices, normals);
  23041. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23042. var vertexData = new VertexData();
  23043. vertexData.indices = indices;
  23044. vertexData.positions = positions;
  23045. vertexData.normals = normals;
  23046. vertexData.uvs = uvs;
  23047. return vertexData;
  23048. };
  23049. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  23050. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  23051. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  23052. var indices = [];
  23053. var positions = [];
  23054. var normals = [];
  23055. var uvs = [];
  23056. radius = radius || 2;
  23057. tube = tube || 0.5;
  23058. radialSegments = radialSegments || 32;
  23059. tubularSegments = tubularSegments || 32;
  23060. p = p || 2;
  23061. q = q || 3;
  23062. // Helper
  23063. var getPos = function (angle) {
  23064. var cu = Math.cos(angle);
  23065. var su = Math.sin(angle);
  23066. var quOverP = q / p * angle;
  23067. var cs = Math.cos(quOverP);
  23068. var tx = radius * (2 + cs) * 0.5 * cu;
  23069. var ty = radius * (2 + cs) * su * 0.5;
  23070. var tz = radius * Math.sin(quOverP) * 0.5;
  23071. return new BABYLON.Vector3(tx, ty, tz);
  23072. };
  23073. for (var i = 0; i <= radialSegments; i++) {
  23074. var modI = i % radialSegments;
  23075. var u = modI / radialSegments * 2 * p * Math.PI;
  23076. var p1 = getPos(u);
  23077. var p2 = getPos(u + 0.01);
  23078. var tang = p2.subtract(p1);
  23079. var n = p2.add(p1);
  23080. var bitan = BABYLON.Vector3.Cross(tang, n);
  23081. n = BABYLON.Vector3.Cross(bitan, tang);
  23082. bitan.normalize();
  23083. n.normalize();
  23084. for (var j = 0; j < tubularSegments; j++) {
  23085. var modJ = j % tubularSegments;
  23086. var v = modJ / tubularSegments * 2 * Math.PI;
  23087. var cx = -tube * Math.cos(v);
  23088. var cy = tube * Math.sin(v);
  23089. positions.push(p1.x + cx * n.x + cy * bitan.x);
  23090. positions.push(p1.y + cx * n.y + cy * bitan.y);
  23091. positions.push(p1.z + cx * n.z + cy * bitan.z);
  23092. uvs.push(i / radialSegments);
  23093. uvs.push(j / tubularSegments);
  23094. }
  23095. }
  23096. for (i = 0; i < radialSegments; i++) {
  23097. for (j = 0; j < tubularSegments; j++) {
  23098. var jNext = (j + 1) % tubularSegments;
  23099. var a = i * tubularSegments + j;
  23100. var b = (i + 1) * tubularSegments + j;
  23101. var c = (i + 1) * tubularSegments + jNext;
  23102. var d = i * tubularSegments + jNext;
  23103. indices.push(d);
  23104. indices.push(b);
  23105. indices.push(a);
  23106. indices.push(d);
  23107. indices.push(c);
  23108. indices.push(b);
  23109. }
  23110. }
  23111. // Normals
  23112. VertexData.ComputeNormals(positions, indices, normals);
  23113. // Sides
  23114. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  23115. // Result
  23116. var vertexData = new VertexData();
  23117. vertexData.indices = indices;
  23118. vertexData.positions = positions;
  23119. vertexData.normals = normals;
  23120. vertexData.uvs = uvs;
  23121. return vertexData;
  23122. };
  23123. // Tools
  23124. /**
  23125. * @param {any} - positions (number[] or Float32Array)
  23126. * @param {any} - indices (number[] or Uint16Array)
  23127. * @param {any} - normals (number[] or Float32Array)
  23128. */
  23129. VertexData.ComputeNormals = function (positions, indices, normals) {
  23130. var positionVectors = [];
  23131. var facesOfVertices = [];
  23132. var index;
  23133. for (index = 0; index < positions.length; index += 3) {
  23134. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  23135. positionVectors.push(vector3);
  23136. facesOfVertices.push([]);
  23137. }
  23138. // Compute normals
  23139. var facesNormals = [];
  23140. for (index = 0; index < indices.length / 3; index++) {
  23141. var i1 = indices[index * 3];
  23142. var i2 = indices[index * 3 + 1];
  23143. var i3 = indices[index * 3 + 2];
  23144. var p1 = positionVectors[i1];
  23145. var p2 = positionVectors[i2];
  23146. var p3 = positionVectors[i3];
  23147. var p1p2 = p1.subtract(p2);
  23148. var p3p2 = p3.subtract(p2);
  23149. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  23150. facesOfVertices[i1].push(index);
  23151. facesOfVertices[i2].push(index);
  23152. facesOfVertices[i3].push(index);
  23153. }
  23154. for (index = 0; index < positionVectors.length; index++) {
  23155. var faces = facesOfVertices[index];
  23156. var normal = BABYLON.Vector3.Zero();
  23157. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  23158. normal.addInPlace(facesNormals[faces[faceIndex]]);
  23159. }
  23160. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  23161. normals[index * 3] = normal.x;
  23162. normals[index * 3 + 1] = normal.y;
  23163. normals[index * 3 + 2] = normal.z;
  23164. }
  23165. };
  23166. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  23167. var li = indices.length;
  23168. var ln = normals.length;
  23169. var i;
  23170. var n;
  23171. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23172. switch (sideOrientation) {
  23173. case BABYLON.Mesh.FRONTSIDE:
  23174. break;
  23175. case BABYLON.Mesh.BACKSIDE:
  23176. var tmp;
  23177. for (i = 0; i < li; i += 3) {
  23178. tmp = indices[i];
  23179. indices[i] = indices[i + 2];
  23180. indices[i + 2] = tmp;
  23181. }
  23182. for (n = 0; n < ln; n++) {
  23183. normals[n] = -normals[n];
  23184. }
  23185. break;
  23186. case BABYLON.Mesh.DOUBLESIDE:
  23187. // positions
  23188. var lp = positions.length;
  23189. var l = lp / 3;
  23190. for (var p = 0; p < lp; p++) {
  23191. positions[lp + p] = positions[p];
  23192. }
  23193. for (i = 0; i < li; i += 3) {
  23194. indices[i + li] = indices[i + 2] + l;
  23195. indices[i + 1 + li] = indices[i + 1] + l;
  23196. indices[i + 2 + li] = indices[i] + l;
  23197. }
  23198. for (n = 0; n < ln; n++) {
  23199. normals[ln + n] = -normals[n];
  23200. }
  23201. // uvs
  23202. var lu = uvs.length;
  23203. for (var u = 0; u < lu; u++) {
  23204. uvs[u + lu] = uvs[u];
  23205. }
  23206. break;
  23207. }
  23208. };
  23209. return VertexData;
  23210. })();
  23211. BABYLON.VertexData = VertexData;
  23212. })(BABYLON || (BABYLON = {}));
  23213. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  23214. var BABYLON;
  23215. (function (BABYLON) {
  23216. var buildCamera = function (that, name) {
  23217. that._leftCamera.isIntermediate = true;
  23218. that.subCameras.push(that._leftCamera);
  23219. that.subCameras.push(that._rightCamera);
  23220. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  23221. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  23222. that._anaglyphPostProcess.onApply = function (effect) {
  23223. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  23224. };
  23225. that._update();
  23226. };
  23227. var AnaglyphArcRotateCamera = (function (_super) {
  23228. __extends(AnaglyphArcRotateCamera, _super);
  23229. // ANY
  23230. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  23231. _super.call(this, name, alpha, beta, radius, target, scene);
  23232. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  23233. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  23234. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  23235. buildCamera(this, name);
  23236. }
  23237. AnaglyphArcRotateCamera.prototype._update = function () {
  23238. this._updateCamera(this._leftCamera);
  23239. this._updateCamera(this._rightCamera);
  23240. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  23241. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  23242. _super.prototype._update.call(this);
  23243. };
  23244. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  23245. camera.beta = this.beta;
  23246. camera.radius = this.radius;
  23247. camera.minZ = this.minZ;
  23248. camera.maxZ = this.maxZ;
  23249. camera.fov = this.fov;
  23250. camera.target = this.target;
  23251. };
  23252. return AnaglyphArcRotateCamera;
  23253. })(BABYLON.ArcRotateCamera);
  23254. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  23255. var AnaglyphFreeCamera = (function (_super) {
  23256. __extends(AnaglyphFreeCamera, _super);
  23257. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  23258. _super.call(this, name, position, scene);
  23259. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  23260. this._transformMatrix = new BABYLON.Matrix();
  23261. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  23262. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  23263. buildCamera(this, name);
  23264. }
  23265. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  23266. var target = this.getTarget();
  23267. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  23268. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  23269. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  23270. };
  23271. AnaglyphFreeCamera.prototype._update = function () {
  23272. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  23273. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  23274. this._updateCamera(this._leftCamera);
  23275. this._updateCamera(this._rightCamera);
  23276. _super.prototype._update.call(this);
  23277. };
  23278. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  23279. camera.minZ = this.minZ;
  23280. camera.maxZ = this.maxZ;
  23281. camera.fov = this.fov;
  23282. camera.viewport = this.viewport;
  23283. camera.setTarget(this.getTarget());
  23284. };
  23285. return AnaglyphFreeCamera;
  23286. })(BABYLON.FreeCamera);
  23287. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  23288. })(BABYLON || (BABYLON = {}));
  23289. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  23290. var BABYLON;
  23291. (function (BABYLON) {
  23292. var AnaglyphPostProcess = (function (_super) {
  23293. __extends(AnaglyphPostProcess, _super);
  23294. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23295. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  23296. }
  23297. return AnaglyphPostProcess;
  23298. })(BABYLON.PostProcess);
  23299. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  23300. })(BABYLON || (BABYLON = {}));
  23301. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  23302. (function (BABYLON) {
  23303. var Tags = (function () {
  23304. function Tags() {
  23305. }
  23306. Tags.EnableFor = function (obj) {
  23307. obj._tags = obj._tags || {};
  23308. obj.hasTags = function () {
  23309. return Tags.HasTags(obj);
  23310. };
  23311. obj.addTags = function (tagsString) {
  23312. return Tags.AddTagsTo(obj, tagsString);
  23313. };
  23314. obj.removeTags = function (tagsString) {
  23315. return Tags.RemoveTagsFrom(obj, tagsString);
  23316. };
  23317. obj.matchesTagsQuery = function (tagsQuery) {
  23318. return Tags.MatchesQuery(obj, tagsQuery);
  23319. };
  23320. };
  23321. Tags.DisableFor = function (obj) {
  23322. delete obj._tags;
  23323. delete obj.hasTags;
  23324. delete obj.addTags;
  23325. delete obj.removeTags;
  23326. delete obj.matchesTagsQuery;
  23327. };
  23328. Tags.HasTags = function (obj) {
  23329. if (!obj._tags) {
  23330. return false;
  23331. }
  23332. return !BABYLON.Tools.IsEmpty(obj._tags);
  23333. };
  23334. Tags.GetTags = function (obj) {
  23335. if (!obj._tags) {
  23336. return null;
  23337. }
  23338. return obj._tags;
  23339. };
  23340. // the tags 'true' and 'false' are reserved and cannot be used as tags
  23341. // a tag cannot start with '||', '&&', and '!'
  23342. // it cannot contain whitespaces
  23343. Tags.AddTagsTo = function (obj, tagsString) {
  23344. if (!tagsString) {
  23345. return;
  23346. }
  23347. var tags = tagsString.split(" ");
  23348. for (var t in tags) {
  23349. Tags._AddTagTo(obj, tags[t]);
  23350. }
  23351. };
  23352. Tags._AddTagTo = function (obj, tag) {
  23353. tag = tag.trim();
  23354. if (tag === "" || tag === "true" || tag === "false") {
  23355. return;
  23356. }
  23357. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  23358. return;
  23359. }
  23360. Tags.EnableFor(obj);
  23361. obj._tags[tag] = true;
  23362. };
  23363. Tags.RemoveTagsFrom = function (obj, tagsString) {
  23364. if (!Tags.HasTags(obj)) {
  23365. return;
  23366. }
  23367. var tags = tagsString.split(" ");
  23368. for (var t in tags) {
  23369. Tags._RemoveTagFrom(obj, tags[t]);
  23370. }
  23371. };
  23372. Tags._RemoveTagFrom = function (obj, tag) {
  23373. delete obj._tags[tag];
  23374. };
  23375. Tags.MatchesQuery = function (obj, tagsQuery) {
  23376. if (tagsQuery === undefined) {
  23377. return true;
  23378. }
  23379. if (tagsQuery === "") {
  23380. return Tags.HasTags(obj);
  23381. }
  23382. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  23383. };
  23384. return Tags;
  23385. })();
  23386. BABYLON.Tags = Tags;
  23387. })(BABYLON || (BABYLON = {}));
  23388. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  23389. (function (BABYLON) {
  23390. var Internals;
  23391. (function (Internals) {
  23392. var AndOrNotEvaluator = (function () {
  23393. function AndOrNotEvaluator() {
  23394. }
  23395. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  23396. if (!query.match(/\([^\(\)]*\)/g)) {
  23397. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  23398. }
  23399. else {
  23400. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  23401. // remove parenthesis
  23402. r = r.slice(1, r.length - 1);
  23403. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  23404. });
  23405. }
  23406. if (query === "true") {
  23407. return true;
  23408. }
  23409. if (query === "false") {
  23410. return false;
  23411. }
  23412. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  23413. };
  23414. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  23415. evaluateCallback = evaluateCallback || (function (r) {
  23416. return r === "true" ? true : false;
  23417. });
  23418. var result;
  23419. var or = parenthesisContent.split("||");
  23420. for (var i in or) {
  23421. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  23422. var and = ori.split("&&");
  23423. if (and.length > 1) {
  23424. for (var j = 0; j < and.length; ++j) {
  23425. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  23426. if (andj !== "true" && andj !== "false") {
  23427. if (andj[0] === "!") {
  23428. result = !evaluateCallback(andj.substring(1));
  23429. }
  23430. else {
  23431. result = evaluateCallback(andj);
  23432. }
  23433. }
  23434. else {
  23435. result = andj === "true" ? true : false;
  23436. }
  23437. if (!result) {
  23438. ori = "false";
  23439. break;
  23440. }
  23441. }
  23442. }
  23443. if (result || ori === "true") {
  23444. result = true;
  23445. break;
  23446. }
  23447. // result equals false (or undefined)
  23448. if (ori !== "true" && ori !== "false") {
  23449. if (ori[0] === "!") {
  23450. result = !evaluateCallback(ori.substring(1));
  23451. }
  23452. else {
  23453. result = evaluateCallback(ori);
  23454. }
  23455. }
  23456. else {
  23457. result = ori === "true" ? true : false;
  23458. }
  23459. }
  23460. // the whole parenthesis scope is replaced by 'true' or 'false'
  23461. return result ? "true" : "false";
  23462. };
  23463. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  23464. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  23465. // remove whitespaces
  23466. r = r.replace(/[\s]/g, function () { return ""; });
  23467. return r.length % 2 ? "!" : "";
  23468. });
  23469. booleanString = booleanString.trim();
  23470. if (booleanString === "!true") {
  23471. booleanString = "false";
  23472. }
  23473. else if (booleanString === "!false") {
  23474. booleanString = "true";
  23475. }
  23476. return booleanString;
  23477. };
  23478. return AndOrNotEvaluator;
  23479. })();
  23480. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  23481. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23482. })(BABYLON || (BABYLON = {}));
  23483. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  23484. (function (BABYLON) {
  23485. var PostProcessRenderPass = (function () {
  23486. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  23487. this._enabled = true;
  23488. this._refCount = 0;
  23489. this._name = name;
  23490. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  23491. this.setRenderList(renderList);
  23492. this._renderTexture.onBeforeRender = beforeRender;
  23493. this._renderTexture.onAfterRender = afterRender;
  23494. this._scene = scene;
  23495. this._renderList = renderList;
  23496. }
  23497. // private
  23498. PostProcessRenderPass.prototype._incRefCount = function () {
  23499. if (this._refCount === 0) {
  23500. this._scene.customRenderTargets.push(this._renderTexture);
  23501. }
  23502. return ++this._refCount;
  23503. };
  23504. PostProcessRenderPass.prototype._decRefCount = function () {
  23505. this._refCount--;
  23506. if (this._refCount <= 0) {
  23507. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  23508. }
  23509. return this._refCount;
  23510. };
  23511. PostProcessRenderPass.prototype._update = function () {
  23512. this.setRenderList(this._renderList);
  23513. };
  23514. // public
  23515. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  23516. this._renderTexture.renderList = renderList;
  23517. };
  23518. PostProcessRenderPass.prototype.getRenderTexture = function () {
  23519. return this._renderTexture;
  23520. };
  23521. return PostProcessRenderPass;
  23522. })();
  23523. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  23524. })(BABYLON || (BABYLON = {}));
  23525. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  23526. (function (BABYLON) {
  23527. var PostProcessRenderEffect = (function () {
  23528. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  23529. this._engine = engine;
  23530. this._name = name;
  23531. this._singleInstance = singleInstance || true;
  23532. this._getPostProcess = getPostProcess;
  23533. this._cameras = [];
  23534. this._indicesForCamera = [];
  23535. this._postProcesses = {};
  23536. this._renderPasses = {};
  23537. this._renderEffectAsPasses = {};
  23538. }
  23539. PostProcessRenderEffect.prototype._update = function () {
  23540. for (var renderPassName in this._renderPasses) {
  23541. this._renderPasses[renderPassName]._update();
  23542. }
  23543. };
  23544. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  23545. this._renderPasses[renderPass._name] = renderPass;
  23546. this._linkParameters();
  23547. };
  23548. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  23549. delete this._renderPasses[renderPass._name];
  23550. this._linkParameters();
  23551. };
  23552. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  23553. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  23554. this._linkParameters();
  23555. };
  23556. PostProcessRenderEffect.prototype.getPass = function (passName) {
  23557. for (var renderPassName in this._renderPasses) {
  23558. if (renderPassName === passName) {
  23559. return this._renderPasses[passName];
  23560. }
  23561. }
  23562. };
  23563. PostProcessRenderEffect.prototype.emptyPasses = function () {
  23564. this._renderPasses = {};
  23565. this._linkParameters();
  23566. };
  23567. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  23568. var cameraKey;
  23569. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23570. for (var i = 0; i < _cam.length; i++) {
  23571. var camera = _cam[i];
  23572. var cameraName = camera.name;
  23573. if (this._singleInstance) {
  23574. cameraKey = 0;
  23575. }
  23576. else {
  23577. cameraKey = cameraName;
  23578. }
  23579. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  23580. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  23581. if (!this._indicesForCamera[cameraName]) {
  23582. this._indicesForCamera[cameraName] = [];
  23583. }
  23584. this._indicesForCamera[cameraName].push(index);
  23585. if (this._cameras.indexOf(camera) === -1) {
  23586. this._cameras[cameraName] = camera;
  23587. }
  23588. for (var passName in this._renderPasses) {
  23589. this._renderPasses[passName]._incRefCount();
  23590. }
  23591. }
  23592. this._linkParameters();
  23593. };
  23594. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  23595. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23596. for (var i = 0; i < _cam.length; i++) {
  23597. var camera = _cam[i];
  23598. var cameraName = camera.name;
  23599. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  23600. var index = this._cameras.indexOf(cameraName);
  23601. this._indicesForCamera.splice(index, 1);
  23602. this._cameras.splice(index, 1);
  23603. for (var passName in this._renderPasses) {
  23604. this._renderPasses[passName]._decRefCount();
  23605. }
  23606. }
  23607. };
  23608. PostProcessRenderEffect.prototype._enable = function (cameras) {
  23609. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23610. for (var i = 0; i < _cam.length; i++) {
  23611. var camera = _cam[i];
  23612. var cameraName = camera.name;
  23613. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  23614. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  23615. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  23616. }
  23617. }
  23618. for (var passName in this._renderPasses) {
  23619. this._renderPasses[passName]._incRefCount();
  23620. }
  23621. }
  23622. };
  23623. PostProcessRenderEffect.prototype._disable = function (cameras) {
  23624. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23625. for (var i = 0; i < _cam.length; i++) {
  23626. var camera = _cam[i];
  23627. var cameraName = camera.Name;
  23628. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  23629. for (var passName in this._renderPasses) {
  23630. this._renderPasses[passName]._decRefCount();
  23631. }
  23632. }
  23633. };
  23634. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  23635. if (this._singleInstance) {
  23636. return this._postProcesses[0];
  23637. }
  23638. else {
  23639. return this._postProcesses[camera.name];
  23640. }
  23641. };
  23642. PostProcessRenderEffect.prototype._linkParameters = function () {
  23643. var _this = this;
  23644. for (var index in this._postProcesses) {
  23645. if (this.applyParameters) {
  23646. this.applyParameters(this._postProcesses[index]);
  23647. }
  23648. this._postProcesses[index].onBeforeRender = function (effect) {
  23649. _this._linkTextures(effect);
  23650. };
  23651. }
  23652. };
  23653. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  23654. for (var renderPassName in this._renderPasses) {
  23655. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  23656. }
  23657. for (var renderEffectName in this._renderEffectAsPasses) {
  23658. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  23659. }
  23660. };
  23661. return PostProcessRenderEffect;
  23662. })();
  23663. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  23664. })(BABYLON || (BABYLON = {}));
  23665. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  23666. (function (BABYLON) {
  23667. var PostProcessRenderPipeline = (function () {
  23668. function PostProcessRenderPipeline(engine, name) {
  23669. this._engine = engine;
  23670. this._name = name;
  23671. this._renderEffects = {};
  23672. this._renderEffectsForIsolatedPass = {};
  23673. this._cameras = [];
  23674. }
  23675. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  23676. this._renderEffects[renderEffect._name] = renderEffect;
  23677. };
  23678. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  23679. var renderEffects = this._renderEffects[renderEffectName];
  23680. if (!renderEffects) {
  23681. return;
  23682. }
  23683. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  23684. };
  23685. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  23686. var renderEffects = this._renderEffects[renderEffectName];
  23687. if (!renderEffects) {
  23688. return;
  23689. }
  23690. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  23691. };
  23692. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  23693. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23694. var indicesToDelete = [];
  23695. for (var i = 0; i < _cam.length; i++) {
  23696. var camera = _cam[i];
  23697. var cameraName = camera.name;
  23698. if (this._cameras.indexOf(camera) === -1) {
  23699. this._cameras[cameraName] = camera;
  23700. }
  23701. else if (unique) {
  23702. indicesToDelete.push(i);
  23703. }
  23704. }
  23705. for (var i = 0; i < indicesToDelete.length; i++) {
  23706. cameras.splice(indicesToDelete[i], 1);
  23707. }
  23708. for (var renderEffectName in this._renderEffects) {
  23709. this._renderEffects[renderEffectName]._attachCameras(_cam);
  23710. }
  23711. };
  23712. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  23713. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23714. for (var renderEffectName in this._renderEffects) {
  23715. this._renderEffects[renderEffectName]._detachCameras(_cam);
  23716. }
  23717. for (var i = 0; i < _cam.length; i++) {
  23718. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  23719. }
  23720. };
  23721. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  23722. var _this = this;
  23723. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23724. var pass = null;
  23725. for (var renderEffectName in this._renderEffects) {
  23726. pass = this._renderEffects[renderEffectName].getPass(passName);
  23727. if (pass != null) {
  23728. break;
  23729. }
  23730. }
  23731. if (pass === null) {
  23732. return;
  23733. }
  23734. for (var renderEffectName in this._renderEffects) {
  23735. this._renderEffects[renderEffectName]._disable(_cam);
  23736. }
  23737. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  23738. for (var i = 0; i < _cam.length; i++) {
  23739. var camera = _cam[i];
  23740. var cameraName = camera.name;
  23741. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  23742. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  23743. });
  23744. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  23745. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  23746. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  23747. }
  23748. };
  23749. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  23750. var _this = this;
  23751. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23752. for (var i = 0; i < _cam.length; i++) {
  23753. var camera = _cam[i];
  23754. var cameraName = camera.name;
  23755. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  23756. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  23757. });
  23758. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  23759. }
  23760. for (var renderEffectName in this._renderEffects) {
  23761. this._renderEffects[renderEffectName]._enable(_cam);
  23762. }
  23763. };
  23764. PostProcessRenderPipeline.prototype._update = function () {
  23765. for (var renderEffectName in this._renderEffects) {
  23766. this._renderEffects[renderEffectName]._update();
  23767. }
  23768. for (var i = 0; i < this._cameras.length; i++) {
  23769. var cameraName = this._cameras[i].name;
  23770. if (this._renderEffectsForIsolatedPass[cameraName]) {
  23771. this._renderEffectsForIsolatedPass[cameraName]._update();
  23772. }
  23773. }
  23774. };
  23775. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  23776. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  23777. return PostProcessRenderPipeline;
  23778. })();
  23779. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  23780. })(BABYLON || (BABYLON = {}));
  23781. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  23782. (function (BABYLON) {
  23783. var PostProcessRenderPipelineManager = (function () {
  23784. function PostProcessRenderPipelineManager() {
  23785. this._renderPipelines = {};
  23786. }
  23787. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  23788. this._renderPipelines[renderPipeline._name] = renderPipeline;
  23789. };
  23790. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  23791. var renderPipeline = this._renderPipelines[renderPipelineName];
  23792. if (!renderPipeline) {
  23793. return;
  23794. }
  23795. renderPipeline._attachCameras(cameras, unique);
  23796. };
  23797. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  23798. var renderPipeline = this._renderPipelines[renderPipelineName];
  23799. if (!renderPipeline) {
  23800. return;
  23801. }
  23802. renderPipeline._detachCameras(cameras);
  23803. };
  23804. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  23805. var renderPipeline = this._renderPipelines[renderPipelineName];
  23806. if (!renderPipeline) {
  23807. return;
  23808. }
  23809. renderPipeline._enableEffect(renderEffectName, cameras);
  23810. };
  23811. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  23812. var renderPipeline = this._renderPipelines[renderPipelineName];
  23813. if (!renderPipeline) {
  23814. return;
  23815. }
  23816. renderPipeline._disableEffect(renderEffectName, cameras);
  23817. };
  23818. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  23819. var renderPipeline = this._renderPipelines[renderPipelineName];
  23820. if (!renderPipeline) {
  23821. return;
  23822. }
  23823. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  23824. };
  23825. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  23826. var renderPipeline = this._renderPipelines[renderPipelineName];
  23827. if (!renderPipeline) {
  23828. return;
  23829. }
  23830. renderPipeline._disableDisplayOnlyPass(cameras);
  23831. };
  23832. PostProcessRenderPipelineManager.prototype.update = function () {
  23833. for (var renderPipelineName in this._renderPipelines) {
  23834. this._renderPipelines[renderPipelineName]._update();
  23835. }
  23836. };
  23837. return PostProcessRenderPipelineManager;
  23838. })();
  23839. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  23840. })(BABYLON || (BABYLON = {}));
  23841. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  23842. var BABYLON;
  23843. (function (BABYLON) {
  23844. var DisplayPassPostProcess = (function (_super) {
  23845. __extends(DisplayPassPostProcess, _super);
  23846. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23847. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  23848. }
  23849. return DisplayPassPostProcess;
  23850. })(BABYLON.PostProcess);
  23851. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  23852. })(BABYLON || (BABYLON = {}));
  23853. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  23854. (function (BABYLON) {
  23855. var BoundingBoxRenderer = (function () {
  23856. function BoundingBoxRenderer(scene) {
  23857. this.frontColor = new BABYLON.Color3(1, 1, 1);
  23858. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  23859. this.showBackLines = true;
  23860. this.renderList = new BABYLON.SmartArray(32);
  23861. this._scene = scene;
  23862. }
  23863. BoundingBoxRenderer.prototype._prepareRessources = function () {
  23864. if (this._colorShader) {
  23865. return;
  23866. }
  23867. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  23868. attributes: ["position"],
  23869. uniforms: ["worldViewProjection", "color"]
  23870. });
  23871. var engine = this._scene.getEngine();
  23872. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  23873. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  23874. 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]);
  23875. };
  23876. BoundingBoxRenderer.prototype.reset = function () {
  23877. this.renderList.reset();
  23878. };
  23879. BoundingBoxRenderer.prototype.render = function () {
  23880. if (this.renderList.length === 0) {
  23881. return;
  23882. }
  23883. this._prepareRessources();
  23884. if (!this._colorShader.isReady()) {
  23885. return;
  23886. }
  23887. var engine = this._scene.getEngine();
  23888. engine.setDepthWrite(false);
  23889. this._colorShader._preBind();
  23890. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  23891. var boundingBox = this.renderList.data[boundingBoxIndex];
  23892. var min = boundingBox.minimum;
  23893. var max = boundingBox.maximum;
  23894. var diff = max.subtract(min);
  23895. var median = min.add(diff.scale(0.5));
  23896. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  23897. // VBOs
  23898. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  23899. if (this.showBackLines) {
  23900. // Back
  23901. engine.setDepthFunctionToGreaterOrEqual();
  23902. this._scene.resetCachedMaterial();
  23903. this._colorShader.setColor4("color", this.backColor.toColor4());
  23904. this._colorShader.bind(worldMatrix);
  23905. // Draw order
  23906. engine.draw(false, 0, 24);
  23907. }
  23908. // Front
  23909. engine.setDepthFunctionToLess();
  23910. this._scene.resetCachedMaterial();
  23911. this._colorShader.setColor4("color", this.frontColor.toColor4());
  23912. this._colorShader.bind(worldMatrix);
  23913. // Draw order
  23914. engine.draw(false, 0, 24);
  23915. }
  23916. this._colorShader.unbind();
  23917. engine.setDepthFunctionToLessOrEqual();
  23918. engine.setDepthWrite(true);
  23919. };
  23920. BoundingBoxRenderer.prototype.dispose = function () {
  23921. if (!this._colorShader) {
  23922. return;
  23923. }
  23924. this._colorShader.dispose();
  23925. this._vb.dispose();
  23926. this._scene.getEngine()._releaseBuffer(this._ib);
  23927. };
  23928. return BoundingBoxRenderer;
  23929. })();
  23930. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  23931. })(BABYLON || (BABYLON = {}));
  23932. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  23933. (function (BABYLON) {
  23934. var Internals;
  23935. (function (Internals) {
  23936. /*
  23937. * Based on jsTGALoader - Javascript loader for TGA file
  23938. * By Vincent Thibault
  23939. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  23940. */
  23941. var TGATools = (function () {
  23942. function TGATools() {
  23943. }
  23944. TGATools.GetTGAHeader = function (data) {
  23945. var offset = 0;
  23946. var header = {
  23947. id_length: data[offset++],
  23948. colormap_type: data[offset++],
  23949. image_type: data[offset++],
  23950. colormap_index: data[offset++] | data[offset++] << 8,
  23951. colormap_length: data[offset++] | data[offset++] << 8,
  23952. colormap_size: data[offset++],
  23953. origin: [
  23954. data[offset++] | data[offset++] << 8,
  23955. data[offset++] | data[offset++] << 8
  23956. ],
  23957. width: data[offset++] | data[offset++] << 8,
  23958. height: data[offset++] | data[offset++] << 8,
  23959. pixel_size: data[offset++],
  23960. flags: data[offset++]
  23961. };
  23962. return header;
  23963. };
  23964. TGATools.UploadContent = function (gl, data) {
  23965. // Not enough data to contain header ?
  23966. if (data.length < 19) {
  23967. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  23968. return;
  23969. }
  23970. // Read Header
  23971. var offset = 18;
  23972. var header = TGATools.GetTGAHeader(data);
  23973. // Assume it's a valid Targa file.
  23974. if (header.id_length + offset > data.length) {
  23975. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  23976. return;
  23977. }
  23978. // Skip not needed data
  23979. offset += header.id_length;
  23980. var use_rle = false;
  23981. var use_pal = false;
  23982. var use_rgb = false;
  23983. var use_grey = false;
  23984. switch (header.image_type) {
  23985. case TGATools._TYPE_RLE_INDEXED:
  23986. use_rle = true;
  23987. case TGATools._TYPE_INDEXED:
  23988. use_pal = true;
  23989. break;
  23990. case TGATools._TYPE_RLE_RGB:
  23991. use_rle = true;
  23992. case TGATools._TYPE_RGB:
  23993. use_rgb = true;
  23994. break;
  23995. case TGATools._TYPE_RLE_GREY:
  23996. use_rle = true;
  23997. case TGATools._TYPE_GREY:
  23998. use_grey = true;
  23999. break;
  24000. }
  24001. var pixel_data;
  24002. var numAlphaBits = header.flags & 0xf;
  24003. var pixel_size = header.pixel_size >> 3;
  24004. var pixel_total = header.width * header.height * pixel_size;
  24005. // Read palettes
  24006. var palettes;
  24007. if (use_pal) {
  24008. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  24009. }
  24010. // Read LRE
  24011. if (use_rle) {
  24012. pixel_data = new Uint8Array(pixel_total);
  24013. var c, count, i;
  24014. var localOffset = 0;
  24015. var pixels = new Uint8Array(pixel_size);
  24016. while (offset < pixel_total && localOffset < pixel_total) {
  24017. c = data[offset++];
  24018. count = (c & 0x7f) + 1;
  24019. // RLE pixels
  24020. if (c & 0x80) {
  24021. for (i = 0; i < pixel_size; ++i) {
  24022. pixels[i] = data[offset++];
  24023. }
  24024. for (i = 0; i < count; ++i) {
  24025. pixel_data.set(pixels, localOffset + i * pixel_size);
  24026. }
  24027. localOffset += pixel_size * count;
  24028. }
  24029. else {
  24030. count *= pixel_size;
  24031. for (i = 0; i < count; ++i) {
  24032. pixel_data[localOffset + i] = data[offset++];
  24033. }
  24034. localOffset += count;
  24035. }
  24036. }
  24037. }
  24038. else {
  24039. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  24040. }
  24041. // Load to texture
  24042. var x_start, y_start, x_step, y_step, y_end, x_end;
  24043. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  24044. default:
  24045. case TGATools._ORIGIN_UL:
  24046. x_start = 0;
  24047. x_step = 1;
  24048. x_end = header.width;
  24049. y_start = 0;
  24050. y_step = 1;
  24051. y_end = header.height;
  24052. break;
  24053. case TGATools._ORIGIN_BL:
  24054. x_start = 0;
  24055. x_step = 1;
  24056. x_end = header.width;
  24057. y_start = header.height - 1;
  24058. y_step = -1;
  24059. y_end = -1;
  24060. break;
  24061. case TGATools._ORIGIN_UR:
  24062. x_start = header.width - 1;
  24063. x_step = -1;
  24064. x_end = -1;
  24065. y_start = 0;
  24066. y_step = 1;
  24067. y_end = header.height;
  24068. break;
  24069. case TGATools._ORIGIN_BR:
  24070. x_start = header.width - 1;
  24071. x_step = -1;
  24072. x_end = -1;
  24073. y_start = header.height - 1;
  24074. y_step = -1;
  24075. y_end = -1;
  24076. break;
  24077. }
  24078. // Load the specify method
  24079. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  24080. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  24081. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  24082. };
  24083. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24084. var image = pixel_data, colormap = palettes;
  24085. var width = header.width, height = header.height;
  24086. var color, i = 0, x, y;
  24087. var imageData = new Uint8Array(width * height * 4);
  24088. for (y = y_start; y !== y_end; y += y_step) {
  24089. for (x = x_start; x !== x_end; x += x_step, i++) {
  24090. color = image[i];
  24091. imageData[(x + width * y) * 4 + 3] = 255;
  24092. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  24093. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  24094. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  24095. }
  24096. }
  24097. return imageData;
  24098. };
  24099. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24100. var image = pixel_data;
  24101. var width = header.width, height = header.height;
  24102. var color, i = 0, x, y;
  24103. var imageData = new Uint8Array(width * height * 4);
  24104. for (y = y_start; y !== y_end; y += y_step) {
  24105. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  24106. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  24107. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  24108. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  24109. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  24110. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  24111. }
  24112. }
  24113. return imageData;
  24114. };
  24115. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24116. var image = pixel_data;
  24117. var width = header.width, height = header.height;
  24118. var i = 0, x, y;
  24119. var imageData = new Uint8Array(width * height * 4);
  24120. for (y = y_start; y !== y_end; y += y_step) {
  24121. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  24122. imageData[(x + width * y) * 4 + 3] = 255;
  24123. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  24124. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  24125. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  24126. }
  24127. }
  24128. return imageData;
  24129. };
  24130. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24131. var image = pixel_data;
  24132. var width = header.width, height = header.height;
  24133. var i = 0, x, y;
  24134. var imageData = new Uint8Array(width * height * 4);
  24135. for (y = y_start; y !== y_end; y += y_step) {
  24136. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  24137. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  24138. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  24139. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  24140. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  24141. }
  24142. }
  24143. return imageData;
  24144. };
  24145. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24146. var image = pixel_data;
  24147. var width = header.width, height = header.height;
  24148. var color, i = 0, x, y;
  24149. var imageData = new Uint8Array(width * height * 4);
  24150. for (y = y_start; y !== y_end; y += y_step) {
  24151. for (x = x_start; x !== x_end; x += x_step, i++) {
  24152. color = image[i];
  24153. imageData[(x + width * y) * 4 + 0] = color;
  24154. imageData[(x + width * y) * 4 + 1] = color;
  24155. imageData[(x + width * y) * 4 + 2] = color;
  24156. imageData[(x + width * y) * 4 + 3] = 255;
  24157. }
  24158. }
  24159. return imageData;
  24160. };
  24161. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24162. var image = pixel_data;
  24163. var width = header.width, height = header.height;
  24164. var i = 0, x, y;
  24165. var imageData = new Uint8Array(width * height * 4);
  24166. for (y = y_start; y !== y_end; y += y_step) {
  24167. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  24168. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  24169. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  24170. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  24171. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  24172. }
  24173. }
  24174. return imageData;
  24175. };
  24176. TGATools._TYPE_NO_DATA = 0;
  24177. TGATools._TYPE_INDEXED = 1;
  24178. TGATools._TYPE_RGB = 2;
  24179. TGATools._TYPE_GREY = 3;
  24180. TGATools._TYPE_RLE_INDEXED = 9;
  24181. TGATools._TYPE_RLE_RGB = 10;
  24182. TGATools._TYPE_RLE_GREY = 11;
  24183. TGATools._ORIGIN_MASK = 0x30;
  24184. TGATools._ORIGIN_SHIFT = 0x04;
  24185. TGATools._ORIGIN_BL = 0x00;
  24186. TGATools._ORIGIN_BR = 0x01;
  24187. TGATools._ORIGIN_UL = 0x02;
  24188. TGATools._ORIGIN_UR = 0x03;
  24189. return TGATools;
  24190. })();
  24191. Internals.TGATools = TGATools;
  24192. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24193. })(BABYLON || (BABYLON = {}));
  24194. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  24195. (function (BABYLON) {
  24196. var Internals;
  24197. (function (Internals) {
  24198. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  24199. // All values and structures referenced from:
  24200. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  24201. var DDS_MAGIC = 0x20534444;
  24202. 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;
  24203. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  24204. 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;
  24205. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  24206. function FourCCToInt32(value) {
  24207. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  24208. }
  24209. function Int32ToFourCC(value) {
  24210. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  24211. }
  24212. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  24213. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  24214. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  24215. var headerLengthInt = 31; // The header length in 32 bit ints
  24216. // Offsets into the header array
  24217. var off_magic = 0;
  24218. var off_size = 1;
  24219. var off_flags = 2;
  24220. var off_height = 3;
  24221. var off_width = 4;
  24222. var off_mipmapCount = 7;
  24223. var off_pfFlags = 20;
  24224. var off_pfFourCC = 21;
  24225. var off_RGBbpp = 22;
  24226. var off_RMask = 23;
  24227. var off_GMask = 24;
  24228. var off_BMask = 25;
  24229. var off_AMask = 26;
  24230. var off_caps1 = 27;
  24231. var off_caps2 = 28;
  24232. ;
  24233. var DDSTools = (function () {
  24234. function DDSTools() {
  24235. }
  24236. DDSTools.GetDDSInfo = function (arrayBuffer) {
  24237. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  24238. var mipmapCount = 1;
  24239. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  24240. mipmapCount = Math.max(1, header[off_mipmapCount]);
  24241. }
  24242. return {
  24243. width: header[off_width],
  24244. height: header[off_height],
  24245. mipmapCount: mipmapCount,
  24246. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  24247. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  24248. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  24249. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  24250. };
  24251. };
  24252. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  24253. var byteArray = new Uint8Array(dataLength);
  24254. var srcData = new Uint8Array(arrayBuffer);
  24255. var index = 0;
  24256. for (var y = height - 1; y >= 0; y--) {
  24257. for (var x = 0; x < width; x++) {
  24258. var srcPos = dataOffset + (x + y * width) * 4;
  24259. byteArray[index + 2] = srcData[srcPos];
  24260. byteArray[index + 1] = srcData[srcPos + 1];
  24261. byteArray[index] = srcData[srcPos + 2];
  24262. byteArray[index + 3] = srcData[srcPos + 3];
  24263. index += 4;
  24264. }
  24265. }
  24266. return byteArray;
  24267. };
  24268. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  24269. var byteArray = new Uint8Array(dataLength);
  24270. var srcData = new Uint8Array(arrayBuffer);
  24271. var index = 0;
  24272. for (var y = height - 1; y >= 0; y--) {
  24273. for (var x = 0; x < width; x++) {
  24274. var srcPos = dataOffset + (x + y * width) * 3;
  24275. byteArray[index + 2] = srcData[srcPos];
  24276. byteArray[index + 1] = srcData[srcPos + 1];
  24277. byteArray[index] = srcData[srcPos + 2];
  24278. index += 3;
  24279. }
  24280. }
  24281. return byteArray;
  24282. };
  24283. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  24284. var byteArray = new Uint8Array(dataLength);
  24285. var srcData = new Uint8Array(arrayBuffer);
  24286. var index = 0;
  24287. for (var y = height - 1; y >= 0; y--) {
  24288. for (var x = 0; x < width; x++) {
  24289. var srcPos = dataOffset + (x + y * width);
  24290. byteArray[index] = srcData[srcPos];
  24291. index++;
  24292. }
  24293. }
  24294. return byteArray;
  24295. };
  24296. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  24297. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  24298. if (header[off_magic] != DDS_MAGIC) {
  24299. BABYLON.Tools.Error("Invalid magic number in DDS header");
  24300. return;
  24301. }
  24302. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  24303. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  24304. return;
  24305. }
  24306. if (info.isFourCC) {
  24307. fourCC = header[off_pfFourCC];
  24308. switch (fourCC) {
  24309. case FOURCC_DXT1:
  24310. blockBytes = 8;
  24311. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  24312. break;
  24313. case FOURCC_DXT3:
  24314. blockBytes = 16;
  24315. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  24316. break;
  24317. case FOURCC_DXT5:
  24318. blockBytes = 16;
  24319. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  24320. break;
  24321. default:
  24322. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  24323. return;
  24324. }
  24325. }
  24326. mipmapCount = 1;
  24327. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  24328. mipmapCount = Math.max(1, header[off_mipmapCount]);
  24329. }
  24330. var bpp = header[off_RGBbpp];
  24331. for (var face = 0; face < faces; face++) {
  24332. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  24333. width = header[off_width];
  24334. height = header[off_height];
  24335. dataOffset = header[off_size] + 4;
  24336. for (i = 0; i < mipmapCount; ++i) {
  24337. if (info.isRGB) {
  24338. if (bpp == 24) {
  24339. dataLength = width * height * 3;
  24340. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  24341. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  24342. }
  24343. else {
  24344. dataLength = width * height * 4;
  24345. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  24346. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  24347. }
  24348. }
  24349. else if (info.isLuminance) {
  24350. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  24351. var unpaddedRowSize = width;
  24352. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  24353. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  24354. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  24355. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  24356. }
  24357. else {
  24358. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  24359. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  24360. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  24361. }
  24362. dataOffset += dataLength;
  24363. width *= 0.5;
  24364. height *= 0.5;
  24365. width = Math.max(1.0, width);
  24366. height = Math.max(1.0, height);
  24367. }
  24368. }
  24369. };
  24370. return DDSTools;
  24371. })();
  24372. Internals.DDSTools = DDSTools;
  24373. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24374. })(BABYLON || (BABYLON = {}));
  24375. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  24376. (function (BABYLON) {
  24377. var SmartArray = (function () {
  24378. function SmartArray(capacity) {
  24379. this.length = 0;
  24380. this._duplicateId = 0;
  24381. this.data = new Array(capacity);
  24382. this._id = SmartArray._GlobalId++;
  24383. }
  24384. SmartArray.prototype.push = function (value) {
  24385. this.data[this.length++] = value;
  24386. if (this.length > this.data.length) {
  24387. this.data.length *= 2;
  24388. }
  24389. if (!value.__smartArrayFlags) {
  24390. value.__smartArrayFlags = {};
  24391. }
  24392. value.__smartArrayFlags[this._id] = this._duplicateId;
  24393. };
  24394. SmartArray.prototype.pushNoDuplicate = function (value) {
  24395. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  24396. return;
  24397. }
  24398. this.push(value);
  24399. };
  24400. SmartArray.prototype.sort = function (compareFn) {
  24401. this.data.sort(compareFn);
  24402. };
  24403. SmartArray.prototype.reset = function () {
  24404. this.length = 0;
  24405. this._duplicateId++;
  24406. };
  24407. SmartArray.prototype.concat = function (array) {
  24408. if (array.length === 0) {
  24409. return;
  24410. }
  24411. if (this.length + array.length > this.data.length) {
  24412. this.data.length = (this.length + array.length) * 2;
  24413. }
  24414. for (var index = 0; index < array.length; index++) {
  24415. this.data[this.length++] = (array.data || array)[index];
  24416. }
  24417. };
  24418. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  24419. if (array.length === 0) {
  24420. return;
  24421. }
  24422. if (this.length + array.length > this.data.length) {
  24423. this.data.length = (this.length + array.length) * 2;
  24424. }
  24425. for (var index = 0; index < array.length; index++) {
  24426. var item = (array.data || array)[index];
  24427. this.pushNoDuplicate(item);
  24428. }
  24429. };
  24430. SmartArray.prototype.indexOf = function (value) {
  24431. var position = this.data.indexOf(value);
  24432. if (position >= this.length) {
  24433. return -1;
  24434. }
  24435. return position;
  24436. };
  24437. // Statics
  24438. SmartArray._GlobalId = 0;
  24439. return SmartArray;
  24440. })();
  24441. BABYLON.SmartArray = SmartArray;
  24442. })(BABYLON || (BABYLON = {}));
  24443. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  24444. (function (BABYLON) {
  24445. var CannonJSPlugin = (function () {
  24446. function CannonJSPlugin() {
  24447. this._registeredMeshes = [];
  24448. this._physicsMaterials = [];
  24449. this.updateBodyPosition = function (mesh) {
  24450. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24451. var registeredMesh = this._registeredMeshes[index];
  24452. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  24453. var body = registeredMesh.body;
  24454. var center = mesh.getBoundingInfo().boundingBox.center;
  24455. body.position.set(center.x, center.z, center.y);
  24456. body.quaternion.x = mesh.rotationQuaternion.x;
  24457. body.quaternion.z = mesh.rotationQuaternion.y;
  24458. body.quaternion.y = mesh.rotationQuaternion.z;
  24459. body.quaternion.w = -mesh.rotationQuaternion.w;
  24460. return;
  24461. }
  24462. }
  24463. };
  24464. }
  24465. CannonJSPlugin.prototype.initialize = function (iterations) {
  24466. if (iterations === void 0) { iterations = 10; }
  24467. this._world = new CANNON.World();
  24468. this._world.broadphase = new CANNON.NaiveBroadphase();
  24469. this._world.solver.iterations = iterations;
  24470. };
  24471. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  24472. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  24473. };
  24474. CannonJSPlugin.prototype.runOneStep = function (delta) {
  24475. this._world.step(delta);
  24476. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24477. var registeredMesh = this._registeredMeshes[index];
  24478. if (registeredMesh.isChild) {
  24479. continue;
  24480. }
  24481. // Body position
  24482. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  24483. var deltaPos = registeredMesh.delta;
  24484. if (deltaPos) {
  24485. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  24486. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  24487. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  24488. }
  24489. else {
  24490. registeredMesh.mesh.position.x = bodyX;
  24491. registeredMesh.mesh.position.y = bodyZ;
  24492. registeredMesh.mesh.position.z = bodyY;
  24493. }
  24494. if (!registeredMesh.mesh.rotationQuaternion) {
  24495. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24496. }
  24497. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  24498. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  24499. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  24500. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  24501. }
  24502. };
  24503. CannonJSPlugin.prototype.setGravity = function (gravity) {
  24504. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  24505. };
  24506. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  24507. this.unregisterMesh(mesh);
  24508. mesh.computeWorldMatrix(true);
  24509. switch (impostor) {
  24510. case BABYLON.PhysicsEngine.SphereImpostor:
  24511. var bbox = mesh.getBoundingInfo().boundingBox;
  24512. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  24513. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  24514. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  24515. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  24516. case BABYLON.PhysicsEngine.BoxImpostor:
  24517. bbox = mesh.getBoundingInfo().boundingBox;
  24518. var min = bbox.minimumWorld;
  24519. var max = bbox.maximumWorld;
  24520. var box = max.subtract(min).scale(0.5);
  24521. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  24522. case BABYLON.PhysicsEngine.PlaneImpostor:
  24523. return this._createPlane(mesh, options);
  24524. case BABYLON.PhysicsEngine.MeshImpostor:
  24525. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24526. var rawFaces = mesh.getIndices();
  24527. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  24528. }
  24529. return null;
  24530. };
  24531. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  24532. var shape = new CANNON.Sphere(radius);
  24533. if (!options) {
  24534. return shape;
  24535. }
  24536. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24537. };
  24538. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  24539. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  24540. if (!options) {
  24541. return shape;
  24542. }
  24543. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24544. };
  24545. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  24546. var shape = new CANNON.Plane();
  24547. if (!options) {
  24548. return shape;
  24549. }
  24550. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24551. };
  24552. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  24553. var verts = [], faces = [];
  24554. mesh.computeWorldMatrix(true);
  24555. for (var i = 0; i < rawVerts.length; i += 3) {
  24556. var transformed = BABYLON.Vector3.Zero();
  24557. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  24558. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  24559. }
  24560. for (var j = 0; j < rawFaces.length; j += 3) {
  24561. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  24562. }
  24563. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  24564. if (!options) {
  24565. return shape;
  24566. }
  24567. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24568. };
  24569. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  24570. var index;
  24571. var mat;
  24572. for (index = 0; index < this._physicsMaterials.length; index++) {
  24573. mat = this._physicsMaterials[index];
  24574. if (mat.friction === friction && mat.restitution === restitution) {
  24575. return mat;
  24576. }
  24577. }
  24578. var currentMat = new CANNON.Material();
  24579. currentMat.friction = friction;
  24580. currentMat.restitution = restitution;
  24581. this._physicsMaterials.push(currentMat);
  24582. for (index = 0; index < this._physicsMaterials.length; index++) {
  24583. mat = this._physicsMaterials[index];
  24584. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  24585. contactMaterial.contactEquationStiffness = 1e10;
  24586. contactMaterial.contactEquationRegularizationTime = 10;
  24587. this._world.addContactMaterial(contactMaterial);
  24588. }
  24589. return currentMat;
  24590. };
  24591. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  24592. var initialRotation = null;
  24593. if (mesh.rotationQuaternion) {
  24594. initialRotation = mesh.rotationQuaternion.clone();
  24595. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24596. }
  24597. // The delta between the mesh position and the mesh bounding box center
  24598. var bbox = mesh.getBoundingInfo().boundingBox;
  24599. var deltaPosition = mesh.position.subtract(bbox.center);
  24600. var material = this._addMaterial(friction, restitution);
  24601. var body = new CANNON.RigidBody(mass, shape, material);
  24602. if (initialRotation) {
  24603. body.quaternion.x = initialRotation.x;
  24604. body.quaternion.z = initialRotation.y;
  24605. body.quaternion.y = initialRotation.z;
  24606. body.quaternion.w = -initialRotation.w;
  24607. }
  24608. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  24609. this._world.add(body);
  24610. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  24611. return body;
  24612. };
  24613. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  24614. var compoundShape = new CANNON.Compound();
  24615. for (var index = 0; index < parts.length; index++) {
  24616. var mesh = parts[index].mesh;
  24617. var shape = this.registerMesh(mesh, parts[index].impostor);
  24618. if (index == 0) {
  24619. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  24620. }
  24621. else {
  24622. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  24623. }
  24624. }
  24625. var initialMesh = parts[0].mesh;
  24626. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  24627. body.parts = parts;
  24628. return body;
  24629. };
  24630. CannonJSPlugin.prototype._unbindBody = function (body) {
  24631. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24632. var registeredMesh = this._registeredMeshes[index];
  24633. if (registeredMesh.body === body) {
  24634. registeredMesh.body = null;
  24635. registeredMesh.delta = 0;
  24636. }
  24637. }
  24638. };
  24639. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  24640. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24641. var registeredMesh = this._registeredMeshes[index];
  24642. if (registeredMesh.mesh === mesh) {
  24643. // Remove body
  24644. if (registeredMesh.body) {
  24645. this._world.remove(registeredMesh.body);
  24646. this._unbindBody(registeredMesh.body);
  24647. }
  24648. this._registeredMeshes.splice(index, 1);
  24649. return;
  24650. }
  24651. }
  24652. };
  24653. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  24654. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  24655. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  24656. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24657. var registeredMesh = this._registeredMeshes[index];
  24658. if (registeredMesh.mesh === mesh) {
  24659. registeredMesh.body.applyImpulse(impulse, worldPoint);
  24660. return;
  24661. }
  24662. }
  24663. };
  24664. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  24665. var body1 = null, body2 = null;
  24666. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24667. var registeredMesh = this._registeredMeshes[index];
  24668. if (registeredMesh.mesh === mesh1) {
  24669. body1 = registeredMesh.body;
  24670. }
  24671. else if (registeredMesh.mesh === mesh2) {
  24672. body2 = registeredMesh.body;
  24673. }
  24674. }
  24675. if (!body1 || !body2) {
  24676. return false;
  24677. }
  24678. 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));
  24679. this._world.addConstraint(constraint);
  24680. return true;
  24681. };
  24682. CannonJSPlugin.prototype.dispose = function () {
  24683. while (this._registeredMeshes.length) {
  24684. this.unregisterMesh(this._registeredMeshes[0].mesh);
  24685. }
  24686. };
  24687. CannonJSPlugin.prototype.isSupported = function () {
  24688. return window.CANNON !== undefined;
  24689. };
  24690. return CannonJSPlugin;
  24691. })();
  24692. BABYLON.CannonJSPlugin = CannonJSPlugin;
  24693. })(BABYLON || (BABYLON = {}));
  24694. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  24695. var BABYLON;
  24696. (function (BABYLON) {
  24697. var Condition = (function () {
  24698. function Condition(actionManager) {
  24699. this._actionManager = actionManager;
  24700. }
  24701. Condition.prototype.isValid = function () {
  24702. return true;
  24703. };
  24704. Condition.prototype._getProperty = function (propertyPath) {
  24705. return this._actionManager._getProperty(propertyPath);
  24706. };
  24707. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  24708. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24709. };
  24710. return Condition;
  24711. })();
  24712. BABYLON.Condition = Condition;
  24713. var ValueCondition = (function (_super) {
  24714. __extends(ValueCondition, _super);
  24715. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  24716. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  24717. _super.call(this, actionManager);
  24718. this.propertyPath = propertyPath;
  24719. this.value = value;
  24720. this.operator = operator;
  24721. this._target = this._getEffectiveTarget(target, this.propertyPath);
  24722. this._property = this._getProperty(this.propertyPath);
  24723. }
  24724. Object.defineProperty(ValueCondition, "IsEqual", {
  24725. get: function () {
  24726. return ValueCondition._IsEqual;
  24727. },
  24728. enumerable: true,
  24729. configurable: true
  24730. });
  24731. Object.defineProperty(ValueCondition, "IsDifferent", {
  24732. get: function () {
  24733. return ValueCondition._IsDifferent;
  24734. },
  24735. enumerable: true,
  24736. configurable: true
  24737. });
  24738. Object.defineProperty(ValueCondition, "IsGreater", {
  24739. get: function () {
  24740. return ValueCondition._IsGreater;
  24741. },
  24742. enumerable: true,
  24743. configurable: true
  24744. });
  24745. Object.defineProperty(ValueCondition, "IsLesser", {
  24746. get: function () {
  24747. return ValueCondition._IsLesser;
  24748. },
  24749. enumerable: true,
  24750. configurable: true
  24751. });
  24752. // Methods
  24753. ValueCondition.prototype.isValid = function () {
  24754. switch (this.operator) {
  24755. case ValueCondition.IsGreater:
  24756. return this._target[this._property] > this.value;
  24757. case ValueCondition.IsLesser:
  24758. return this._target[this._property] < this.value;
  24759. case ValueCondition.IsEqual:
  24760. case ValueCondition.IsDifferent:
  24761. var check;
  24762. if (this.value.equals) {
  24763. check = this.value.equals(this._target[this._property]);
  24764. }
  24765. else {
  24766. check = this.value === this._target[this._property];
  24767. }
  24768. return this.operator === ValueCondition.IsEqual ? check : !check;
  24769. }
  24770. return false;
  24771. };
  24772. // Statics
  24773. ValueCondition._IsEqual = 0;
  24774. ValueCondition._IsDifferent = 1;
  24775. ValueCondition._IsGreater = 2;
  24776. ValueCondition._IsLesser = 3;
  24777. return ValueCondition;
  24778. })(Condition);
  24779. BABYLON.ValueCondition = ValueCondition;
  24780. var PredicateCondition = (function (_super) {
  24781. __extends(PredicateCondition, _super);
  24782. function PredicateCondition(actionManager, predicate) {
  24783. _super.call(this, actionManager);
  24784. this.predicate = predicate;
  24785. }
  24786. PredicateCondition.prototype.isValid = function () {
  24787. return this.predicate();
  24788. };
  24789. return PredicateCondition;
  24790. })(Condition);
  24791. BABYLON.PredicateCondition = PredicateCondition;
  24792. var StateCondition = (function (_super) {
  24793. __extends(StateCondition, _super);
  24794. function StateCondition(actionManager, target, value) {
  24795. _super.call(this, actionManager);
  24796. this.value = value;
  24797. this._target = target;
  24798. }
  24799. // Methods
  24800. StateCondition.prototype.isValid = function () {
  24801. return this._target.state === this.value;
  24802. };
  24803. return StateCondition;
  24804. })(Condition);
  24805. BABYLON.StateCondition = StateCondition;
  24806. })(BABYLON || (BABYLON = {}));
  24807. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  24808. (function (BABYLON) {
  24809. var Action = (function () {
  24810. function Action(triggerOptions, condition) {
  24811. this.triggerOptions = triggerOptions;
  24812. if (triggerOptions.parameter) {
  24813. this.trigger = triggerOptions.trigger;
  24814. this._triggerParameter = triggerOptions.parameter;
  24815. }
  24816. else {
  24817. this.trigger = triggerOptions;
  24818. }
  24819. this._nextActiveAction = this;
  24820. this._condition = condition;
  24821. }
  24822. // Methods
  24823. Action.prototype._prepare = function () {
  24824. };
  24825. Action.prototype.getTriggerParameter = function () {
  24826. return this._triggerParameter;
  24827. };
  24828. Action.prototype._executeCurrent = function (evt) {
  24829. if (this._nextActiveAction._condition) {
  24830. var condition = this._nextActiveAction._condition;
  24831. var currentRenderId = this._actionManager.getScene().getRenderId();
  24832. // We cache the current evaluation for the current frame
  24833. if (condition._evaluationId === currentRenderId) {
  24834. if (!condition._currentResult) {
  24835. return;
  24836. }
  24837. }
  24838. else {
  24839. condition._evaluationId = currentRenderId;
  24840. if (!condition.isValid()) {
  24841. condition._currentResult = false;
  24842. return;
  24843. }
  24844. condition._currentResult = true;
  24845. }
  24846. }
  24847. this._nextActiveAction.execute(evt);
  24848. if (this._nextActiveAction._child) {
  24849. if (!this._nextActiveAction._child._actionManager) {
  24850. this._nextActiveAction._child._actionManager = this._actionManager;
  24851. }
  24852. this._nextActiveAction = this._nextActiveAction._child;
  24853. }
  24854. else {
  24855. this._nextActiveAction = this;
  24856. }
  24857. };
  24858. Action.prototype.execute = function (evt) {
  24859. };
  24860. Action.prototype.then = function (action) {
  24861. this._child = action;
  24862. action._actionManager = this._actionManager;
  24863. action._prepare();
  24864. return action;
  24865. };
  24866. Action.prototype._getProperty = function (propertyPath) {
  24867. return this._actionManager._getProperty(propertyPath);
  24868. };
  24869. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  24870. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24871. };
  24872. return Action;
  24873. })();
  24874. BABYLON.Action = Action;
  24875. })(BABYLON || (BABYLON = {}));
  24876. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  24877. (function (BABYLON) {
  24878. /**
  24879. * ActionEvent is the event beint sent when an action is triggered.
  24880. */
  24881. var ActionEvent = (function () {
  24882. /**
  24883. * @constructor
  24884. * @param source The mesh that triggered the action.
  24885. * @param pointerX the X mouse cursor position at the time of the event
  24886. * @param pointerY the Y mouse cursor position at the time of the event
  24887. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  24888. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  24889. */
  24890. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  24891. this.source = source;
  24892. this.pointerX = pointerX;
  24893. this.pointerY = pointerY;
  24894. this.meshUnderPointer = meshUnderPointer;
  24895. this.sourceEvent = sourceEvent;
  24896. }
  24897. /**
  24898. * Helper function to auto-create an ActionEvent from a source mesh.
  24899. * @param source the source mesh that triggered the event
  24900. * @param evt {Event} The original (browser) event
  24901. */
  24902. ActionEvent.CreateNew = function (source, evt) {
  24903. var scene = source.getScene();
  24904. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24905. };
  24906. /**
  24907. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  24908. * @param scene the scene where the event occurred
  24909. * @param evt {Event} The original (browser) event
  24910. */
  24911. ActionEvent.CreateNewFromScene = function (scene, evt) {
  24912. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24913. };
  24914. return ActionEvent;
  24915. })();
  24916. BABYLON.ActionEvent = ActionEvent;
  24917. /**
  24918. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  24919. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  24920. */
  24921. var ActionManager = (function () {
  24922. function ActionManager(scene) {
  24923. // Members
  24924. this.actions = new Array();
  24925. this._scene = scene;
  24926. scene._actionManagers.push(this);
  24927. }
  24928. Object.defineProperty(ActionManager, "NothingTrigger", {
  24929. get: function () {
  24930. return ActionManager._NothingTrigger;
  24931. },
  24932. enumerable: true,
  24933. configurable: true
  24934. });
  24935. Object.defineProperty(ActionManager, "OnPickTrigger", {
  24936. get: function () {
  24937. return ActionManager._OnPickTrigger;
  24938. },
  24939. enumerable: true,
  24940. configurable: true
  24941. });
  24942. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  24943. get: function () {
  24944. return ActionManager._OnLeftPickTrigger;
  24945. },
  24946. enumerable: true,
  24947. configurable: true
  24948. });
  24949. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  24950. get: function () {
  24951. return ActionManager._OnRightPickTrigger;
  24952. },
  24953. enumerable: true,
  24954. configurable: true
  24955. });
  24956. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  24957. get: function () {
  24958. return ActionManager._OnCenterPickTrigger;
  24959. },
  24960. enumerable: true,
  24961. configurable: true
  24962. });
  24963. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  24964. get: function () {
  24965. return ActionManager._OnPointerOverTrigger;
  24966. },
  24967. enumerable: true,
  24968. configurable: true
  24969. });
  24970. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  24971. get: function () {
  24972. return ActionManager._OnPointerOutTrigger;
  24973. },
  24974. enumerable: true,
  24975. configurable: true
  24976. });
  24977. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  24978. get: function () {
  24979. return ActionManager._OnEveryFrameTrigger;
  24980. },
  24981. enumerable: true,
  24982. configurable: true
  24983. });
  24984. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  24985. get: function () {
  24986. return ActionManager._OnIntersectionEnterTrigger;
  24987. },
  24988. enumerable: true,
  24989. configurable: true
  24990. });
  24991. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  24992. get: function () {
  24993. return ActionManager._OnIntersectionExitTrigger;
  24994. },
  24995. enumerable: true,
  24996. configurable: true
  24997. });
  24998. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  24999. get: function () {
  25000. return ActionManager._OnKeyDownTrigger;
  25001. },
  25002. enumerable: true,
  25003. configurable: true
  25004. });
  25005. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  25006. get: function () {
  25007. return ActionManager._OnKeyUpTrigger;
  25008. },
  25009. enumerable: true,
  25010. configurable: true
  25011. });
  25012. // Methods
  25013. ActionManager.prototype.dispose = function () {
  25014. var index = this._scene._actionManagers.indexOf(this);
  25015. if (index > -1) {
  25016. this._scene._actionManagers.splice(index, 1);
  25017. }
  25018. };
  25019. ActionManager.prototype.getScene = function () {
  25020. return this._scene;
  25021. };
  25022. /**
  25023. * Does this action manager handles actions of any of the given triggers
  25024. * @param {number[]} triggers - the triggers to be tested
  25025. * @return {boolean} whether one (or more) of the triggers is handeled
  25026. */
  25027. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  25028. for (var index = 0; index < this.actions.length; index++) {
  25029. var action = this.actions[index];
  25030. if (triggers.indexOf(action.trigger) > -1) {
  25031. return true;
  25032. }
  25033. }
  25034. return false;
  25035. };
  25036. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  25037. /**
  25038. * Does this action manager has pointer triggers
  25039. * @return {boolean} whether or not it has pointer triggers
  25040. */
  25041. get: function () {
  25042. for (var index = 0; index < this.actions.length; index++) {
  25043. var action = this.actions[index];
  25044. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  25045. return true;
  25046. }
  25047. }
  25048. return false;
  25049. },
  25050. enumerable: true,
  25051. configurable: true
  25052. });
  25053. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  25054. /**
  25055. * Does this action manager has pick triggers
  25056. * @return {boolean} whether or not it has pick triggers
  25057. */
  25058. get: function () {
  25059. for (var index = 0; index < this.actions.length; index++) {
  25060. var action = this.actions[index];
  25061. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  25062. return true;
  25063. }
  25064. }
  25065. return false;
  25066. },
  25067. enumerable: true,
  25068. configurable: true
  25069. });
  25070. /**
  25071. * Registers an action to this action manager
  25072. * @param {BABYLON.Action} action - the action to be registered
  25073. * @return {BABYLON.Action} the action amended (prepared) after registration
  25074. */
  25075. ActionManager.prototype.registerAction = function (action) {
  25076. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  25077. if (this.getScene().actionManager !== this) {
  25078. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  25079. return null;
  25080. }
  25081. }
  25082. this.actions.push(action);
  25083. action._actionManager = this;
  25084. action._prepare();
  25085. return action;
  25086. };
  25087. /**
  25088. * Process a specific trigger
  25089. * @param {number} trigger - the trigger to process
  25090. * @param evt {BABYLON.ActionEvent} the event details to be processed
  25091. */
  25092. ActionManager.prototype.processTrigger = function (trigger, evt) {
  25093. for (var index = 0; index < this.actions.length; index++) {
  25094. var action = this.actions[index];
  25095. if (action.trigger === trigger) {
  25096. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  25097. var parameter = action.getTriggerParameter();
  25098. if (parameter) {
  25099. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  25100. var actualkey = String.fromCharCode(unicode).toLowerCase();
  25101. if (actualkey !== parameter.toLowerCase()) {
  25102. continue;
  25103. }
  25104. }
  25105. }
  25106. action._executeCurrent(evt);
  25107. }
  25108. }
  25109. };
  25110. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  25111. var properties = propertyPath.split(".");
  25112. for (var index = 0; index < properties.length - 1; index++) {
  25113. target = target[properties[index]];
  25114. }
  25115. return target;
  25116. };
  25117. ActionManager.prototype._getProperty = function (propertyPath) {
  25118. var properties = propertyPath.split(".");
  25119. return properties[properties.length - 1];
  25120. };
  25121. // Statics
  25122. ActionManager._NothingTrigger = 0;
  25123. ActionManager._OnPickTrigger = 1;
  25124. ActionManager._OnLeftPickTrigger = 2;
  25125. ActionManager._OnRightPickTrigger = 3;
  25126. ActionManager._OnCenterPickTrigger = 4;
  25127. ActionManager._OnPointerOverTrigger = 5;
  25128. ActionManager._OnPointerOutTrigger = 6;
  25129. ActionManager._OnEveryFrameTrigger = 7;
  25130. ActionManager._OnIntersectionEnterTrigger = 8;
  25131. ActionManager._OnIntersectionExitTrigger = 9;
  25132. ActionManager._OnKeyDownTrigger = 10;
  25133. ActionManager._OnKeyUpTrigger = 11;
  25134. return ActionManager;
  25135. })();
  25136. BABYLON.ActionManager = ActionManager;
  25137. })(BABYLON || (BABYLON = {}));
  25138. //# sourceMappingURL=babylon.actionManager.js.map
  25139. var BABYLON;
  25140. (function (BABYLON) {
  25141. var InterpolateValueAction = (function (_super) {
  25142. __extends(InterpolateValueAction, _super);
  25143. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  25144. if (duration === void 0) { duration = 1000; }
  25145. _super.call(this, triggerOptions, condition);
  25146. this.propertyPath = propertyPath;
  25147. this.value = value;
  25148. this.duration = duration;
  25149. this.stopOtherAnimations = stopOtherAnimations;
  25150. this._target = target;
  25151. }
  25152. InterpolateValueAction.prototype._prepare = function () {
  25153. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25154. this._property = this._getProperty(this.propertyPath);
  25155. };
  25156. InterpolateValueAction.prototype.execute = function () {
  25157. var scene = this._actionManager.getScene();
  25158. var keys = [
  25159. {
  25160. frame: 0,
  25161. value: this._target[this._property]
  25162. },
  25163. {
  25164. frame: 100,
  25165. value: this.value
  25166. }
  25167. ];
  25168. var dataType;
  25169. if (typeof this.value === "number") {
  25170. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  25171. }
  25172. else if (this.value instanceof BABYLON.Color3) {
  25173. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  25174. }
  25175. else if (this.value instanceof BABYLON.Vector3) {
  25176. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  25177. }
  25178. else if (this.value instanceof BABYLON.Matrix) {
  25179. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  25180. }
  25181. else if (this.value instanceof BABYLON.Quaternion) {
  25182. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  25183. }
  25184. else {
  25185. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  25186. return;
  25187. }
  25188. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  25189. animation.setKeys(keys);
  25190. if (this.stopOtherAnimations) {
  25191. scene.stopAnimation(this._target);
  25192. }
  25193. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  25194. };
  25195. return InterpolateValueAction;
  25196. })(BABYLON.Action);
  25197. BABYLON.InterpolateValueAction = InterpolateValueAction;
  25198. })(BABYLON || (BABYLON = {}));
  25199. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  25200. var BABYLON;
  25201. (function (BABYLON) {
  25202. var SwitchBooleanAction = (function (_super) {
  25203. __extends(SwitchBooleanAction, _super);
  25204. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  25205. _super.call(this, triggerOptions, condition);
  25206. this.propertyPath = propertyPath;
  25207. this._target = target;
  25208. }
  25209. SwitchBooleanAction.prototype._prepare = function () {
  25210. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25211. this._property = this._getProperty(this.propertyPath);
  25212. };
  25213. SwitchBooleanAction.prototype.execute = function () {
  25214. this._target[this._property] = !this._target[this._property];
  25215. };
  25216. return SwitchBooleanAction;
  25217. })(BABYLON.Action);
  25218. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  25219. var SetStateAction = (function (_super) {
  25220. __extends(SetStateAction, _super);
  25221. function SetStateAction(triggerOptions, target, value, condition) {
  25222. _super.call(this, triggerOptions, condition);
  25223. this.value = value;
  25224. this._target = target;
  25225. }
  25226. SetStateAction.prototype.execute = function () {
  25227. this._target.state = this.value;
  25228. };
  25229. return SetStateAction;
  25230. })(BABYLON.Action);
  25231. BABYLON.SetStateAction = SetStateAction;
  25232. var SetValueAction = (function (_super) {
  25233. __extends(SetValueAction, _super);
  25234. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  25235. _super.call(this, triggerOptions, condition);
  25236. this.propertyPath = propertyPath;
  25237. this.value = value;
  25238. this._target = target;
  25239. }
  25240. SetValueAction.prototype._prepare = function () {
  25241. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25242. this._property = this._getProperty(this.propertyPath);
  25243. };
  25244. SetValueAction.prototype.execute = function () {
  25245. this._target[this._property] = this.value;
  25246. };
  25247. return SetValueAction;
  25248. })(BABYLON.Action);
  25249. BABYLON.SetValueAction = SetValueAction;
  25250. var IncrementValueAction = (function (_super) {
  25251. __extends(IncrementValueAction, _super);
  25252. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  25253. _super.call(this, triggerOptions, condition);
  25254. this.propertyPath = propertyPath;
  25255. this.value = value;
  25256. this._target = target;
  25257. }
  25258. IncrementValueAction.prototype._prepare = function () {
  25259. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25260. this._property = this._getProperty(this.propertyPath);
  25261. if (typeof this._target[this._property] !== "number") {
  25262. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  25263. }
  25264. };
  25265. IncrementValueAction.prototype.execute = function () {
  25266. this._target[this._property] += this.value;
  25267. };
  25268. return IncrementValueAction;
  25269. })(BABYLON.Action);
  25270. BABYLON.IncrementValueAction = IncrementValueAction;
  25271. var PlayAnimationAction = (function (_super) {
  25272. __extends(PlayAnimationAction, _super);
  25273. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  25274. _super.call(this, triggerOptions, condition);
  25275. this.from = from;
  25276. this.to = to;
  25277. this.loop = loop;
  25278. this._target = target;
  25279. }
  25280. PlayAnimationAction.prototype._prepare = function () {
  25281. };
  25282. PlayAnimationAction.prototype.execute = function () {
  25283. var scene = this._actionManager.getScene();
  25284. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  25285. };
  25286. return PlayAnimationAction;
  25287. })(BABYLON.Action);
  25288. BABYLON.PlayAnimationAction = PlayAnimationAction;
  25289. var StopAnimationAction = (function (_super) {
  25290. __extends(StopAnimationAction, _super);
  25291. function StopAnimationAction(triggerOptions, target, condition) {
  25292. _super.call(this, triggerOptions, condition);
  25293. this._target = target;
  25294. }
  25295. StopAnimationAction.prototype._prepare = function () {
  25296. };
  25297. StopAnimationAction.prototype.execute = function () {
  25298. var scene = this._actionManager.getScene();
  25299. scene.stopAnimation(this._target);
  25300. };
  25301. return StopAnimationAction;
  25302. })(BABYLON.Action);
  25303. BABYLON.StopAnimationAction = StopAnimationAction;
  25304. var DoNothingAction = (function (_super) {
  25305. __extends(DoNothingAction, _super);
  25306. function DoNothingAction(triggerOptions, condition) {
  25307. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  25308. _super.call(this, triggerOptions, condition);
  25309. }
  25310. DoNothingAction.prototype.execute = function () {
  25311. };
  25312. return DoNothingAction;
  25313. })(BABYLON.Action);
  25314. BABYLON.DoNothingAction = DoNothingAction;
  25315. var CombineAction = (function (_super) {
  25316. __extends(CombineAction, _super);
  25317. function CombineAction(triggerOptions, children, condition) {
  25318. _super.call(this, triggerOptions, condition);
  25319. this.children = children;
  25320. }
  25321. CombineAction.prototype._prepare = function () {
  25322. for (var index = 0; index < this.children.length; index++) {
  25323. this.children[index]._actionManager = this._actionManager;
  25324. this.children[index]._prepare();
  25325. }
  25326. };
  25327. CombineAction.prototype.execute = function (evt) {
  25328. for (var index = 0; index < this.children.length; index++) {
  25329. this.children[index].execute(evt);
  25330. }
  25331. };
  25332. return CombineAction;
  25333. })(BABYLON.Action);
  25334. BABYLON.CombineAction = CombineAction;
  25335. var ExecuteCodeAction = (function (_super) {
  25336. __extends(ExecuteCodeAction, _super);
  25337. function ExecuteCodeAction(triggerOptions, func, condition) {
  25338. _super.call(this, triggerOptions, condition);
  25339. this.func = func;
  25340. }
  25341. ExecuteCodeAction.prototype.execute = function (evt) {
  25342. this.func(evt);
  25343. };
  25344. return ExecuteCodeAction;
  25345. })(BABYLON.Action);
  25346. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  25347. var SetParentAction = (function (_super) {
  25348. __extends(SetParentAction, _super);
  25349. function SetParentAction(triggerOptions, target, parent, condition) {
  25350. _super.call(this, triggerOptions, condition);
  25351. this._target = target;
  25352. this._parent = parent;
  25353. }
  25354. SetParentAction.prototype._prepare = function () {
  25355. };
  25356. SetParentAction.prototype.execute = function () {
  25357. if (this._target.parent === this._parent) {
  25358. return;
  25359. }
  25360. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  25361. invertParentWorldMatrix.invert();
  25362. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  25363. this._target.parent = this._parent;
  25364. };
  25365. return SetParentAction;
  25366. })(BABYLON.Action);
  25367. BABYLON.SetParentAction = SetParentAction;
  25368. var PlaySoundAction = (function (_super) {
  25369. __extends(PlaySoundAction, _super);
  25370. function PlaySoundAction(triggerOptions, sound, condition) {
  25371. _super.call(this, triggerOptions, condition);
  25372. this._sound = sound;
  25373. }
  25374. PlaySoundAction.prototype._prepare = function () {
  25375. };
  25376. PlaySoundAction.prototype.execute = function () {
  25377. if (this._sound !== undefined)
  25378. this._sound.play();
  25379. };
  25380. return PlaySoundAction;
  25381. })(BABYLON.Action);
  25382. BABYLON.PlaySoundAction = PlaySoundAction;
  25383. var StopSoundAction = (function (_super) {
  25384. __extends(StopSoundAction, _super);
  25385. function StopSoundAction(triggerOptions, sound, condition) {
  25386. _super.call(this, triggerOptions, condition);
  25387. this._sound = sound;
  25388. }
  25389. StopSoundAction.prototype._prepare = function () {
  25390. };
  25391. StopSoundAction.prototype.execute = function () {
  25392. if (this._sound !== undefined)
  25393. this._sound.stop();
  25394. };
  25395. return StopSoundAction;
  25396. })(BABYLON.Action);
  25397. BABYLON.StopSoundAction = StopSoundAction;
  25398. })(BABYLON || (BABYLON = {}));
  25399. //# sourceMappingURL=babylon.directActions.js.map
  25400. var BABYLON;
  25401. (function (BABYLON) {
  25402. var Geometry = (function () {
  25403. function Geometry(id, scene, vertexData, updatable, mesh) {
  25404. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25405. this._totalVertices = 0;
  25406. this._indices = [];
  25407. this._isDisposed = false;
  25408. this.id = id;
  25409. this._engine = scene.getEngine();
  25410. this._meshes = [];
  25411. this._scene = scene;
  25412. // vertexData
  25413. if (vertexData) {
  25414. this.setAllVerticesData(vertexData, updatable);
  25415. }
  25416. else {
  25417. this._totalVertices = 0;
  25418. this._indices = [];
  25419. }
  25420. // applyToMesh
  25421. if (mesh) {
  25422. this.applyToMesh(mesh);
  25423. mesh.computeWorldMatrix(true);
  25424. }
  25425. }
  25426. Geometry.prototype.getScene = function () {
  25427. return this._scene;
  25428. };
  25429. Geometry.prototype.getEngine = function () {
  25430. return this._engine;
  25431. };
  25432. Geometry.prototype.isReady = function () {
  25433. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  25434. };
  25435. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  25436. vertexData.applyToGeometry(this, updatable);
  25437. this.notifyUpdate();
  25438. };
  25439. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25440. this._vertexBuffers = this._vertexBuffers || {};
  25441. if (this._vertexBuffers[kind]) {
  25442. this._vertexBuffers[kind].dispose();
  25443. }
  25444. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  25445. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25446. stride = this._vertexBuffers[kind].getStrideSize();
  25447. this._totalVertices = data.length / stride;
  25448. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25449. var meshes = this._meshes;
  25450. var numOfMeshes = meshes.length;
  25451. for (var index = 0; index < numOfMeshes; index++) {
  25452. var mesh = meshes[index];
  25453. mesh._resetPointsArrayCache();
  25454. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25455. mesh._createGlobalSubMesh();
  25456. mesh.computeWorldMatrix(true);
  25457. }
  25458. }
  25459. this.notifyUpdate(kind);
  25460. };
  25461. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  25462. var vertexBuffer = this.getVertexBuffer(kind);
  25463. if (!vertexBuffer) {
  25464. return;
  25465. }
  25466. vertexBuffer.updateDirectly(data, offset);
  25467. this.notifyUpdate(kind);
  25468. };
  25469. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  25470. var vertexBuffer = this.getVertexBuffer(kind);
  25471. if (!vertexBuffer) {
  25472. return;
  25473. }
  25474. vertexBuffer.update(data);
  25475. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25476. var extend;
  25477. var stride = vertexBuffer.getStrideSize();
  25478. this._totalVertices = data.length / stride;
  25479. if (updateExtends) {
  25480. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25481. }
  25482. var meshes = this._meshes;
  25483. var numOfMeshes = meshes.length;
  25484. for (var index = 0; index < numOfMeshes; index++) {
  25485. var mesh = meshes[index];
  25486. mesh._resetPointsArrayCache();
  25487. if (updateExtends) {
  25488. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25489. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  25490. var subMesh = mesh.subMeshes[subIndex];
  25491. subMesh.refreshBoundingInfo();
  25492. }
  25493. }
  25494. }
  25495. }
  25496. this.notifyUpdate(kind);
  25497. };
  25498. Geometry.prototype.getTotalVertices = function () {
  25499. if (!this.isReady()) {
  25500. return 0;
  25501. }
  25502. return this._totalVertices;
  25503. };
  25504. Geometry.prototype.getVerticesData = function (kind) {
  25505. var vertexBuffer = this.getVertexBuffer(kind);
  25506. if (!vertexBuffer) {
  25507. return null;
  25508. }
  25509. return vertexBuffer.getData();
  25510. };
  25511. Geometry.prototype.getVertexBuffer = function (kind) {
  25512. if (!this.isReady()) {
  25513. return null;
  25514. }
  25515. return this._vertexBuffers[kind];
  25516. };
  25517. Geometry.prototype.getVertexBuffers = function () {
  25518. if (!this.isReady()) {
  25519. return null;
  25520. }
  25521. return this._vertexBuffers;
  25522. };
  25523. Geometry.prototype.isVerticesDataPresent = function (kind) {
  25524. if (!this._vertexBuffers) {
  25525. if (this._delayInfo) {
  25526. return this._delayInfo.indexOf(kind) !== -1;
  25527. }
  25528. return false;
  25529. }
  25530. return this._vertexBuffers[kind] !== undefined;
  25531. };
  25532. Geometry.prototype.getVerticesDataKinds = function () {
  25533. var result = [];
  25534. if (!this._vertexBuffers && this._delayInfo) {
  25535. for (var kind in this._delayInfo) {
  25536. result.push(kind);
  25537. }
  25538. }
  25539. else {
  25540. for (kind in this._vertexBuffers) {
  25541. result.push(kind);
  25542. }
  25543. }
  25544. return result;
  25545. };
  25546. Geometry.prototype.setIndices = function (indices, totalVertices) {
  25547. if (this._indexBuffer) {
  25548. this._engine._releaseBuffer(this._indexBuffer);
  25549. }
  25550. this._indices = indices;
  25551. if (this._meshes.length !== 0 && this._indices) {
  25552. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25553. }
  25554. if (totalVertices !== undefined) {
  25555. this._totalVertices = totalVertices;
  25556. }
  25557. var meshes = this._meshes;
  25558. var numOfMeshes = meshes.length;
  25559. for (var index = 0; index < numOfMeshes; index++) {
  25560. meshes[index]._createGlobalSubMesh();
  25561. }
  25562. this.notifyUpdate();
  25563. };
  25564. Geometry.prototype.getTotalIndices = function () {
  25565. if (!this.isReady()) {
  25566. return 0;
  25567. }
  25568. return this._indices.length;
  25569. };
  25570. Geometry.prototype.getIndices = function () {
  25571. if (!this.isReady()) {
  25572. return null;
  25573. }
  25574. return this._indices;
  25575. };
  25576. Geometry.prototype.getIndexBuffer = function () {
  25577. if (!this.isReady()) {
  25578. return null;
  25579. }
  25580. return this._indexBuffer;
  25581. };
  25582. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  25583. var meshes = this._meshes;
  25584. var index = meshes.indexOf(mesh);
  25585. if (index === -1) {
  25586. return;
  25587. }
  25588. for (var kind in this._vertexBuffers) {
  25589. this._vertexBuffers[kind].dispose();
  25590. }
  25591. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  25592. this._indexBuffer = null;
  25593. }
  25594. meshes.splice(index, 1);
  25595. mesh._geometry = null;
  25596. if (meshes.length === 0 && shouldDispose) {
  25597. this.dispose();
  25598. }
  25599. };
  25600. Geometry.prototype.applyToMesh = function (mesh) {
  25601. if (mesh._geometry === this) {
  25602. return;
  25603. }
  25604. var previousGeometry = mesh._geometry;
  25605. if (previousGeometry) {
  25606. previousGeometry.releaseForMesh(mesh);
  25607. }
  25608. var meshes = this._meshes;
  25609. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  25610. mesh._geometry = this;
  25611. this._scene.pushGeometry(this);
  25612. meshes.push(mesh);
  25613. if (this.isReady()) {
  25614. this._applyToMesh(mesh);
  25615. }
  25616. else {
  25617. mesh._boundingInfo = this._boundingInfo;
  25618. }
  25619. };
  25620. Geometry.prototype._applyToMesh = function (mesh) {
  25621. var numOfMeshes = this._meshes.length;
  25622. for (var kind in this._vertexBuffers) {
  25623. if (numOfMeshes === 1) {
  25624. this._vertexBuffers[kind].create();
  25625. }
  25626. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  25627. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25628. mesh._resetPointsArrayCache();
  25629. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  25630. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25631. mesh._createGlobalSubMesh();
  25632. //bounding info was just created again, world matrix should be applied again.
  25633. mesh._updateBoundingInfo();
  25634. }
  25635. }
  25636. // indexBuffer
  25637. if (numOfMeshes === 1 && this._indices) {
  25638. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25639. }
  25640. if (this._indexBuffer) {
  25641. this._indexBuffer.references = numOfMeshes;
  25642. }
  25643. };
  25644. Geometry.prototype.notifyUpdate = function (kind) {
  25645. if (this.onGeometryUpdated) {
  25646. this.onGeometryUpdated(this, kind);
  25647. }
  25648. };
  25649. Geometry.prototype.load = function (scene, onLoaded) {
  25650. var _this = this;
  25651. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25652. return;
  25653. }
  25654. if (this.isReady()) {
  25655. if (onLoaded) {
  25656. onLoaded();
  25657. }
  25658. return;
  25659. }
  25660. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  25661. scene._addPendingData(this);
  25662. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  25663. _this._delayLoadingFunction(JSON.parse(data), _this);
  25664. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25665. _this._delayInfo = [];
  25666. scene._removePendingData(_this);
  25667. var meshes = _this._meshes;
  25668. var numOfMeshes = meshes.length;
  25669. for (var index = 0; index < numOfMeshes; index++) {
  25670. _this._applyToMesh(meshes[index]);
  25671. }
  25672. if (onLoaded) {
  25673. onLoaded();
  25674. }
  25675. }, function () {
  25676. }, scene.database);
  25677. };
  25678. Geometry.prototype.isDisposed = function () {
  25679. return this._isDisposed;
  25680. };
  25681. Geometry.prototype.dispose = function () {
  25682. var meshes = this._meshes;
  25683. var numOfMeshes = meshes.length;
  25684. var index;
  25685. for (index = 0; index < numOfMeshes; index++) {
  25686. this.releaseForMesh(meshes[index]);
  25687. }
  25688. this._meshes = [];
  25689. for (var kind in this._vertexBuffers) {
  25690. this._vertexBuffers[kind].dispose();
  25691. }
  25692. this._vertexBuffers = [];
  25693. this._totalVertices = 0;
  25694. if (this._indexBuffer) {
  25695. this._engine._releaseBuffer(this._indexBuffer);
  25696. }
  25697. this._indexBuffer = null;
  25698. this._indices = [];
  25699. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25700. this.delayLoadingFile = null;
  25701. this._delayLoadingFunction = null;
  25702. this._delayInfo = [];
  25703. this._boundingInfo = null; // todo: .dispose()
  25704. this._scene.removeGeometry(this);
  25705. this._isDisposed = true;
  25706. };
  25707. Geometry.prototype.copy = function (id) {
  25708. var vertexData = new BABYLON.VertexData();
  25709. vertexData.indices = [];
  25710. var indices = this.getIndices();
  25711. for (var index = 0; index < indices.length; index++) {
  25712. vertexData.indices.push(indices[index]);
  25713. }
  25714. var updatable = false;
  25715. var stopChecking = false;
  25716. for (var kind in this._vertexBuffers) {
  25717. // using slice() to make a copy of the array and not just reference it
  25718. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  25719. if (!stopChecking) {
  25720. updatable = this.getVertexBuffer(kind).isUpdatable();
  25721. stopChecking = !updatable;
  25722. }
  25723. }
  25724. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  25725. geometry.delayLoadState = this.delayLoadState;
  25726. geometry.delayLoadingFile = this.delayLoadingFile;
  25727. geometry._delayLoadingFunction = this._delayLoadingFunction;
  25728. for (kind in this._delayInfo) {
  25729. geometry._delayInfo = geometry._delayInfo || [];
  25730. geometry._delayInfo.push(kind);
  25731. }
  25732. // Bounding info
  25733. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  25734. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25735. return geometry;
  25736. };
  25737. // Statics
  25738. Geometry.ExtractFromMesh = function (mesh, id) {
  25739. var geometry = mesh._geometry;
  25740. if (!geometry) {
  25741. return null;
  25742. }
  25743. return geometry.copy(id);
  25744. };
  25745. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  25746. // be aware Math.random() could cause collisions
  25747. Geometry.RandomId = function () {
  25748. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  25749. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  25750. return v.toString(16);
  25751. });
  25752. };
  25753. return Geometry;
  25754. })();
  25755. BABYLON.Geometry = Geometry;
  25756. /////// Primitives //////////////////////////////////////////////
  25757. var Geometry;
  25758. (function (Geometry) {
  25759. var Primitives;
  25760. (function (Primitives) {
  25761. /// Abstract class
  25762. var _Primitive = (function (_super) {
  25763. __extends(_Primitive, _super);
  25764. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  25765. this._beingRegenerated = true;
  25766. this._canBeRegenerated = canBeRegenerated;
  25767. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  25768. this._beingRegenerated = false;
  25769. }
  25770. _Primitive.prototype.canBeRegenerated = function () {
  25771. return this._canBeRegenerated;
  25772. };
  25773. _Primitive.prototype.regenerate = function () {
  25774. if (!this._canBeRegenerated) {
  25775. return;
  25776. }
  25777. this._beingRegenerated = true;
  25778. this.setAllVerticesData(this._regenerateVertexData(), false);
  25779. this._beingRegenerated = false;
  25780. };
  25781. _Primitive.prototype.asNewGeometry = function (id) {
  25782. return _super.prototype.copy.call(this, id);
  25783. };
  25784. // overrides
  25785. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  25786. if (!this._beingRegenerated) {
  25787. return;
  25788. }
  25789. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  25790. };
  25791. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  25792. if (!this._beingRegenerated) {
  25793. return;
  25794. }
  25795. _super.prototype.setVerticesData.call(this, kind, data, false);
  25796. };
  25797. // to override
  25798. // protected
  25799. _Primitive.prototype._regenerateVertexData = function () {
  25800. throw new Error("Abstract method");
  25801. };
  25802. _Primitive.prototype.copy = function (id) {
  25803. throw new Error("Must be overriden in sub-classes.");
  25804. };
  25805. return _Primitive;
  25806. })(Geometry);
  25807. Primitives._Primitive = _Primitive;
  25808. var Ribbon = (function (_super) {
  25809. __extends(Ribbon, _super);
  25810. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  25811. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25812. this.pathArray = pathArray;
  25813. this.closeArray = closeArray;
  25814. this.closePath = closePath;
  25815. this.offset = offset;
  25816. this.side = side;
  25817. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25818. }
  25819. Ribbon.prototype._regenerateVertexData = function () {
  25820. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  25821. };
  25822. Ribbon.prototype.copy = function (id) {
  25823. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  25824. };
  25825. return Ribbon;
  25826. })(_Primitive);
  25827. Primitives.Ribbon = Ribbon;
  25828. var Box = (function (_super) {
  25829. __extends(Box, _super);
  25830. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  25831. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25832. this.size = size;
  25833. this.side = side;
  25834. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25835. }
  25836. Box.prototype._regenerateVertexData = function () {
  25837. return BABYLON.VertexData.CreateBox(this.size, this.side);
  25838. };
  25839. Box.prototype.copy = function (id) {
  25840. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25841. };
  25842. return Box;
  25843. })(_Primitive);
  25844. Primitives.Box = Box;
  25845. var Sphere = (function (_super) {
  25846. __extends(Sphere, _super);
  25847. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  25848. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25849. this.segments = segments;
  25850. this.diameter = diameter;
  25851. this.side = side;
  25852. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25853. }
  25854. Sphere.prototype._regenerateVertexData = function () {
  25855. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  25856. };
  25857. Sphere.prototype.copy = function (id) {
  25858. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  25859. };
  25860. return Sphere;
  25861. })(_Primitive);
  25862. Primitives.Sphere = Sphere;
  25863. var Cylinder = (function (_super) {
  25864. __extends(Cylinder, _super);
  25865. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  25866. if (subdivisions === void 0) { subdivisions = 1; }
  25867. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25868. this.height = height;
  25869. this.diameterTop = diameterTop;
  25870. this.diameterBottom = diameterBottom;
  25871. this.tessellation = tessellation;
  25872. this.subdivisions = subdivisions;
  25873. this.side = side;
  25874. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25875. }
  25876. Cylinder.prototype._regenerateVertexData = function () {
  25877. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  25878. };
  25879. Cylinder.prototype.copy = function (id) {
  25880. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  25881. };
  25882. return Cylinder;
  25883. })(_Primitive);
  25884. Primitives.Cylinder = Cylinder;
  25885. var Torus = (function (_super) {
  25886. __extends(Torus, _super);
  25887. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  25888. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25889. this.diameter = diameter;
  25890. this.thickness = thickness;
  25891. this.tessellation = tessellation;
  25892. this.side = side;
  25893. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25894. }
  25895. Torus.prototype._regenerateVertexData = function () {
  25896. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  25897. };
  25898. Torus.prototype.copy = function (id) {
  25899. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  25900. };
  25901. return Torus;
  25902. })(_Primitive);
  25903. Primitives.Torus = Torus;
  25904. var Ground = (function (_super) {
  25905. __extends(Ground, _super);
  25906. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  25907. this.width = width;
  25908. this.height = height;
  25909. this.subdivisions = subdivisions;
  25910. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25911. }
  25912. Ground.prototype._regenerateVertexData = function () {
  25913. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  25914. };
  25915. Ground.prototype.copy = function (id) {
  25916. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  25917. };
  25918. return Ground;
  25919. })(_Primitive);
  25920. Primitives.Ground = Ground;
  25921. var TiledGround = (function (_super) {
  25922. __extends(TiledGround, _super);
  25923. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  25924. this.xmin = xmin;
  25925. this.zmin = zmin;
  25926. this.xmax = xmax;
  25927. this.zmax = zmax;
  25928. this.subdivisions = subdivisions;
  25929. this.precision = precision;
  25930. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25931. }
  25932. TiledGround.prototype._regenerateVertexData = function () {
  25933. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  25934. };
  25935. TiledGround.prototype.copy = function (id) {
  25936. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  25937. };
  25938. return TiledGround;
  25939. })(_Primitive);
  25940. Primitives.TiledGround = TiledGround;
  25941. var Plane = (function (_super) {
  25942. __extends(Plane, _super);
  25943. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  25944. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25945. this.size = size;
  25946. this.side = side;
  25947. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25948. }
  25949. Plane.prototype._regenerateVertexData = function () {
  25950. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  25951. };
  25952. Plane.prototype.copy = function (id) {
  25953. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25954. };
  25955. return Plane;
  25956. })(_Primitive);
  25957. Primitives.Plane = Plane;
  25958. var TorusKnot = (function (_super) {
  25959. __extends(TorusKnot, _super);
  25960. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  25961. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25962. this.radius = radius;
  25963. this.tube = tube;
  25964. this.radialSegments = radialSegments;
  25965. this.tubularSegments = tubularSegments;
  25966. this.p = p;
  25967. this.q = q;
  25968. this.side = side;
  25969. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25970. }
  25971. TorusKnot.prototype._regenerateVertexData = function () {
  25972. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  25973. };
  25974. TorusKnot.prototype.copy = function (id) {
  25975. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  25976. };
  25977. return TorusKnot;
  25978. })(_Primitive);
  25979. Primitives.TorusKnot = TorusKnot;
  25980. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  25981. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  25982. })(BABYLON || (BABYLON = {}));
  25983. //# sourceMappingURL=babylon.geometry.js.map
  25984. var BABYLON;
  25985. (function (BABYLON) {
  25986. var Gamepads = (function () {
  25987. function Gamepads(ongamedpadconnected) {
  25988. var _this = this;
  25989. this.babylonGamepads = [];
  25990. this.oneGamepadConnected = false;
  25991. this.isMonitoring = false;
  25992. this.gamepadEventSupported = 'GamepadEvent' in window;
  25993. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  25994. 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=";
  25995. this._callbackGamepadConnected = ongamedpadconnected;
  25996. if (this.gamepadSupportAvailable) {
  25997. // Checking if the gamepad connected event is supported (like in Firefox)
  25998. if (this.gamepadEventSupported) {
  25999. window.addEventListener('gamepadconnected', function (evt) {
  26000. _this._onGamepadConnected(evt);
  26001. }, false);
  26002. window.addEventListener('gamepaddisconnected', function (evt) {
  26003. _this._onGamepadDisconnected(evt);
  26004. }, false);
  26005. }
  26006. else {
  26007. this._startMonitoringGamepads();
  26008. }
  26009. if (!this.oneGamepadConnected) {
  26010. this._insertGamepadDOMInstructions();
  26011. }
  26012. }
  26013. else {
  26014. this._insertGamepadDOMNotSupported();
  26015. }
  26016. }
  26017. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  26018. Gamepads.gamepadDOMInfo = document.createElement("div");
  26019. var buttonAImage = document.createElement("img");
  26020. buttonAImage.src = this.buttonADataURL;
  26021. var spanMessage = document.createElement("span");
  26022. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  26023. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  26024. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  26025. Gamepads.gamepadDOMInfo.style.position = "absolute";
  26026. Gamepads.gamepadDOMInfo.style.width = "100%";
  26027. Gamepads.gamepadDOMInfo.style.height = "48px";
  26028. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  26029. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  26030. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  26031. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  26032. buttonAImage.style.position = "relative";
  26033. buttonAImage.style.bottom = "8px";
  26034. spanMessage.style.position = "relative";
  26035. spanMessage.style.fontSize = "32px";
  26036. spanMessage.style.bottom = "32px";
  26037. spanMessage.style.color = "green";
  26038. document.body.appendChild(Gamepads.gamepadDOMInfo);
  26039. };
  26040. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  26041. Gamepads.gamepadDOMInfo = document.createElement("div");
  26042. var spanMessage = document.createElement("span");
  26043. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  26044. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  26045. Gamepads.gamepadDOMInfo.style.position = "absolute";
  26046. Gamepads.gamepadDOMInfo.style.width = "100%";
  26047. Gamepads.gamepadDOMInfo.style.height = "40px";
  26048. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  26049. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  26050. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  26051. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  26052. spanMessage.style.position = "relative";
  26053. spanMessage.style.fontSize = "32px";
  26054. spanMessage.style.color = "red";
  26055. document.body.appendChild(Gamepads.gamepadDOMInfo);
  26056. };
  26057. Gamepads.prototype.dispose = function () {
  26058. if (Gamepads.gamepadDOMInfo) {
  26059. document.body.removeChild(Gamepads.gamepadDOMInfo);
  26060. }
  26061. };
  26062. Gamepads.prototype._onGamepadConnected = function (evt) {
  26063. var newGamepad = this._addNewGamepad(evt.gamepad);
  26064. if (this._callbackGamepadConnected)
  26065. this._callbackGamepadConnected(newGamepad);
  26066. this._startMonitoringGamepads();
  26067. };
  26068. Gamepads.prototype._addNewGamepad = function (gamepad) {
  26069. if (!this.oneGamepadConnected) {
  26070. this.oneGamepadConnected = true;
  26071. if (Gamepads.gamepadDOMInfo) {
  26072. document.body.removeChild(Gamepads.gamepadDOMInfo);
  26073. Gamepads.gamepadDOMInfo = null;
  26074. }
  26075. }
  26076. var newGamepad;
  26077. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  26078. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  26079. }
  26080. else {
  26081. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  26082. }
  26083. this.babylonGamepads.push(newGamepad);
  26084. return newGamepad;
  26085. };
  26086. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  26087. for (var i in this.babylonGamepads) {
  26088. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  26089. this.babylonGamepads.splice(i, 1);
  26090. break;
  26091. }
  26092. }
  26093. // If no gamepads are left, stop the polling loop.
  26094. if (this.babylonGamepads.length == 0) {
  26095. this._stopMonitoringGamepads();
  26096. }
  26097. };
  26098. Gamepads.prototype._startMonitoringGamepads = function () {
  26099. if (!this.isMonitoring) {
  26100. this.isMonitoring = true;
  26101. this._checkGamepadsStatus();
  26102. }
  26103. };
  26104. Gamepads.prototype._stopMonitoringGamepads = function () {
  26105. this.isMonitoring = false;
  26106. };
  26107. Gamepads.prototype._checkGamepadsStatus = function () {
  26108. var _this = this;
  26109. // updating gamepad objects
  26110. this._updateGamepadObjects();
  26111. for (var i in this.babylonGamepads) {
  26112. this.babylonGamepads[i].update();
  26113. }
  26114. if (this.isMonitoring) {
  26115. if (window.requestAnimationFrame) {
  26116. window.requestAnimationFrame(function () {
  26117. _this._checkGamepadsStatus();
  26118. });
  26119. }
  26120. else if (window.mozRequestAnimationFrame) {
  26121. window.mozRequestAnimationFrame(function () {
  26122. _this._checkGamepadsStatus();
  26123. });
  26124. }
  26125. else if (window.webkitRequestAnimationFrame) {
  26126. window.webkitRequestAnimationFrame(function () {
  26127. _this._checkGamepadsStatus();
  26128. });
  26129. }
  26130. }
  26131. };
  26132. // This function is called only on Chrome, which does not yet support
  26133. // connection/disconnection events, but requires you to monitor
  26134. // an array for changes.
  26135. Gamepads.prototype._updateGamepadObjects = function () {
  26136. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  26137. for (var i = 0; i < gamepads.length; i++) {
  26138. if (gamepads[i]) {
  26139. if (!(gamepads[i].index in this.babylonGamepads)) {
  26140. var newGamepad = this._addNewGamepad(gamepads[i]);
  26141. if (this._callbackGamepadConnected) {
  26142. this._callbackGamepadConnected(newGamepad);
  26143. }
  26144. }
  26145. else {
  26146. this.babylonGamepads[i].browserGamepad = gamepads[i];
  26147. }
  26148. }
  26149. }
  26150. };
  26151. return Gamepads;
  26152. })();
  26153. BABYLON.Gamepads = Gamepads;
  26154. var StickValues = (function () {
  26155. function StickValues(x, y) {
  26156. this.x = x;
  26157. this.y = y;
  26158. }
  26159. return StickValues;
  26160. })();
  26161. BABYLON.StickValues = StickValues;
  26162. var Gamepad = (function () {
  26163. function Gamepad(id, index, browserGamepad) {
  26164. this.id = id;
  26165. this.index = index;
  26166. this.browserGamepad = browserGamepad;
  26167. if (this.browserGamepad.axes.length >= 2) {
  26168. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  26169. }
  26170. if (this.browserGamepad.axes.length >= 4) {
  26171. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  26172. }
  26173. }
  26174. Gamepad.prototype.onleftstickchanged = function (callback) {
  26175. this._onleftstickchanged = callback;
  26176. };
  26177. Gamepad.prototype.onrightstickchanged = function (callback) {
  26178. this._onrightstickchanged = callback;
  26179. };
  26180. Object.defineProperty(Gamepad.prototype, "leftStick", {
  26181. get: function () {
  26182. return this._leftStick;
  26183. },
  26184. set: function (newValues) {
  26185. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  26186. this._onleftstickchanged(newValues);
  26187. }
  26188. this._leftStick = newValues;
  26189. },
  26190. enumerable: true,
  26191. configurable: true
  26192. });
  26193. Object.defineProperty(Gamepad.prototype, "rightStick", {
  26194. get: function () {
  26195. return this._rightStick;
  26196. },
  26197. set: function (newValues) {
  26198. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  26199. this._onrightstickchanged(newValues);
  26200. }
  26201. this._rightStick = newValues;
  26202. },
  26203. enumerable: true,
  26204. configurable: true
  26205. });
  26206. Gamepad.prototype.update = function () {
  26207. if (this._leftStick) {
  26208. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  26209. }
  26210. if (this._rightStick) {
  26211. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  26212. }
  26213. };
  26214. return Gamepad;
  26215. })();
  26216. BABYLON.Gamepad = Gamepad;
  26217. var GenericPad = (function (_super) {
  26218. __extends(GenericPad, _super);
  26219. function GenericPad(id, index, gamepad) {
  26220. _super.call(this, id, index, gamepad);
  26221. this.id = id;
  26222. this.index = index;
  26223. this.gamepad = gamepad;
  26224. this._buttons = new Array(gamepad.buttons.length);
  26225. }
  26226. GenericPad.prototype.onbuttondown = function (callback) {
  26227. this._onbuttondown = callback;
  26228. };
  26229. GenericPad.prototype.onbuttonup = function (callback) {
  26230. this._onbuttonup = callback;
  26231. };
  26232. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  26233. if (newValue !== currentValue) {
  26234. if (this._onbuttondown && newValue === 1) {
  26235. this._onbuttondown(buttonIndex);
  26236. }
  26237. if (this._onbuttonup && newValue === 0) {
  26238. this._onbuttonup(buttonIndex);
  26239. }
  26240. }
  26241. return newValue;
  26242. };
  26243. GenericPad.prototype.update = function () {
  26244. _super.prototype.update.call(this);
  26245. for (var index = 0; index < this._buttons.length; index++) {
  26246. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  26247. }
  26248. };
  26249. return GenericPad;
  26250. })(Gamepad);
  26251. BABYLON.GenericPad = GenericPad;
  26252. (function (Xbox360Button) {
  26253. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  26254. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  26255. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  26256. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  26257. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  26258. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  26259. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  26260. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  26261. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  26262. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  26263. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  26264. var Xbox360Button = BABYLON.Xbox360Button;
  26265. (function (Xbox360Dpad) {
  26266. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  26267. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  26268. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  26269. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  26270. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  26271. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  26272. var Xbox360Pad = (function (_super) {
  26273. __extends(Xbox360Pad, _super);
  26274. function Xbox360Pad() {
  26275. _super.apply(this, arguments);
  26276. this._leftTrigger = 0;
  26277. this._rightTrigger = 0;
  26278. this._buttonA = 0;
  26279. this._buttonB = 0;
  26280. this._buttonX = 0;
  26281. this._buttonY = 0;
  26282. this._buttonBack = 0;
  26283. this._buttonStart = 0;
  26284. this._buttonLB = 0;
  26285. this._buttonRB = 0;
  26286. this._buttonLeftStick = 0;
  26287. this._buttonRightStick = 0;
  26288. this._dPadUp = 0;
  26289. this._dPadDown = 0;
  26290. this._dPadLeft = 0;
  26291. this._dPadRight = 0;
  26292. }
  26293. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  26294. this._onlefttriggerchanged = callback;
  26295. };
  26296. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  26297. this._onrighttriggerchanged = callback;
  26298. };
  26299. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  26300. get: function () {
  26301. return this._leftTrigger;
  26302. },
  26303. set: function (newValue) {
  26304. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  26305. this._onlefttriggerchanged(newValue);
  26306. }
  26307. this._leftTrigger = newValue;
  26308. },
  26309. enumerable: true,
  26310. configurable: true
  26311. });
  26312. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  26313. get: function () {
  26314. return this._rightTrigger;
  26315. },
  26316. set: function (newValue) {
  26317. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  26318. this._onrighttriggerchanged(newValue);
  26319. }
  26320. this._rightTrigger = newValue;
  26321. },
  26322. enumerable: true,
  26323. configurable: true
  26324. });
  26325. Xbox360Pad.prototype.onbuttondown = function (callback) {
  26326. this._onbuttondown = callback;
  26327. };
  26328. Xbox360Pad.prototype.onbuttonup = function (callback) {
  26329. this._onbuttonup = callback;
  26330. };
  26331. Xbox360Pad.prototype.ondpaddown = function (callback) {
  26332. this._ondpaddown = callback;
  26333. };
  26334. Xbox360Pad.prototype.ondpadup = function (callback) {
  26335. this._ondpadup = callback;
  26336. };
  26337. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  26338. if (newValue !== currentValue) {
  26339. if (this._onbuttondown && newValue === 1) {
  26340. this._onbuttondown(buttonType);
  26341. }
  26342. if (this._onbuttonup && newValue === 0) {
  26343. this._onbuttonup(buttonType);
  26344. }
  26345. }
  26346. return newValue;
  26347. };
  26348. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  26349. if (newValue !== currentValue) {
  26350. if (this._ondpaddown && newValue === 1) {
  26351. this._ondpaddown(buttonType);
  26352. }
  26353. if (this._ondpadup && newValue === 0) {
  26354. this._ondpadup(buttonType);
  26355. }
  26356. }
  26357. return newValue;
  26358. };
  26359. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  26360. get: function () {
  26361. return this._buttonA;
  26362. },
  26363. set: function (value) {
  26364. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  26365. },
  26366. enumerable: true,
  26367. configurable: true
  26368. });
  26369. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  26370. get: function () {
  26371. return this._buttonB;
  26372. },
  26373. set: function (value) {
  26374. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  26375. },
  26376. enumerable: true,
  26377. configurable: true
  26378. });
  26379. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  26380. get: function () {
  26381. return this._buttonX;
  26382. },
  26383. set: function (value) {
  26384. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  26385. },
  26386. enumerable: true,
  26387. configurable: true
  26388. });
  26389. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  26390. get: function () {
  26391. return this._buttonY;
  26392. },
  26393. set: function (value) {
  26394. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  26395. },
  26396. enumerable: true,
  26397. configurable: true
  26398. });
  26399. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  26400. get: function () {
  26401. return this._buttonStart;
  26402. },
  26403. set: function (value) {
  26404. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  26405. },
  26406. enumerable: true,
  26407. configurable: true
  26408. });
  26409. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  26410. get: function () {
  26411. return this._buttonBack;
  26412. },
  26413. set: function (value) {
  26414. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  26415. },
  26416. enumerable: true,
  26417. configurable: true
  26418. });
  26419. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  26420. get: function () {
  26421. return this._buttonLB;
  26422. },
  26423. set: function (value) {
  26424. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  26425. },
  26426. enumerable: true,
  26427. configurable: true
  26428. });
  26429. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  26430. get: function () {
  26431. return this._buttonRB;
  26432. },
  26433. set: function (value) {
  26434. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  26435. },
  26436. enumerable: true,
  26437. configurable: true
  26438. });
  26439. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  26440. get: function () {
  26441. return this._buttonLeftStick;
  26442. },
  26443. set: function (value) {
  26444. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  26445. },
  26446. enumerable: true,
  26447. configurable: true
  26448. });
  26449. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  26450. get: function () {
  26451. return this._buttonRightStick;
  26452. },
  26453. set: function (value) {
  26454. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  26455. },
  26456. enumerable: true,
  26457. configurable: true
  26458. });
  26459. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  26460. get: function () {
  26461. return this._dPadUp;
  26462. },
  26463. set: function (value) {
  26464. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  26465. },
  26466. enumerable: true,
  26467. configurable: true
  26468. });
  26469. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  26470. get: function () {
  26471. return this._dPadDown;
  26472. },
  26473. set: function (value) {
  26474. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  26475. },
  26476. enumerable: true,
  26477. configurable: true
  26478. });
  26479. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  26480. get: function () {
  26481. return this._dPadLeft;
  26482. },
  26483. set: function (value) {
  26484. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  26485. },
  26486. enumerable: true,
  26487. configurable: true
  26488. });
  26489. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  26490. get: function () {
  26491. return this._dPadRight;
  26492. },
  26493. set: function (value) {
  26494. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  26495. },
  26496. enumerable: true,
  26497. configurable: true
  26498. });
  26499. Xbox360Pad.prototype.update = function () {
  26500. _super.prototype.update.call(this);
  26501. this.buttonA = this.browserGamepad.buttons[0].value;
  26502. this.buttonB = this.browserGamepad.buttons[1].value;
  26503. this.buttonX = this.browserGamepad.buttons[2].value;
  26504. this.buttonY = this.browserGamepad.buttons[3].value;
  26505. this.buttonLB = this.browserGamepad.buttons[4].value;
  26506. this.buttonRB = this.browserGamepad.buttons[5].value;
  26507. this.leftTrigger = this.browserGamepad.buttons[6].value;
  26508. this.rightTrigger = this.browserGamepad.buttons[7].value;
  26509. this.buttonBack = this.browserGamepad.buttons[8].value;
  26510. this.buttonStart = this.browserGamepad.buttons[9].value;
  26511. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  26512. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  26513. this.dPadUp = this.browserGamepad.buttons[12].value;
  26514. this.dPadDown = this.browserGamepad.buttons[13].value;
  26515. this.dPadLeft = this.browserGamepad.buttons[14].value;
  26516. this.dPadRight = this.browserGamepad.buttons[15].value;
  26517. };
  26518. return Xbox360Pad;
  26519. })(Gamepad);
  26520. BABYLON.Xbox360Pad = Xbox360Pad;
  26521. })(BABYLON || (BABYLON = {}));
  26522. //# sourceMappingURL=babylon.gamepads.js.map
  26523. var BABYLON;
  26524. (function (BABYLON) {
  26525. // We're mainly based on the logic defined into the FreeCamera code
  26526. var GamepadCamera = (function (_super) {
  26527. __extends(GamepadCamera, _super);
  26528. function GamepadCamera(name, position, scene) {
  26529. var _this = this;
  26530. _super.call(this, name, position, scene);
  26531. this.angularSensibility = 200;
  26532. this.moveSensibility = 75;
  26533. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  26534. _this._onNewGameConnected(gamepad);
  26535. });
  26536. }
  26537. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  26538. // Only the first gamepad can control the camera
  26539. if (gamepad.index === 0) {
  26540. this._gamepad = gamepad;
  26541. }
  26542. };
  26543. GamepadCamera.prototype._checkInputs = function () {
  26544. if (!this._gamepad) {
  26545. return;
  26546. }
  26547. var LSValues = this._gamepad.leftStick;
  26548. var normalizedLX = LSValues.x / this.moveSensibility;
  26549. var normalizedLY = LSValues.y / this.moveSensibility;
  26550. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  26551. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  26552. var RSValues = this._gamepad.rightStick;
  26553. var normalizedRX = RSValues.x / this.angularSensibility;
  26554. var normalizedRY = RSValues.y / this.angularSensibility;
  26555. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  26556. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  26557. ;
  26558. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  26559. var speed = this._computeLocalCameraSpeed() * 50.0;
  26560. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  26561. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  26562. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  26563. };
  26564. GamepadCamera.prototype.dispose = function () {
  26565. this._gamepads.dispose();
  26566. _super.prototype.dispose.call(this);
  26567. };
  26568. return GamepadCamera;
  26569. })(BABYLON.FreeCamera);
  26570. BABYLON.GamepadCamera = GamepadCamera;
  26571. })(BABYLON || (BABYLON = {}));
  26572. //# sourceMappingURL=babylon.gamepadCamera.js.map
  26573. var BABYLON;
  26574. (function (BABYLON) {
  26575. var LinesMesh = (function (_super) {
  26576. __extends(LinesMesh, _super);
  26577. function LinesMesh(name, scene, updatable) {
  26578. if (updatable === void 0) { updatable = false; }
  26579. _super.call(this, name, scene);
  26580. this.color = new BABYLON.Color3(1, 1, 1);
  26581. this.alpha = 1;
  26582. this._indices = new Array();
  26583. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  26584. attributes: ["position"],
  26585. uniforms: ["worldViewProjection", "color"],
  26586. needAlphaBlending: true
  26587. });
  26588. }
  26589. Object.defineProperty(LinesMesh.prototype, "material", {
  26590. get: function () {
  26591. return this._colorShader;
  26592. },
  26593. enumerable: true,
  26594. configurable: true
  26595. });
  26596. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  26597. get: function () {
  26598. return false;
  26599. },
  26600. enumerable: true,
  26601. configurable: true
  26602. });
  26603. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  26604. get: function () {
  26605. return false;
  26606. },
  26607. enumerable: true,
  26608. configurable: true
  26609. });
  26610. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  26611. var engine = this.getScene().getEngine();
  26612. var indexToBind = this._geometry.getIndexBuffer();
  26613. // VBOs
  26614. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  26615. // Color
  26616. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  26617. };
  26618. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  26619. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26620. return;
  26621. }
  26622. var engine = this.getScene().getEngine();
  26623. // Draw order
  26624. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  26625. };
  26626. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  26627. return null;
  26628. };
  26629. LinesMesh.prototype.dispose = function (doNotRecurse) {
  26630. this._colorShader.dispose();
  26631. _super.prototype.dispose.call(this, doNotRecurse);
  26632. };
  26633. return LinesMesh;
  26634. })(BABYLON.Mesh);
  26635. BABYLON.LinesMesh = LinesMesh;
  26636. })(BABYLON || (BABYLON = {}));
  26637. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  26638. (function (BABYLON) {
  26639. var OutlineRenderer = (function () {
  26640. function OutlineRenderer(scene) {
  26641. this._scene = scene;
  26642. }
  26643. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  26644. var _this = this;
  26645. if (useOverlay === void 0) { useOverlay = false; }
  26646. var scene = this._scene;
  26647. var engine = this._scene.getEngine();
  26648. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  26649. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  26650. return;
  26651. }
  26652. var mesh = subMesh.getRenderingMesh();
  26653. var material = subMesh.getMaterial();
  26654. engine.enableEffect(this._effect);
  26655. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  26656. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  26657. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  26658. // Bones
  26659. if (mesh.useBones) {
  26660. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  26661. }
  26662. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  26663. // Alpha test
  26664. if (material && material.needAlphaTesting()) {
  26665. var alphaTexture = material.getAlphaTestTexture();
  26666. this._effect.setTexture("diffuseSampler", alphaTexture);
  26667. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  26668. }
  26669. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  26670. _this._effect.setMatrix("world", world);
  26671. });
  26672. };
  26673. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  26674. var defines = [];
  26675. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  26676. var mesh = subMesh.getMesh();
  26677. var material = subMesh.getMaterial();
  26678. // Alpha test
  26679. if (material && material.needAlphaTesting()) {
  26680. defines.push("#define ALPHATEST");
  26681. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26682. attribs.push(BABYLON.VertexBuffer.UVKind);
  26683. defines.push("#define UV1");
  26684. }
  26685. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26686. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  26687. defines.push("#define UV2");
  26688. }
  26689. }
  26690. // Bones
  26691. if (mesh.useBones) {
  26692. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26693. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26694. defines.push("#define BONES");
  26695. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  26696. }
  26697. // Instances
  26698. if (useInstances) {
  26699. defines.push("#define INSTANCES");
  26700. attribs.push("world0");
  26701. attribs.push("world1");
  26702. attribs.push("world2");
  26703. attribs.push("world3");
  26704. }
  26705. // Get correct effect
  26706. var join = defines.join("\n");
  26707. if (this._cachedDefines !== join) {
  26708. this._cachedDefines = join;
  26709. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  26710. }
  26711. return this._effect.isReady();
  26712. };
  26713. return OutlineRenderer;
  26714. })();
  26715. BABYLON.OutlineRenderer = OutlineRenderer;
  26716. })(BABYLON || (BABYLON = {}));
  26717. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  26718. (function (BABYLON) {
  26719. var MeshAssetTask = (function () {
  26720. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  26721. this.name = name;
  26722. this.meshesNames = meshesNames;
  26723. this.rootUrl = rootUrl;
  26724. this.sceneFilename = sceneFilename;
  26725. this.isCompleted = false;
  26726. }
  26727. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26728. var _this = this;
  26729. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  26730. _this.loadedMeshes = meshes;
  26731. _this.loadedParticleSystems = particleSystems;
  26732. _this.loadedSkeletons = skeletons;
  26733. _this.isCompleted = true;
  26734. if (_this.onSuccess) {
  26735. _this.onSuccess(_this);
  26736. }
  26737. onSuccess();
  26738. }, null, function () {
  26739. if (_this.onError) {
  26740. _this.onError(_this);
  26741. }
  26742. onError();
  26743. });
  26744. };
  26745. return MeshAssetTask;
  26746. })();
  26747. BABYLON.MeshAssetTask = MeshAssetTask;
  26748. var TextFileAssetTask = (function () {
  26749. function TextFileAssetTask(name, url) {
  26750. this.name = name;
  26751. this.url = url;
  26752. this.isCompleted = false;
  26753. }
  26754. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26755. var _this = this;
  26756. BABYLON.Tools.LoadFile(this.url, function (data) {
  26757. _this.text = data;
  26758. _this.isCompleted = true;
  26759. if (_this.onSuccess) {
  26760. _this.onSuccess(_this);
  26761. }
  26762. onSuccess();
  26763. }, null, scene.database, false, function () {
  26764. if (_this.onError) {
  26765. _this.onError(_this);
  26766. }
  26767. onError();
  26768. });
  26769. };
  26770. return TextFileAssetTask;
  26771. })();
  26772. BABYLON.TextFileAssetTask = TextFileAssetTask;
  26773. var BinaryFileAssetTask = (function () {
  26774. function BinaryFileAssetTask(name, url) {
  26775. this.name = name;
  26776. this.url = url;
  26777. this.isCompleted = false;
  26778. }
  26779. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26780. var _this = this;
  26781. BABYLON.Tools.LoadFile(this.url, function (data) {
  26782. _this.data = data;
  26783. _this.isCompleted = true;
  26784. if (_this.onSuccess) {
  26785. _this.onSuccess(_this);
  26786. }
  26787. onSuccess();
  26788. }, null, scene.database, true, function () {
  26789. if (_this.onError) {
  26790. _this.onError(_this);
  26791. }
  26792. onError();
  26793. });
  26794. };
  26795. return BinaryFileAssetTask;
  26796. })();
  26797. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  26798. var ImageAssetTask = (function () {
  26799. function ImageAssetTask(name, url) {
  26800. this.name = name;
  26801. this.url = url;
  26802. this.isCompleted = false;
  26803. }
  26804. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26805. var _this = this;
  26806. var img = new Image();
  26807. img.onload = function () {
  26808. _this.image = img;
  26809. _this.isCompleted = true;
  26810. if (_this.onSuccess) {
  26811. _this.onSuccess(_this);
  26812. }
  26813. onSuccess();
  26814. };
  26815. img.onerror = function () {
  26816. if (_this.onError) {
  26817. _this.onError(_this);
  26818. }
  26819. onError();
  26820. };
  26821. img.src = this.url;
  26822. };
  26823. return ImageAssetTask;
  26824. })();
  26825. BABYLON.ImageAssetTask = ImageAssetTask;
  26826. var TextureAssetTask = (function () {
  26827. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  26828. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26829. this.name = name;
  26830. this.url = url;
  26831. this.noMipmap = noMipmap;
  26832. this.invertY = invertY;
  26833. this.samplingMode = samplingMode;
  26834. this.isCompleted = false;
  26835. }
  26836. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26837. var _this = this;
  26838. var onload = function () {
  26839. _this.isCompleted = true;
  26840. if (_this.onSuccess) {
  26841. _this.onSuccess(_this);
  26842. }
  26843. onSuccess();
  26844. };
  26845. var onerror = function () {
  26846. if (_this.onError) {
  26847. _this.onError(_this);
  26848. }
  26849. onError();
  26850. };
  26851. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  26852. };
  26853. return TextureAssetTask;
  26854. })();
  26855. BABYLON.TextureAssetTask = TextureAssetTask;
  26856. var AssetsManager = (function () {
  26857. function AssetsManager(scene) {
  26858. this._tasks = new Array();
  26859. this._waitingTasksCount = 0;
  26860. this.useDefaultLoadingScreen = true;
  26861. this._scene = scene;
  26862. }
  26863. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  26864. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  26865. this._tasks.push(task);
  26866. return task;
  26867. };
  26868. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  26869. var task = new TextFileAssetTask(taskName, url);
  26870. this._tasks.push(task);
  26871. return task;
  26872. };
  26873. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  26874. var task = new BinaryFileAssetTask(taskName, url);
  26875. this._tasks.push(task);
  26876. return task;
  26877. };
  26878. AssetsManager.prototype.addImageTask = function (taskName, url) {
  26879. var task = new ImageAssetTask(taskName, url);
  26880. this._tasks.push(task);
  26881. return task;
  26882. };
  26883. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  26884. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26885. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  26886. this._tasks.push(task);
  26887. return task;
  26888. };
  26889. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  26890. this._waitingTasksCount--;
  26891. if (this._waitingTasksCount === 0) {
  26892. if (this.onFinish) {
  26893. this.onFinish(this._tasks);
  26894. }
  26895. this._scene.getEngine().hideLoadingUI();
  26896. }
  26897. };
  26898. AssetsManager.prototype._runTask = function (task) {
  26899. var _this = this;
  26900. task.run(this._scene, function () {
  26901. if (_this.onTaskSuccess) {
  26902. _this.onTaskSuccess(task);
  26903. }
  26904. _this._decreaseWaitingTasksCount();
  26905. }, function () {
  26906. if (_this.onTaskError) {
  26907. _this.onTaskError(task);
  26908. }
  26909. _this._decreaseWaitingTasksCount();
  26910. });
  26911. };
  26912. AssetsManager.prototype.reset = function () {
  26913. this._tasks = new Array();
  26914. return this;
  26915. };
  26916. AssetsManager.prototype.load = function () {
  26917. this._waitingTasksCount = this._tasks.length;
  26918. if (this._waitingTasksCount === 0) {
  26919. if (this.onFinish) {
  26920. this.onFinish(this._tasks);
  26921. }
  26922. return this;
  26923. }
  26924. if (this.useDefaultLoadingScreen) {
  26925. this._scene.getEngine().displayLoadingUI();
  26926. }
  26927. for (var index = 0; index < this._tasks.length; index++) {
  26928. var task = this._tasks[index];
  26929. this._runTask(task);
  26930. }
  26931. return this;
  26932. };
  26933. return AssetsManager;
  26934. })();
  26935. BABYLON.AssetsManager = AssetsManager;
  26936. })(BABYLON || (BABYLON = {}));
  26937. //# sourceMappingURL=babylon.assetsManager.js.map
  26938. var BABYLON;
  26939. (function (BABYLON) {
  26940. var VRDeviceOrientationCamera = (function (_super) {
  26941. __extends(VRDeviceOrientationCamera, _super);
  26942. function VRDeviceOrientationCamera(name, position, scene) {
  26943. _super.call(this, name, position, scene);
  26944. this._alpha = 0;
  26945. this._beta = 0;
  26946. this._gamma = 0;
  26947. }
  26948. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  26949. this._alpha = +evt.alpha | 0;
  26950. this._beta = +evt.beta | 0;
  26951. this._gamma = +evt.gamma | 0;
  26952. if (this._gamma < 0) {
  26953. this._gamma = 90 + this._gamma;
  26954. }
  26955. else {
  26956. // Incline it in the correct angle.
  26957. this._gamma = 270 - this._gamma;
  26958. }
  26959. this.rotation.x = this._gamma / 180.0 * Math.PI;
  26960. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  26961. this.rotation.z = this._beta / 180.0 * Math.PI;
  26962. };
  26963. return VRDeviceOrientationCamera;
  26964. })(BABYLON.OculusCamera);
  26965. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  26966. })(BABYLON || (BABYLON = {}));
  26967. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  26968. var BABYLON;
  26969. (function (BABYLON) {
  26970. var WebVRCamera = (function (_super) {
  26971. __extends(WebVRCamera, _super);
  26972. function WebVRCamera(name, position, scene) {
  26973. _super.call(this, name, position, scene);
  26974. this._hmdDevice = null;
  26975. this._sensorDevice = null;
  26976. this._cacheState = null;
  26977. this._cacheQuaternion = new BABYLON.Quaternion();
  26978. this._cacheRotation = BABYLON.Vector3.Zero();
  26979. this._vrEnabled = false;
  26980. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  26981. }
  26982. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  26983. var size = devices.length;
  26984. var i = 0;
  26985. // Reset devices.
  26986. this._sensorDevice = null;
  26987. this._hmdDevice = null;
  26988. while (i < size && this._hmdDevice === null) {
  26989. if (devices[i] instanceof HMDVRDevice) {
  26990. this._hmdDevice = devices[i];
  26991. }
  26992. i++;
  26993. }
  26994. i = 0;
  26995. while (i < size && this._sensorDevice === null) {
  26996. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  26997. this._sensorDevice = devices[i];
  26998. }
  26999. i++;
  27000. }
  27001. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  27002. };
  27003. WebVRCamera.prototype._update = function () {
  27004. if (this._vrEnabled) {
  27005. this._cacheState = this._sensorDevice.getState();
  27006. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  27007. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  27008. this.rotation.x = -this._cacheRotation.z;
  27009. this.rotation.y = -this._cacheRotation.y;
  27010. this.rotation.z = this._cacheRotation.x;
  27011. }
  27012. _super.prototype._update.call(this);
  27013. };
  27014. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  27015. _super.prototype.attachControl.call(this, element, noPreventDefault);
  27016. if (navigator.getVRDevices) {
  27017. navigator.getVRDevices().then(this._getWebVRDevices);
  27018. }
  27019. else if (navigator.mozGetVRDevices) {
  27020. navigator.mozGetVRDevices(this._getWebVRDevices);
  27021. }
  27022. };
  27023. WebVRCamera.prototype.detachControl = function (element) {
  27024. _super.prototype.detachControl.call(this, element);
  27025. this._vrEnabled = false;
  27026. };
  27027. return WebVRCamera;
  27028. })(BABYLON.OculusCamera);
  27029. BABYLON.WebVRCamera = WebVRCamera;
  27030. })(BABYLON || (BABYLON = {}));
  27031. //# sourceMappingURL=babylon.webVRCamera.js.map
  27032. var BABYLON;
  27033. (function (BABYLON) {
  27034. // Standard optimizations
  27035. var SceneOptimization = (function () {
  27036. function SceneOptimization(priority) {
  27037. if (priority === void 0) { priority = 0; }
  27038. this.priority = priority;
  27039. this.apply = function (scene) {
  27040. return true; // Return true if everything that can be done was applied
  27041. };
  27042. }
  27043. return SceneOptimization;
  27044. })();
  27045. BABYLON.SceneOptimization = SceneOptimization;
  27046. var TextureOptimization = (function (_super) {
  27047. __extends(TextureOptimization, _super);
  27048. function TextureOptimization(priority, maximumSize) {
  27049. var _this = this;
  27050. if (priority === void 0) { priority = 0; }
  27051. if (maximumSize === void 0) { maximumSize = 1024; }
  27052. _super.call(this, priority);
  27053. this.priority = priority;
  27054. this.maximumSize = maximumSize;
  27055. this.apply = function (scene) {
  27056. var allDone = true;
  27057. for (var index = 0; index < scene.textures.length; index++) {
  27058. var texture = scene.textures[index];
  27059. if (!texture.canRescale) {
  27060. continue;
  27061. }
  27062. var currentSize = texture.getSize();
  27063. var maxDimension = Math.max(currentSize.width, currentSize.height);
  27064. if (maxDimension > _this.maximumSize) {
  27065. texture.scale(0.5);
  27066. allDone = false;
  27067. }
  27068. }
  27069. return allDone;
  27070. };
  27071. }
  27072. return TextureOptimization;
  27073. })(SceneOptimization);
  27074. BABYLON.TextureOptimization = TextureOptimization;
  27075. var HardwareScalingOptimization = (function (_super) {
  27076. __extends(HardwareScalingOptimization, _super);
  27077. function HardwareScalingOptimization(priority, maximumScale) {
  27078. var _this = this;
  27079. if (priority === void 0) { priority = 0; }
  27080. if (maximumScale === void 0) { maximumScale = 2; }
  27081. _super.call(this, priority);
  27082. this.priority = priority;
  27083. this.maximumScale = maximumScale;
  27084. this._currentScale = 1;
  27085. this.apply = function (scene) {
  27086. _this._currentScale++;
  27087. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  27088. return _this._currentScale >= _this.maximumScale;
  27089. };
  27090. }
  27091. return HardwareScalingOptimization;
  27092. })(SceneOptimization);
  27093. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  27094. var ShadowsOptimization = (function (_super) {
  27095. __extends(ShadowsOptimization, _super);
  27096. function ShadowsOptimization() {
  27097. _super.apply(this, arguments);
  27098. this.apply = function (scene) {
  27099. scene.shadowsEnabled = false;
  27100. return true;
  27101. };
  27102. }
  27103. return ShadowsOptimization;
  27104. })(SceneOptimization);
  27105. BABYLON.ShadowsOptimization = ShadowsOptimization;
  27106. var PostProcessesOptimization = (function (_super) {
  27107. __extends(PostProcessesOptimization, _super);
  27108. function PostProcessesOptimization() {
  27109. _super.apply(this, arguments);
  27110. this.apply = function (scene) {
  27111. scene.postProcessesEnabled = false;
  27112. return true;
  27113. };
  27114. }
  27115. return PostProcessesOptimization;
  27116. })(SceneOptimization);
  27117. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  27118. var LensFlaresOptimization = (function (_super) {
  27119. __extends(LensFlaresOptimization, _super);
  27120. function LensFlaresOptimization() {
  27121. _super.apply(this, arguments);
  27122. this.apply = function (scene) {
  27123. scene.lensFlaresEnabled = false;
  27124. return true;
  27125. };
  27126. }
  27127. return LensFlaresOptimization;
  27128. })(SceneOptimization);
  27129. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  27130. var ParticlesOptimization = (function (_super) {
  27131. __extends(ParticlesOptimization, _super);
  27132. function ParticlesOptimization() {
  27133. _super.apply(this, arguments);
  27134. this.apply = function (scene) {
  27135. scene.particlesEnabled = false;
  27136. return true;
  27137. };
  27138. }
  27139. return ParticlesOptimization;
  27140. })(SceneOptimization);
  27141. BABYLON.ParticlesOptimization = ParticlesOptimization;
  27142. var RenderTargetsOptimization = (function (_super) {
  27143. __extends(RenderTargetsOptimization, _super);
  27144. function RenderTargetsOptimization() {
  27145. _super.apply(this, arguments);
  27146. this.apply = function (scene) {
  27147. scene.renderTargetsEnabled = false;
  27148. return true;
  27149. };
  27150. }
  27151. return RenderTargetsOptimization;
  27152. })(SceneOptimization);
  27153. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  27154. var MergeMeshesOptimization = (function (_super) {
  27155. __extends(MergeMeshesOptimization, _super);
  27156. function MergeMeshesOptimization() {
  27157. var _this = this;
  27158. _super.apply(this, arguments);
  27159. this._canBeMerged = function (abstractMesh) {
  27160. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  27161. return false;
  27162. }
  27163. var mesh = abstractMesh;
  27164. if (!mesh.isVisible || !mesh.isEnabled()) {
  27165. return false;
  27166. }
  27167. if (mesh.instances.length > 0) {
  27168. return false;
  27169. }
  27170. if (mesh.skeleton || mesh.hasLODLevels) {
  27171. return false;
  27172. }
  27173. return true;
  27174. };
  27175. this.apply = function (scene) {
  27176. var globalPool = scene.meshes.slice(0);
  27177. var globalLength = globalPool.length;
  27178. for (var index = 0; index < globalLength; index++) {
  27179. var currentPool = new Array();
  27180. var current = globalPool[index];
  27181. // Checks
  27182. if (!_this._canBeMerged(current)) {
  27183. continue;
  27184. }
  27185. currentPool.push(current);
  27186. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  27187. var otherMesh = globalPool[subIndex];
  27188. if (!_this._canBeMerged(otherMesh)) {
  27189. continue;
  27190. }
  27191. if (otherMesh.material !== current.material) {
  27192. continue;
  27193. }
  27194. if (otherMesh.checkCollisions !== current.checkCollisions) {
  27195. continue;
  27196. }
  27197. currentPool.push(otherMesh);
  27198. globalLength--;
  27199. globalPool.splice(subIndex, 1);
  27200. subIndex--;
  27201. }
  27202. if (currentPool.length < 2) {
  27203. continue;
  27204. }
  27205. // Merge meshes
  27206. BABYLON.Mesh.MergeMeshes(currentPool);
  27207. }
  27208. return true;
  27209. };
  27210. }
  27211. return MergeMeshesOptimization;
  27212. })(SceneOptimization);
  27213. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  27214. // Options
  27215. var SceneOptimizerOptions = (function () {
  27216. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  27217. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  27218. if (trackerDuration === void 0) { trackerDuration = 2000; }
  27219. this.targetFrameRate = targetFrameRate;
  27220. this.trackerDuration = trackerDuration;
  27221. this.optimizations = new Array();
  27222. }
  27223. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  27224. var result = new SceneOptimizerOptions(targetFrameRate);
  27225. var priority = 0;
  27226. result.optimizations.push(new MergeMeshesOptimization(priority));
  27227. result.optimizations.push(new ShadowsOptimization(priority));
  27228. result.optimizations.push(new LensFlaresOptimization(priority));
  27229. // Next priority
  27230. priority++;
  27231. result.optimizations.push(new PostProcessesOptimization(priority));
  27232. result.optimizations.push(new ParticlesOptimization(priority));
  27233. // Next priority
  27234. priority++;
  27235. result.optimizations.push(new TextureOptimization(priority, 1024));
  27236. return result;
  27237. };
  27238. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  27239. var result = new SceneOptimizerOptions(targetFrameRate);
  27240. var priority = 0;
  27241. result.optimizations.push(new MergeMeshesOptimization(priority));
  27242. result.optimizations.push(new ShadowsOptimization(priority));
  27243. result.optimizations.push(new LensFlaresOptimization(priority));
  27244. // Next priority
  27245. priority++;
  27246. result.optimizations.push(new PostProcessesOptimization(priority));
  27247. result.optimizations.push(new ParticlesOptimization(priority));
  27248. // Next priority
  27249. priority++;
  27250. result.optimizations.push(new TextureOptimization(priority, 512));
  27251. // Next priority
  27252. priority++;
  27253. result.optimizations.push(new RenderTargetsOptimization(priority));
  27254. // Next priority
  27255. priority++;
  27256. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  27257. return result;
  27258. };
  27259. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  27260. var result = new SceneOptimizerOptions(targetFrameRate);
  27261. var priority = 0;
  27262. result.optimizations.push(new MergeMeshesOptimization(priority));
  27263. result.optimizations.push(new ShadowsOptimization(priority));
  27264. result.optimizations.push(new LensFlaresOptimization(priority));
  27265. // Next priority
  27266. priority++;
  27267. result.optimizations.push(new PostProcessesOptimization(priority));
  27268. result.optimizations.push(new ParticlesOptimization(priority));
  27269. // Next priority
  27270. priority++;
  27271. result.optimizations.push(new TextureOptimization(priority, 256));
  27272. // Next priority
  27273. priority++;
  27274. result.optimizations.push(new RenderTargetsOptimization(priority));
  27275. // Next priority
  27276. priority++;
  27277. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  27278. return result;
  27279. };
  27280. return SceneOptimizerOptions;
  27281. })();
  27282. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  27283. // Scene optimizer tool
  27284. var SceneOptimizer = (function () {
  27285. function SceneOptimizer() {
  27286. }
  27287. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  27288. // TODO: add an epsilon
  27289. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  27290. if (onSuccess) {
  27291. onSuccess();
  27292. }
  27293. return;
  27294. }
  27295. // Apply current level of optimizations
  27296. var allDone = true;
  27297. var noOptimizationApplied = true;
  27298. for (var index = 0; index < options.optimizations.length; index++) {
  27299. var optimization = options.optimizations[index];
  27300. if (optimization.priority === currentPriorityLevel) {
  27301. noOptimizationApplied = false;
  27302. allDone = allDone && optimization.apply(scene);
  27303. }
  27304. }
  27305. // If no optimization was applied, this is a failure :(
  27306. if (noOptimizationApplied) {
  27307. if (onFailure) {
  27308. onFailure();
  27309. }
  27310. return;
  27311. }
  27312. // If all optimizations were done, move to next level
  27313. if (allDone) {
  27314. currentPriorityLevel++;
  27315. }
  27316. // Let's the system running for a specific amount of time before checking FPS
  27317. scene.executeWhenReady(function () {
  27318. setTimeout(function () {
  27319. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  27320. }, options.trackerDuration);
  27321. });
  27322. };
  27323. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  27324. if (!options) {
  27325. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  27326. }
  27327. // Let's the system running for a specific amount of time before checking FPS
  27328. scene.executeWhenReady(function () {
  27329. setTimeout(function () {
  27330. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  27331. }, options.trackerDuration);
  27332. });
  27333. };
  27334. return SceneOptimizer;
  27335. })();
  27336. BABYLON.SceneOptimizer = SceneOptimizer;
  27337. })(BABYLON || (BABYLON = {}));
  27338. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  27339. (function (BABYLON) {
  27340. var Internals;
  27341. (function (Internals) {
  27342. var MeshLODLevel = (function () {
  27343. function MeshLODLevel(distance, mesh) {
  27344. this.distance = distance;
  27345. this.mesh = mesh;
  27346. }
  27347. return MeshLODLevel;
  27348. })();
  27349. Internals.MeshLODLevel = MeshLODLevel;
  27350. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27351. })(BABYLON || (BABYLON = {}));
  27352. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  27353. (function (BABYLON) {
  27354. var AudioEngine = (function () {
  27355. function AudioEngine() {
  27356. this._audioContext = null;
  27357. this._audioContextInitialized = false;
  27358. this.canUseWebAudio = false;
  27359. this.WarnedWebAudioUnsupported = false;
  27360. if (typeof AudioContext !== 'undefined' || typeof webkitAudioContext !== 'undefined') {
  27361. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  27362. this.canUseWebAudio = true;
  27363. }
  27364. }
  27365. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  27366. get: function () {
  27367. if (!this._audioContextInitialized) {
  27368. this._initializeAudioContext();
  27369. }
  27370. return this._audioContext;
  27371. },
  27372. enumerable: true,
  27373. configurable: true
  27374. });
  27375. AudioEngine.prototype._initializeAudioContext = function () {
  27376. try {
  27377. if (this.canUseWebAudio) {
  27378. this._audioContext = new AudioContext();
  27379. // create a global volume gain node
  27380. this.masterGain = this._audioContext.createGain();
  27381. this.masterGain.gain.value = 1;
  27382. this.masterGain.connect(this._audioContext.destination);
  27383. this._audioContextInitialized = true;
  27384. }
  27385. }
  27386. catch (e) {
  27387. this.canUseWebAudio = false;
  27388. BABYLON.Tools.Error("Web Audio: " + e.message);
  27389. }
  27390. };
  27391. AudioEngine.prototype.dispose = function () {
  27392. if (this.canUseWebAudio && this._audioContextInitialized) {
  27393. if (this._connectedAnalyser) {
  27394. this._connectedAnalyser.stopDebugCanvas();
  27395. this._connectedAnalyser.dispose();
  27396. this.masterGain.disconnect();
  27397. this.masterGain.connect(this._audioContext.destination);
  27398. this._connectedAnalyser = null;
  27399. }
  27400. this.masterGain.gain.value = 1;
  27401. }
  27402. this.WarnedWebAudioUnsupported = false;
  27403. };
  27404. AudioEngine.prototype.getGlobalVolume = function () {
  27405. if (this.canUseWebAudio && this._audioContextInitialized) {
  27406. return this.masterGain.gain.value;
  27407. }
  27408. else {
  27409. return -1;
  27410. }
  27411. };
  27412. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  27413. if (this.canUseWebAudio && this._audioContextInitialized) {
  27414. this.masterGain.gain.value = newVolume;
  27415. }
  27416. };
  27417. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  27418. if (this._connectedAnalyser) {
  27419. this._connectedAnalyser.stopDebugCanvas();
  27420. }
  27421. if (this.canUseWebAudio && this._audioContextInitialized) {
  27422. this._connectedAnalyser = analyser;
  27423. this.masterGain.disconnect();
  27424. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  27425. }
  27426. };
  27427. return AudioEngine;
  27428. })();
  27429. BABYLON.AudioEngine = AudioEngine;
  27430. })(BABYLON || (BABYLON = {}));
  27431. //# sourceMappingURL=babylon.audioEngine.js.mapvar BABYLON;
  27432. (function (BABYLON) {
  27433. var Sound = (function () {
  27434. /**
  27435. * Create a sound and attach it to a scene
  27436. * @param name Name of your sound
  27437. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  27438. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  27439. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  27440. */
  27441. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  27442. var _this = this;
  27443. this.autoplay = false;
  27444. this.loop = false;
  27445. this.useCustomAttenuation = false;
  27446. this.spatialSound = false;
  27447. this.refDistance = 1;
  27448. this.rolloffFactor = 1;
  27449. this.maxDistance = 100;
  27450. this.distanceModel = "linear";
  27451. this._panningModel = "equalpower";
  27452. this._playbackRate = 1;
  27453. this._startTime = 0;
  27454. this._startOffset = 0;
  27455. this._position = BABYLON.Vector3.Zero();
  27456. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  27457. this._volume = 1;
  27458. this._isLoaded = false;
  27459. this._isReadyToPlay = false;
  27460. this.isPlaying = false;
  27461. this.isPaused = false;
  27462. this._isDirectional = false;
  27463. // Used if you'd like to create a directional sound.
  27464. // If not set, the sound will be omnidirectional
  27465. this._coneInnerAngle = 360;
  27466. this._coneOuterAngle = 360;
  27467. this._coneOuterGain = 0;
  27468. this.name = name;
  27469. this._scene = scene;
  27470. this._readyToPlayCallback = readyToPlayCallback;
  27471. // Default custom attenuation function is a linear attenuation
  27472. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  27473. if (currentDistance < maxDistance) {
  27474. return currentVolume * (1 - currentDistance / maxDistance);
  27475. }
  27476. else {
  27477. return 0;
  27478. }
  27479. };
  27480. if (options) {
  27481. this.autoplay = options.autoplay || false;
  27482. this.loop = options.loop || false;
  27483. // if volume === 0, we need another way to check this option
  27484. if (options.volume !== undefined) {
  27485. this._volume = options.volume;
  27486. }
  27487. this.spatialSound = options.spatialSound || false;
  27488. this.maxDistance = options.maxDistance || 100;
  27489. this.useCustomAttenuation = options.useCustomAttenuation || false;
  27490. this.rolloffFactor = options.rolloffFactor || 1;
  27491. this.refDistance = options.refDistance || 1;
  27492. this.distanceModel = options.distanceModel || "linear";
  27493. this._playbackRate = options.playbackRate || 1;
  27494. }
  27495. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27496. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  27497. this._soundGain.gain.value = this._volume;
  27498. this._inputAudioNode = this._soundGain;
  27499. this._ouputAudioNode = this._soundGain;
  27500. if (this.spatialSound) {
  27501. this._createSpatialParameters();
  27502. }
  27503. this._scene.mainSoundTrack.AddSound(this);
  27504. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  27505. if (urlOrArrayBuffer) {
  27506. // If it's an URL
  27507. if (typeof (urlOrArrayBuffer) === "string") {
  27508. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  27509. _this._soundLoaded(data);
  27510. }, null, null, true);
  27511. }
  27512. else {
  27513. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  27514. this._soundLoaded(urlOrArrayBuffer);
  27515. }
  27516. else {
  27517. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  27518. }
  27519. }
  27520. }
  27521. }
  27522. else {
  27523. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  27524. this._scene.mainSoundTrack.AddSound(this);
  27525. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  27526. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  27527. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  27528. }
  27529. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  27530. if (this._readyToPlayCallback) {
  27531. window.setTimeout(function () {
  27532. _this._readyToPlayCallback();
  27533. }, 1000);
  27534. }
  27535. }
  27536. }
  27537. Sound.prototype.dispose = function () {
  27538. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  27539. if (this.isPlaying) {
  27540. this.stop();
  27541. }
  27542. this._isReadyToPlay = false;
  27543. if (this.soundTrackId === -1) {
  27544. this._scene.mainSoundTrack.RemoveSound(this);
  27545. }
  27546. else {
  27547. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  27548. }
  27549. if (this._soundGain) {
  27550. this._soundGain.disconnect();
  27551. this._soundGain = null;
  27552. }
  27553. if (this._soundPanner) {
  27554. this._soundPanner.disconnect();
  27555. this._soundPanner = null;
  27556. }
  27557. if (this._soundSource) {
  27558. this._soundSource.disconnect();
  27559. this._soundSource = null;
  27560. }
  27561. this._audioBuffer = null;
  27562. if (this._connectedMesh) {
  27563. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  27564. this._connectedMesh = null;
  27565. }
  27566. }
  27567. };
  27568. Sound.prototype._soundLoaded = function (audioData) {
  27569. var _this = this;
  27570. this._isLoaded = true;
  27571. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  27572. _this._audioBuffer = buffer;
  27573. _this._isReadyToPlay = true;
  27574. if (_this.autoplay) {
  27575. _this.play();
  27576. }
  27577. if (_this._readyToPlayCallback) {
  27578. _this._readyToPlayCallback();
  27579. }
  27580. }, function (error) {
  27581. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  27582. });
  27583. };
  27584. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  27585. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27586. this._audioBuffer = audioBuffer;
  27587. this._isReadyToPlay = true;
  27588. }
  27589. };
  27590. Sound.prototype.updateOptions = function (options) {
  27591. if (options) {
  27592. this.loop = options.loop || this.loop;
  27593. this.maxDistance = options.maxDistance || this.maxDistance;
  27594. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  27595. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  27596. this.refDistance = options.refDistance || this.refDistance;
  27597. this.distanceModel = options.distanceModel || this.distanceModel;
  27598. this._playbackRate = options.playbackRate || this._playbackRate;
  27599. }
  27600. };
  27601. Sound.prototype._createSpatialParameters = function () {
  27602. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27603. if (this._scene.headphone) {
  27604. this._panningModel = "HRTF";
  27605. }
  27606. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  27607. if (this.useCustomAttenuation) {
  27608. // Tricks to disable in a way embedded Web Audio attenuation
  27609. this._soundPanner.distanceModel = "linear";
  27610. this._soundPanner.maxDistance = Number.MAX_VALUE;
  27611. this._soundPanner.refDistance = 1;
  27612. this._soundPanner.rolloffFactor = 1;
  27613. this._soundPanner.panningModel = this._panningModel;
  27614. }
  27615. else {
  27616. this._soundPanner.distanceModel = this.distanceModel;
  27617. this._soundPanner.maxDistance = this.maxDistance;
  27618. this._soundPanner.refDistance = this.refDistance;
  27619. this._soundPanner.rolloffFactor = this.rolloffFactor;
  27620. this._soundPanner.panningModel = this._panningModel;
  27621. }
  27622. this._soundPanner.connect(this._ouputAudioNode);
  27623. this._inputAudioNode = this._soundPanner;
  27624. }
  27625. };
  27626. Sound.prototype.switchPanningModelToHRTF = function () {
  27627. this._panningModel = "HRTF";
  27628. this._switchPanningModel();
  27629. };
  27630. Sound.prototype.switchPanningModelToEqualPower = function () {
  27631. this._panningModel = "equalpower";
  27632. this._switchPanningModel();
  27633. };
  27634. Sound.prototype._switchPanningModel = function () {
  27635. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  27636. this._soundPanner.panningModel = this._panningModel;
  27637. }
  27638. };
  27639. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  27640. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27641. this._ouputAudioNode.disconnect();
  27642. this._ouputAudioNode.connect(soundTrackAudioNode);
  27643. }
  27644. };
  27645. /**
  27646. * Transform this sound into a directional source
  27647. * @param coneInnerAngle Size of the inner cone in degree
  27648. * @param coneOuterAngle Size of the outer cone in degree
  27649. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  27650. */
  27651. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  27652. if (coneOuterAngle < coneInnerAngle) {
  27653. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  27654. return;
  27655. }
  27656. this._coneInnerAngle = coneInnerAngle;
  27657. this._coneOuterAngle = coneOuterAngle;
  27658. this._coneOuterGain = coneOuterGain;
  27659. this._isDirectional = true;
  27660. if (this.isPlaying && this.loop) {
  27661. this.stop();
  27662. this.play();
  27663. }
  27664. };
  27665. Sound.prototype.setPosition = function (newPosition) {
  27666. this._position = newPosition;
  27667. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  27668. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  27669. }
  27670. };
  27671. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  27672. this._localDirection = newLocalDirection;
  27673. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  27674. this._updateDirection();
  27675. }
  27676. };
  27677. Sound.prototype._updateDirection = function () {
  27678. var mat = this._connectedMesh.getWorldMatrix();
  27679. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  27680. direction.normalize();
  27681. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  27682. };
  27683. Sound.prototype.updateDistanceFromListener = function () {
  27684. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  27685. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  27686. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  27687. }
  27688. };
  27689. Sound.prototype.setAttenuationFunction = function (callback) {
  27690. this._customAttenuationFunction = callback;
  27691. };
  27692. /**
  27693. * Play the sound
  27694. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  27695. */
  27696. Sound.prototype.play = function (time) {
  27697. var _this = this;
  27698. if (this._isReadyToPlay && this._scene.audioEnabled) {
  27699. try {
  27700. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  27701. if (!this._soundSource) {
  27702. if (this.spatialSound) {
  27703. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  27704. if (this._isDirectional) {
  27705. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  27706. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  27707. this._soundPanner.coneOuterGain = this._coneOuterGain;
  27708. if (this._connectedMesh) {
  27709. this._updateDirection();
  27710. }
  27711. else {
  27712. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  27713. }
  27714. }
  27715. }
  27716. }
  27717. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  27718. this._soundSource.buffer = this._audioBuffer;
  27719. this._soundSource.connect(this._inputAudioNode);
  27720. this._soundSource.loop = this.loop;
  27721. this._soundSource.playbackRate.value = this._playbackRate;
  27722. this._startTime = startTime;
  27723. this._soundSource.onended = function () {
  27724. _this._onended();
  27725. };
  27726. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  27727. this.isPlaying = true;
  27728. this.isPaused = false;
  27729. }
  27730. catch (ex) {
  27731. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  27732. }
  27733. }
  27734. };
  27735. Sound.prototype._onended = function () {
  27736. this.isPlaying = false;
  27737. if (this.onended) {
  27738. this.onended();
  27739. }
  27740. };
  27741. /**
  27742. * Stop the sound
  27743. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  27744. */
  27745. Sound.prototype.stop = function (time) {
  27746. if (this.isPlaying) {
  27747. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  27748. this._soundSource.stop(stopTime);
  27749. this.isPlaying = false;
  27750. }
  27751. };
  27752. Sound.prototype.pause = function () {
  27753. if (this.isPlaying) {
  27754. this.stop(0);
  27755. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  27756. this.isPaused = true;
  27757. }
  27758. };
  27759. Sound.prototype.setVolume = function (newVolume, time) {
  27760. if (BABYLON.Engine.audioEngine.canUseWebAudio && !this.spatialSound) {
  27761. if (time) {
  27762. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  27763. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  27764. }
  27765. else {
  27766. this._soundGain.gain.value = newVolume;
  27767. }
  27768. }
  27769. this._volume = newVolume;
  27770. };
  27771. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  27772. this._playbackRate = newPlaybackRate;
  27773. if (this.isPlaying) {
  27774. this._soundSource.playbackRate.value = this._playbackRate;
  27775. }
  27776. };
  27777. Sound.prototype.getVolume = function () {
  27778. return this._volume;
  27779. };
  27780. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  27781. var _this = this;
  27782. this._connectedMesh = meshToConnectTo;
  27783. if (!this.spatialSound) {
  27784. this._createSpatialParameters();
  27785. this.spatialSound = true;
  27786. if (this.isPlaying && this.loop) {
  27787. this.stop();
  27788. this.play();
  27789. }
  27790. }
  27791. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  27792. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  27793. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  27794. };
  27795. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  27796. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  27797. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  27798. this._updateDirection();
  27799. }
  27800. };
  27801. return Sound;
  27802. })();
  27803. BABYLON.Sound = Sound;
  27804. })(BABYLON || (BABYLON = {}));
  27805. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  27806. (function (BABYLON) {
  27807. var SoundTrack = (function () {
  27808. function SoundTrack(scene, options) {
  27809. this.id = -1;
  27810. this._isMainTrack = false;
  27811. this._scene = scene;
  27812. this._audioEngine = BABYLON.Engine.audioEngine;
  27813. this.soundCollection = new Array();
  27814. if (this._audioEngine.canUseWebAudio) {
  27815. this._trackGain = this._audioEngine.audioContext.createGain();
  27816. this._trackGain.connect(this._audioEngine.masterGain);
  27817. if (options) {
  27818. if (options.volume) {
  27819. this._trackGain.gain.value = options.volume;
  27820. }
  27821. if (options.mainTrack) {
  27822. this._isMainTrack = options.mainTrack;
  27823. }
  27824. }
  27825. }
  27826. if (!this._isMainTrack) {
  27827. this._scene.soundTracks.push(this);
  27828. this.id = this._scene.soundTracks.length - 1;
  27829. }
  27830. }
  27831. SoundTrack.prototype.dispose = function () {
  27832. if (this._audioEngine.canUseWebAudio) {
  27833. if (this._connectedAnalyser) {
  27834. this._connectedAnalyser.stopDebugCanvas();
  27835. }
  27836. while (this.soundCollection.length) {
  27837. this.soundCollection[0].dispose();
  27838. }
  27839. this._trackGain.disconnect();
  27840. this._trackGain = null;
  27841. }
  27842. };
  27843. SoundTrack.prototype.AddSound = function (sound) {
  27844. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27845. sound.connectToSoundTrackAudioNode(this._trackGain);
  27846. }
  27847. if (sound.soundTrackId) {
  27848. if (sound.soundTrackId === -1) {
  27849. this._scene.mainSoundTrack.RemoveSound(sound);
  27850. }
  27851. else {
  27852. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  27853. }
  27854. }
  27855. this.soundCollection.push(sound);
  27856. sound.soundTrackId = this.id;
  27857. };
  27858. SoundTrack.prototype.RemoveSound = function (sound) {
  27859. var index = this.soundCollection.indexOf(sound);
  27860. if (index !== -1) {
  27861. this.soundCollection.splice(index, 1);
  27862. }
  27863. };
  27864. SoundTrack.prototype.setVolume = function (newVolume) {
  27865. if (this._audioEngine.canUseWebAudio) {
  27866. this._trackGain.gain.value = newVolume;
  27867. }
  27868. };
  27869. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  27870. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27871. for (var i = 0; i < this.soundCollection.length; i++) {
  27872. this.soundCollection[i].switchPanningModelToHRTF();
  27873. }
  27874. }
  27875. };
  27876. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  27877. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27878. for (var i = 0; i < this.soundCollection.length; i++) {
  27879. this.soundCollection[i].switchPanningModelToEqualPower();
  27880. }
  27881. }
  27882. };
  27883. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  27884. if (this._connectedAnalyser) {
  27885. this._connectedAnalyser.stopDebugCanvas();
  27886. }
  27887. this._connectedAnalyser = analyser;
  27888. if (this._audioEngine.canUseWebAudio) {
  27889. this._trackGain.disconnect();
  27890. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  27891. }
  27892. };
  27893. return SoundTrack;
  27894. })();
  27895. BABYLON.SoundTrack = SoundTrack;
  27896. })(BABYLON || (BABYLON = {}));
  27897. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  27898. (function (BABYLON) {
  27899. var DebugLayer = (function () {
  27900. function DebugLayer(scene) {
  27901. var _this = this;
  27902. this._transformationMatrix = BABYLON.Matrix.Identity();
  27903. this._enabled = false;
  27904. this._labelsEnabled = false;
  27905. this._displayStatistics = true;
  27906. this._displayTree = false;
  27907. this._displayLogs = false;
  27908. this._identityMatrix = BABYLON.Matrix.Identity();
  27909. this.axisRatio = 0.02;
  27910. this.accentColor = "orange";
  27911. this._scene = scene;
  27912. this._syncPositions = function () {
  27913. var engine = _this._scene.getEngine();
  27914. var canvasRect = engine.getRenderingCanvasClientRect();
  27915. if (_this._showUI) {
  27916. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  27917. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  27918. _this._statsDiv.style.width = "400px";
  27919. _this._statsDiv.style.height = "auto";
  27920. _this._statsSubsetDiv.style.maxHeight = "240px";
  27921. _this._optionsDiv.style.left = "0px";
  27922. _this._optionsDiv.style.top = "10px";
  27923. _this._optionsDiv.style.width = "200px";
  27924. _this._optionsDiv.style.height = "auto";
  27925. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  27926. _this._logDiv.style.left = "0px";
  27927. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  27928. _this._logDiv.style.width = "600px";
  27929. _this._logDiv.style.height = "160px";
  27930. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  27931. _this._treeDiv.style.top = "10px";
  27932. _this._treeDiv.style.width = "300px";
  27933. _this._treeDiv.style.height = "auto";
  27934. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  27935. }
  27936. _this._globalDiv.style.left = canvasRect.left + "px";
  27937. _this._globalDiv.style.top = canvasRect.top + "px";
  27938. _this._drawingCanvas.style.left = "0px";
  27939. _this._drawingCanvas.style.top = "0px";
  27940. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  27941. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  27942. var devicePixelRatio = window.devicePixelRatio || 1;
  27943. var context = _this._drawingContext;
  27944. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  27945. _this._ratio = devicePixelRatio / backingStoreRatio;
  27946. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  27947. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  27948. };
  27949. this._onCanvasClick = function (evt) {
  27950. _this._clickPosition = {
  27951. x: evt.clientX * _this._ratio,
  27952. y: evt.clientY * _this._ratio
  27953. };
  27954. };
  27955. this._syncUI = function () {
  27956. if (_this._showUI) {
  27957. if (_this._displayStatistics) {
  27958. _this._displayStats();
  27959. _this._statsDiv.style.display = "";
  27960. }
  27961. else {
  27962. _this._statsDiv.style.display = "none";
  27963. }
  27964. if (_this._displayLogs) {
  27965. _this._logDiv.style.display = "";
  27966. }
  27967. else {
  27968. _this._logDiv.style.display = "none";
  27969. }
  27970. if (_this._displayTree) {
  27971. _this._treeDiv.style.display = "";
  27972. if (_this._needToRefreshMeshesTree) {
  27973. _this._needToRefreshMeshesTree = false;
  27974. _this._refreshMeshesTreeContent();
  27975. }
  27976. }
  27977. else {
  27978. _this._treeDiv.style.display = "none";
  27979. }
  27980. }
  27981. };
  27982. this._syncData = function () {
  27983. if (_this._labelsEnabled || !_this._showUI) {
  27984. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  27985. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  27986. var engine = _this._scene.getEngine();
  27987. var viewport = _this._camera.viewport;
  27988. var globalViewport = viewport.toGlobal(engine);
  27989. // Meshes
  27990. var meshes = _this._camera.getActiveMeshes();
  27991. for (var index = 0; index < meshes.length; index++) {
  27992. var mesh = meshes.data[index];
  27993. var position = mesh.getBoundingInfo().boundingSphere.center;
  27994. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27995. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  27996. _this._renderAxis(projectedPosition, mesh, globalViewport);
  27997. }
  27998. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  27999. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  28000. mesh.renderOverlay = !mesh.renderOverlay;
  28001. }, function () {
  28002. return mesh.renderOverlay ? 'red' : 'black';
  28003. });
  28004. }
  28005. }
  28006. // Cameras
  28007. var cameras = _this._scene.cameras;
  28008. for (index = 0; index < cameras.length; index++) {
  28009. var camera = cameras[index];
  28010. if (camera === _this._camera) {
  28011. continue;
  28012. }
  28013. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  28014. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  28015. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  28016. _this._camera.detachControl(engine.getRenderingCanvas());
  28017. _this._camera = camera;
  28018. _this._camera.attachControl(engine.getRenderingCanvas());
  28019. }, function () {
  28020. return "purple";
  28021. });
  28022. }
  28023. }
  28024. // Lights
  28025. var lights = _this._scene.lights;
  28026. for (index = 0; index < lights.length; index++) {
  28027. var light = lights[index];
  28028. if (light.position) {
  28029. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  28030. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  28031. _this._renderLabel(light.name, projectedPosition, -20, function () {
  28032. light.setEnabled(!light.isEnabled());
  28033. }, function () {
  28034. return light.isEnabled() ? "orange" : "gray";
  28035. });
  28036. }
  28037. }
  28038. }
  28039. }
  28040. _this._clickPosition = undefined;
  28041. };
  28042. }
  28043. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  28044. while (this._treeSubsetDiv.hasChildNodes()) {
  28045. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  28046. }
  28047. // Add meshes
  28048. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  28049. sortedArray.sort(function (a, b) {
  28050. if (a.name === b.name) {
  28051. return 0;
  28052. }
  28053. return (a.name > b.name) ? 1 : -1;
  28054. });
  28055. for (var index = 0; index < sortedArray.length; index++) {
  28056. var mesh = sortedArray[index];
  28057. if (!mesh.isEnabled()) {
  28058. continue;
  28059. }
  28060. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  28061. m.isVisible = element.checked;
  28062. }, mesh);
  28063. }
  28064. };
  28065. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  28066. this._drawingContext.beginPath();
  28067. this._drawingContext.moveTo(zero.x, zero.y);
  28068. this._drawingContext.lineTo(unit.x, unit.y);
  28069. this._drawingContext.strokeStyle = color;
  28070. this._drawingContext.lineWidth = 4;
  28071. this._drawingContext.stroke();
  28072. this._drawingContext.font = "normal 14px Segoe UI";
  28073. this._drawingContext.fillStyle = color;
  28074. this._drawingContext.fillText(label, unitText.x, unitText.y);
  28075. };
  28076. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  28077. var position = mesh.getBoundingInfo().boundingSphere.center;
  28078. var worldMatrix = mesh.getWorldMatrix();
  28079. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  28080. var unit = (unprojectedVector.subtract(position)).length();
  28081. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28082. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28083. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  28084. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28085. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  28086. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  28087. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  28088. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  28089. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  28090. };
  28091. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  28092. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  28093. this._drawingContext.font = "normal 12px Segoe UI";
  28094. var textMetrics = this._drawingContext.measureText(text);
  28095. var centerX = projectedPosition.x - textMetrics.width / 2;
  28096. var centerY = projectedPosition.y;
  28097. var clientRect = this._drawingCanvas.getBoundingClientRect();
  28098. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  28099. onClick();
  28100. }
  28101. this._drawingContext.beginPath();
  28102. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  28103. this._drawingContext.fillStyle = getFillStyle();
  28104. this._drawingContext.globalAlpha = 0.5;
  28105. this._drawingContext.fill();
  28106. this._drawingContext.globalAlpha = 1.0;
  28107. this._drawingContext.strokeStyle = '#FFFFFF';
  28108. this._drawingContext.lineWidth = 1;
  28109. this._drawingContext.stroke();
  28110. this._drawingContext.fillStyle = "#FFFFFF";
  28111. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  28112. this._drawingContext.beginPath();
  28113. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  28114. this._drawingContext.fill();
  28115. }
  28116. };
  28117. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  28118. if (!this._clickPosition) {
  28119. return false;
  28120. }
  28121. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  28122. return false;
  28123. }
  28124. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  28125. return false;
  28126. }
  28127. return true;
  28128. };
  28129. DebugLayer.prototype.isVisible = function () {
  28130. return this._enabled;
  28131. };
  28132. DebugLayer.prototype.hide = function () {
  28133. if (!this._enabled) {
  28134. return;
  28135. }
  28136. this._enabled = false;
  28137. var engine = this._scene.getEngine();
  28138. this._scene.unregisterBeforeRender(this._syncData);
  28139. this._scene.unregisterAfterRender(this._syncUI);
  28140. document.body.removeChild(this._globalDiv);
  28141. window.removeEventListener("resize", this._syncPositions);
  28142. this._scene.forceShowBoundingBoxes = false;
  28143. this._scene.forceWireframe = false;
  28144. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  28145. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  28146. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  28147. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  28148. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  28149. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  28150. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  28151. this._scene.shadowsEnabled = true;
  28152. this._scene.particlesEnabled = true;
  28153. this._scene.postProcessesEnabled = true;
  28154. this._scene.collisionsEnabled = true;
  28155. this._scene.lightsEnabled = true;
  28156. this._scene.texturesEnabled = true;
  28157. this._scene.lensFlaresEnabled = true;
  28158. this._scene.proceduralTexturesEnabled = true;
  28159. this._scene.renderTargetsEnabled = true;
  28160. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  28161. };
  28162. DebugLayer.prototype.show = function (showUI, camera) {
  28163. if (showUI === void 0) { showUI = true; }
  28164. if (camera === void 0) { camera = null; }
  28165. if (this._enabled) {
  28166. return;
  28167. }
  28168. this._enabled = true;
  28169. if (camera) {
  28170. this._camera = camera;
  28171. }
  28172. else {
  28173. this._camera = this._scene.activeCamera;
  28174. }
  28175. this._showUI = showUI;
  28176. var engine = this._scene.getEngine();
  28177. this._globalDiv = document.createElement("div");
  28178. document.body.appendChild(this._globalDiv);
  28179. this._generateDOMelements();
  28180. window.addEventListener("resize", this._syncPositions);
  28181. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  28182. this._syncPositions();
  28183. this._scene.registerBeforeRender(this._syncData);
  28184. this._scene.registerAfterRender(this._syncUI);
  28185. };
  28186. DebugLayer.prototype._clearLabels = function () {
  28187. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  28188. for (var index = 0; index < this._scene.meshes.length; index++) {
  28189. var mesh = this._scene.meshes[index];
  28190. mesh.renderOverlay = false;
  28191. }
  28192. };
  28193. DebugLayer.prototype._generateheader = function (root, text) {
  28194. var header = document.createElement("div");
  28195. header.innerHTML = text + "&nbsp;";
  28196. header.style.textAlign = "right";
  28197. header.style.width = "100%";
  28198. header.style.color = "white";
  28199. header.style.backgroundColor = "Black";
  28200. header.style.padding = "5px 5px 4px 0px";
  28201. header.style.marginLeft = "-5px";
  28202. header.style.fontWeight = "bold";
  28203. root.appendChild(header);
  28204. };
  28205. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  28206. var label = document.createElement("label");
  28207. label.innerHTML = title;
  28208. label.style.color = color;
  28209. root.appendChild(label);
  28210. root.appendChild(document.createElement("br"));
  28211. };
  28212. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  28213. if (tag === void 0) { tag = null; }
  28214. var label = document.createElement("label");
  28215. var boundingBoxesCheckbox = document.createElement("input");
  28216. boundingBoxesCheckbox.type = "checkbox";
  28217. boundingBoxesCheckbox.checked = initialState;
  28218. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  28219. task(evt.target, tag);
  28220. });
  28221. label.appendChild(boundingBoxesCheckbox);
  28222. var container = document.createElement("span");
  28223. var leftPart = document.createElement("span");
  28224. var rightPart = document.createElement("span");
  28225. rightPart.style.cssFloat = "right";
  28226. leftPart.innerHTML = leftTitle;
  28227. rightPart.innerHTML = rightTitle;
  28228. rightPart.style.fontSize = "12px";
  28229. rightPart.style.maxWidth = "200px";
  28230. container.appendChild(leftPart);
  28231. container.appendChild(rightPart);
  28232. label.appendChild(container);
  28233. root.appendChild(label);
  28234. root.appendChild(document.createElement("br"));
  28235. };
  28236. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  28237. if (tag === void 0) { tag = null; }
  28238. var label = document.createElement("label");
  28239. var checkBox = document.createElement("input");
  28240. checkBox.type = "checkbox";
  28241. checkBox.checked = initialState;
  28242. checkBox.addEventListener("change", function (evt) {
  28243. task(evt.target, tag);
  28244. });
  28245. label.appendChild(checkBox);
  28246. label.appendChild(document.createTextNode(title));
  28247. root.appendChild(label);
  28248. root.appendChild(document.createElement("br"));
  28249. };
  28250. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  28251. if (tag === void 0) { tag = null; }
  28252. var button = document.createElement("button");
  28253. button.innerHTML = title;
  28254. button.style.height = "24px";
  28255. button.style.color = "#444444";
  28256. button.style.border = "1px solid white";
  28257. button.className = "debugLayerButton";
  28258. button.addEventListener("click", function (evt) {
  28259. task(evt.target, tag);
  28260. });
  28261. root.appendChild(button);
  28262. root.appendChild(document.createElement("br"));
  28263. };
  28264. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  28265. if (tag === void 0) { tag = null; }
  28266. var label = document.createElement("label");
  28267. var boundingBoxesRadio = document.createElement("input");
  28268. boundingBoxesRadio.type = "radio";
  28269. boundingBoxesRadio.name = name;
  28270. boundingBoxesRadio.checked = initialState;
  28271. boundingBoxesRadio.addEventListener("change", function (evt) {
  28272. task(evt.target, tag);
  28273. });
  28274. label.appendChild(boundingBoxesRadio);
  28275. label.appendChild(document.createTextNode(title));
  28276. root.appendChild(label);
  28277. root.appendChild(document.createElement("br"));
  28278. };
  28279. DebugLayer.prototype._generateDOMelements = function () {
  28280. var _this = this;
  28281. this._globalDiv.id = "DebugLayer";
  28282. this._globalDiv.style.position = "absolute";
  28283. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  28284. this._globalDiv.style.fontSize = "14px";
  28285. this._globalDiv.style.color = "white";
  28286. // Drawing canvas
  28287. this._drawingCanvas = document.createElement("canvas");
  28288. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  28289. this._drawingCanvas.style.position = "absolute";
  28290. this._drawingCanvas.style.pointerEvents = "none";
  28291. this._drawingContext = this._drawingCanvas.getContext("2d");
  28292. this._globalDiv.appendChild(this._drawingCanvas);
  28293. if (this._showUI) {
  28294. var background = "rgba(128, 128, 128, 0.4)";
  28295. var border = "rgb(180, 180, 180) solid 1px";
  28296. // Stats
  28297. this._statsDiv = document.createElement("div");
  28298. this._statsDiv.id = "DebugLayerStats";
  28299. this._statsDiv.style.border = border;
  28300. this._statsDiv.style.position = "absolute";
  28301. this._statsDiv.style.background = background;
  28302. this._statsDiv.style.padding = "0px 0px 0px 5px";
  28303. this._generateheader(this._statsDiv, "STATISTICS");
  28304. this._statsSubsetDiv = document.createElement("div");
  28305. this._statsSubsetDiv.style.paddingTop = "5px";
  28306. this._statsSubsetDiv.style.paddingBottom = "5px";
  28307. this._statsSubsetDiv.style.overflowY = "auto";
  28308. this._statsDiv.appendChild(this._statsSubsetDiv);
  28309. // Tree
  28310. this._treeDiv = document.createElement("div");
  28311. this._treeDiv.id = "DebugLayerTree";
  28312. this._treeDiv.style.border = border;
  28313. this._treeDiv.style.position = "absolute";
  28314. this._treeDiv.style.background = background;
  28315. this._treeDiv.style.padding = "0px 0px 0px 5px";
  28316. this._treeDiv.style.display = "none";
  28317. this._generateheader(this._treeDiv, "MESHES TREE");
  28318. this._treeSubsetDiv = document.createElement("div");
  28319. this._treeSubsetDiv.style.paddingTop = "5px";
  28320. this._treeSubsetDiv.style.paddingRight = "5px";
  28321. this._treeSubsetDiv.style.overflowY = "auto";
  28322. this._treeSubsetDiv.style.maxHeight = "300px";
  28323. this._treeDiv.appendChild(this._treeSubsetDiv);
  28324. this._needToRefreshMeshesTree = true;
  28325. // Logs
  28326. this._logDiv = document.createElement("div");
  28327. this._logDiv.style.border = border;
  28328. this._logDiv.id = "DebugLayerLogs";
  28329. this._logDiv.style.position = "absolute";
  28330. this._logDiv.style.background = background;
  28331. this._logDiv.style.padding = "0px 0px 0px 5px";
  28332. this._logDiv.style.display = "none";
  28333. this._generateheader(this._logDiv, "LOGS");
  28334. this._logSubsetDiv = document.createElement("div");
  28335. this._logSubsetDiv.style.height = "127px";
  28336. this._logSubsetDiv.style.paddingTop = "5px";
  28337. this._logSubsetDiv.style.overflowY = "auto";
  28338. this._logSubsetDiv.style.fontSize = "12px";
  28339. this._logSubsetDiv.style.fontFamily = "consolas";
  28340. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  28341. this._logDiv.appendChild(this._logSubsetDiv);
  28342. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  28343. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  28344. };
  28345. // Options
  28346. this._optionsDiv = document.createElement("div");
  28347. this._optionsDiv.id = "DebugLayerOptions";
  28348. this._optionsDiv.style.border = border;
  28349. this._optionsDiv.style.position = "absolute";
  28350. this._optionsDiv.style.background = background;
  28351. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  28352. this._optionsDiv.style.overflowY = "auto";
  28353. this._generateheader(this._optionsDiv, "OPTIONS");
  28354. this._optionsSubsetDiv = document.createElement("div");
  28355. this._optionsSubsetDiv.style.paddingTop = "5px";
  28356. this._optionsSubsetDiv.style.paddingBottom = "5px";
  28357. this._optionsSubsetDiv.style.overflowY = "auto";
  28358. this._optionsSubsetDiv.style.maxHeight = "200px";
  28359. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  28360. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  28361. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  28362. _this._displayStatistics = element.checked;
  28363. });
  28364. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  28365. _this._displayLogs = element.checked;
  28366. });
  28367. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  28368. _this._displayTree = element.checked;
  28369. _this._needToRefreshMeshesTree = true;
  28370. });
  28371. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28372. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  28373. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  28374. _this._scene.forceShowBoundingBoxes = element.checked;
  28375. });
  28376. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  28377. _this._labelsEnabled = element.checked;
  28378. if (!_this._labelsEnabled) {
  28379. _this._clearLabels();
  28380. }
  28381. });
  28382. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  28383. if (element.checked) {
  28384. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  28385. }
  28386. else {
  28387. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  28388. }
  28389. });
  28390. ;
  28391. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28392. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  28393. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  28394. if (element.checked) {
  28395. _this._scene.forceWireframe = false;
  28396. _this._scene.forcePointsCloud = false;
  28397. }
  28398. });
  28399. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  28400. if (element.checked) {
  28401. _this._scene.forceWireframe = true;
  28402. _this._scene.forcePointsCloud = false;
  28403. }
  28404. });
  28405. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  28406. if (element.checked) {
  28407. _this._scene.forceWireframe = false;
  28408. _this._scene.forcePointsCloud = true;
  28409. }
  28410. });
  28411. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28412. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  28413. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  28414. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  28415. });
  28416. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  28417. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  28418. });
  28419. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  28420. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  28421. });
  28422. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  28423. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  28424. });
  28425. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  28426. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  28427. });
  28428. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  28429. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  28430. });
  28431. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  28432. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  28433. });
  28434. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  28435. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  28436. });
  28437. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28438. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  28439. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  28440. _this._scene.animationsEnabled = element.checked;
  28441. });
  28442. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  28443. _this._scene.collisionsEnabled = element.checked;
  28444. });
  28445. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  28446. _this._scene.fogEnabled = element.checked;
  28447. });
  28448. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  28449. _this._scene.lensFlaresEnabled = element.checked;
  28450. });
  28451. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  28452. _this._scene.lightsEnabled = element.checked;
  28453. });
  28454. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  28455. _this._scene.particlesEnabled = element.checked;
  28456. });
  28457. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  28458. _this._scene.postProcessesEnabled = element.checked;
  28459. });
  28460. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  28461. _this._scene.proceduralTexturesEnabled = element.checked;
  28462. });
  28463. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  28464. _this._scene.renderTargetsEnabled = element.checked;
  28465. });
  28466. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  28467. _this._scene.shadowsEnabled = element.checked;
  28468. });
  28469. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  28470. _this._scene.skeletonsEnabled = element.checked;
  28471. });
  28472. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) {
  28473. _this._scene.spritesEnabled = element.checked;
  28474. });
  28475. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  28476. _this._scene.texturesEnabled = element.checked;
  28477. });
  28478. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28479. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28480. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  28481. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  28482. if (element.checked) {
  28483. _this._scene.headphone = true;
  28484. }
  28485. });
  28486. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  28487. if (element.checked) {
  28488. _this._scene.headphone = false;
  28489. }
  28490. });
  28491. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  28492. _this._scene.audioEnabled = !element.checked;
  28493. });
  28494. }
  28495. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28496. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  28497. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) {
  28498. _this._scene.dumpNextRenderTargets = true;
  28499. });
  28500. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28501. this._globalDiv.appendChild(this._statsDiv);
  28502. this._globalDiv.appendChild(this._logDiv);
  28503. this._globalDiv.appendChild(this._optionsDiv);
  28504. this._globalDiv.appendChild(this._treeDiv);
  28505. }
  28506. };
  28507. DebugLayer.prototype._displayStats = function () {
  28508. var scene = this._scene;
  28509. var engine = scene.getEngine();
  28510. var glInfo = engine.getGlInfo();
  28511. 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>";
  28512. if (this.customStatsFunction) {
  28513. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  28514. }
  28515. };
  28516. return DebugLayer;
  28517. })();
  28518. BABYLON.DebugLayer = DebugLayer;
  28519. })(BABYLON || (BABYLON = {}));
  28520. //# sourceMappingURL=babylon.debugLayer.js.map
  28521. var BABYLON;
  28522. (function (BABYLON) {
  28523. var RawTexture = (function (_super) {
  28524. __extends(RawTexture, _super);
  28525. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  28526. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28527. if (invertY === void 0) { invertY = false; }
  28528. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28529. _super.call(this, null, scene, !generateMipMaps, invertY);
  28530. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  28531. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28532. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28533. }
  28534. // Statics
  28535. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28536. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28537. if (invertY === void 0) { invertY = false; }
  28538. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28539. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  28540. };
  28541. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28542. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28543. if (invertY === void 0) { invertY = false; }
  28544. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28545. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  28546. };
  28547. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28548. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28549. if (invertY === void 0) { invertY = false; }
  28550. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28551. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  28552. };
  28553. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28554. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28555. if (invertY === void 0) { invertY = false; }
  28556. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28557. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  28558. };
  28559. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28560. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28561. if (invertY === void 0) { invertY = false; }
  28562. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28563. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  28564. };
  28565. return RawTexture;
  28566. })(BABYLON.Texture);
  28567. BABYLON.RawTexture = RawTexture;
  28568. })(BABYLON || (BABYLON = {}));
  28569. //# sourceMappingURL=babylon.rawTexture.js.map
  28570. var BABYLON;
  28571. (function (BABYLON) {
  28572. var IndexedVector2 = (function (_super) {
  28573. __extends(IndexedVector2, _super);
  28574. function IndexedVector2(original, index) {
  28575. _super.call(this, original.x, original.y);
  28576. this.index = index;
  28577. }
  28578. return IndexedVector2;
  28579. })(BABYLON.Vector2);
  28580. var PolygonPoints = (function () {
  28581. function PolygonPoints() {
  28582. this.elements = new Array();
  28583. }
  28584. PolygonPoints.prototype.add = function (originalPoints) {
  28585. var _this = this;
  28586. var result = new Array();
  28587. originalPoints.forEach(function (point) {
  28588. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  28589. var newPoint = new IndexedVector2(point, _this.elements.length);
  28590. result.push(newPoint);
  28591. _this.elements.push(newPoint);
  28592. }
  28593. });
  28594. return result;
  28595. };
  28596. PolygonPoints.prototype.computeBounds = function () {
  28597. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  28598. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  28599. this.elements.forEach(function (point) {
  28600. // x
  28601. if (point.x < lmin.x) {
  28602. lmin.x = point.x;
  28603. }
  28604. else if (point.x > lmax.x) {
  28605. lmax.x = point.x;
  28606. }
  28607. // y
  28608. if (point.y < lmin.y) {
  28609. lmin.y = point.y;
  28610. }
  28611. else if (point.y > lmax.y) {
  28612. lmax.y = point.y;
  28613. }
  28614. });
  28615. return {
  28616. min: lmin,
  28617. max: lmax,
  28618. width: lmax.x - lmin.x,
  28619. height: lmax.y - lmin.y
  28620. };
  28621. };
  28622. return PolygonPoints;
  28623. })();
  28624. var Polygon = (function () {
  28625. function Polygon() {
  28626. }
  28627. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  28628. return [
  28629. new BABYLON.Vector2(xmin, ymin),
  28630. new BABYLON.Vector2(xmax, ymin),
  28631. new BABYLON.Vector2(xmax, ymax),
  28632. new BABYLON.Vector2(xmin, ymax)
  28633. ];
  28634. };
  28635. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  28636. if (cx === void 0) { cx = 0; }
  28637. if (cy === void 0) { cy = 0; }
  28638. if (numberOfSides === void 0) { numberOfSides = 32; }
  28639. var result = new Array();
  28640. var angle = 0;
  28641. var increment = (Math.PI * 2) / numberOfSides;
  28642. for (var i = 0; i < numberOfSides; i++) {
  28643. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  28644. angle -= increment;
  28645. }
  28646. return result;
  28647. };
  28648. Polygon.Parse = function (input) {
  28649. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  28650. var i, result = [];
  28651. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  28652. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  28653. }
  28654. return result;
  28655. };
  28656. Polygon.StartingAt = function (x, y) {
  28657. return BABYLON.Path2.StartingAt(x, y);
  28658. };
  28659. return Polygon;
  28660. })();
  28661. BABYLON.Polygon = Polygon;
  28662. var PolygonMeshBuilder = (function () {
  28663. function PolygonMeshBuilder(name, contours, scene) {
  28664. this._points = new PolygonPoints();
  28665. if (!("poly2tri" in window)) {
  28666. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  28667. }
  28668. this._name = name;
  28669. this._scene = scene;
  28670. var points;
  28671. if (contours instanceof BABYLON.Path2) {
  28672. points = contours.getPoints();
  28673. }
  28674. else {
  28675. points = contours;
  28676. }
  28677. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  28678. }
  28679. PolygonMeshBuilder.prototype.addHole = function (hole) {
  28680. this._swctx.addHole(this._points.add(hole));
  28681. return this;
  28682. };
  28683. PolygonMeshBuilder.prototype.build = function (updatable) {
  28684. if (updatable === void 0) { updatable = false; }
  28685. var result = new BABYLON.Mesh(this._name, this._scene);
  28686. var normals = [];
  28687. var positions = [];
  28688. var uvs = [];
  28689. var bounds = this._points.computeBounds();
  28690. this._points.elements.forEach(function (p) {
  28691. normals.push(0, 1.0, 0);
  28692. positions.push(p.x, 0, p.y);
  28693. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  28694. });
  28695. var indices = [];
  28696. this._swctx.triangulate();
  28697. this._swctx.getTriangles().forEach(function (triangle) {
  28698. triangle.getPoints().forEach(function (point) {
  28699. indices.push(point.index);
  28700. });
  28701. });
  28702. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  28703. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  28704. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  28705. result.setIndices(indices);
  28706. return result;
  28707. };
  28708. return PolygonMeshBuilder;
  28709. })();
  28710. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  28711. })(BABYLON || (BABYLON = {}));
  28712. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  28713. (function (BABYLON) {
  28714. var SimplificationSettings = (function () {
  28715. function SimplificationSettings(quality, distance, optimizeMesh) {
  28716. this.quality = quality;
  28717. this.distance = distance;
  28718. this.optimizeMesh = optimizeMesh;
  28719. }
  28720. return SimplificationSettings;
  28721. })();
  28722. BABYLON.SimplificationSettings = SimplificationSettings;
  28723. var SimplificationQueue = (function () {
  28724. function SimplificationQueue() {
  28725. this.running = false;
  28726. this._simplificationArray = [];
  28727. }
  28728. SimplificationQueue.prototype.addTask = function (task) {
  28729. this._simplificationArray.push(task);
  28730. };
  28731. SimplificationQueue.prototype.executeNext = function () {
  28732. var task = this._simplificationArray.pop();
  28733. if (task) {
  28734. this.running = true;
  28735. this.runSimplification(task);
  28736. }
  28737. else {
  28738. this.running = false;
  28739. }
  28740. };
  28741. SimplificationQueue.prototype.runSimplification = function (task) {
  28742. var _this = this;
  28743. if (task.parallelProcessing) {
  28744. //parallel simplifier
  28745. task.settings.forEach(function (setting) {
  28746. var simplifier = _this.getSimplifier(task);
  28747. simplifier.simplify(setting, function (newMesh) {
  28748. task.mesh.addLODLevel(setting.distance, newMesh);
  28749. newMesh.isVisible = true;
  28750. //check if it is the last
  28751. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  28752. //all done, run the success callback.
  28753. task.successCallback();
  28754. }
  28755. _this.executeNext();
  28756. });
  28757. });
  28758. }
  28759. else {
  28760. //single simplifier.
  28761. var simplifier = this.getSimplifier(task);
  28762. var runDecimation = function (setting, callback) {
  28763. simplifier.simplify(setting, function (newMesh) {
  28764. task.mesh.addLODLevel(setting.distance, newMesh);
  28765. newMesh.isVisible = true;
  28766. //run the next quality level
  28767. callback();
  28768. });
  28769. };
  28770. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  28771. runDecimation(task.settings[loop.index], function () {
  28772. loop.executeNext();
  28773. });
  28774. }, function () {
  28775. //execution ended, run the success callback.
  28776. if (task.successCallback) {
  28777. task.successCallback();
  28778. }
  28779. _this.executeNext();
  28780. });
  28781. }
  28782. };
  28783. SimplificationQueue.prototype.getSimplifier = function (task) {
  28784. switch (task.simplificationType) {
  28785. case 0 /* QUADRATIC */:
  28786. default:
  28787. return new QuadraticErrorSimplification(task.mesh);
  28788. }
  28789. };
  28790. return SimplificationQueue;
  28791. })();
  28792. BABYLON.SimplificationQueue = SimplificationQueue;
  28793. /**
  28794. * The implemented types of simplification.
  28795. * At the moment only Quadratic Error Decimation is implemented.
  28796. */
  28797. (function (SimplificationType) {
  28798. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  28799. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  28800. var SimplificationType = BABYLON.SimplificationType;
  28801. var DecimationTriangle = (function () {
  28802. function DecimationTriangle(vertices) {
  28803. this.vertices = vertices;
  28804. this.error = new Array(4);
  28805. this.deleted = false;
  28806. this.isDirty = false;
  28807. this.deletePending = false;
  28808. this.borderFactor = 0;
  28809. }
  28810. return DecimationTriangle;
  28811. })();
  28812. BABYLON.DecimationTriangle = DecimationTriangle;
  28813. var DecimationVertex = (function () {
  28814. function DecimationVertex(position, id) {
  28815. this.position = position;
  28816. this.id = id;
  28817. this.isBorder = true;
  28818. this.q = new QuadraticMatrix();
  28819. this.triangleCount = 0;
  28820. this.triangleStart = 0;
  28821. this.originalOffsets = [];
  28822. }
  28823. DecimationVertex.prototype.updatePosition = function (newPosition) {
  28824. this.position.copyFrom(newPosition);
  28825. };
  28826. return DecimationVertex;
  28827. })();
  28828. BABYLON.DecimationVertex = DecimationVertex;
  28829. var QuadraticMatrix = (function () {
  28830. function QuadraticMatrix(data) {
  28831. this.data = new Array(10);
  28832. for (var i = 0; i < 10; ++i) {
  28833. if (data && data[i]) {
  28834. this.data[i] = data[i];
  28835. }
  28836. else {
  28837. this.data[i] = 0;
  28838. }
  28839. }
  28840. }
  28841. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  28842. 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];
  28843. return det;
  28844. };
  28845. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  28846. for (var i = 0; i < 10; ++i) {
  28847. this.data[i] += matrix.data[i];
  28848. }
  28849. };
  28850. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  28851. for (var i = 0; i < 10; ++i) {
  28852. this.data[i] += data[i];
  28853. }
  28854. };
  28855. QuadraticMatrix.prototype.add = function (matrix) {
  28856. var m = new QuadraticMatrix();
  28857. for (var i = 0; i < 10; ++i) {
  28858. m.data[i] = this.data[i] + matrix.data[i];
  28859. }
  28860. return m;
  28861. };
  28862. QuadraticMatrix.FromData = function (a, b, c, d) {
  28863. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  28864. };
  28865. //returning an array to avoid garbage collection
  28866. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  28867. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  28868. };
  28869. return QuadraticMatrix;
  28870. })();
  28871. BABYLON.QuadraticMatrix = QuadraticMatrix;
  28872. var Reference = (function () {
  28873. function Reference(vertexId, triangleId) {
  28874. this.vertexId = vertexId;
  28875. this.triangleId = triangleId;
  28876. }
  28877. return Reference;
  28878. })();
  28879. BABYLON.Reference = Reference;
  28880. /**
  28881. * An implementation of the Quadratic Error simplification algorithm.
  28882. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  28883. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  28884. * @author RaananW
  28885. */
  28886. var QuadraticErrorSimplification = (function () {
  28887. function QuadraticErrorSimplification(_mesh) {
  28888. this._mesh = _mesh;
  28889. this.initialized = false;
  28890. this.syncIterations = 5000;
  28891. this.aggressiveness = 7;
  28892. this.decimationIterations = 100;
  28893. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  28894. }
  28895. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  28896. var _this = this;
  28897. this.initDecimatedMesh();
  28898. //iterating through the submeshes array, one after the other.
  28899. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  28900. _this.initWithMesh(loop.index, function () {
  28901. _this.runDecimation(settings, loop.index, function () {
  28902. loop.executeNext();
  28903. });
  28904. }, settings.optimizeMesh);
  28905. }, function () {
  28906. setTimeout(function () {
  28907. successCallback(_this._reconstructedMesh);
  28908. }, 0);
  28909. });
  28910. };
  28911. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  28912. var _this = this;
  28913. var gCount = 0;
  28914. triangle.vertices.forEach(function (vertex) {
  28915. var count = 0;
  28916. var vPos = vertex.position;
  28917. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  28918. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  28919. ++count;
  28920. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  28921. ++count;
  28922. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  28923. ++count;
  28924. if (count > 1) {
  28925. ++gCount;
  28926. }
  28927. ;
  28928. });
  28929. if (gCount > 1) {
  28930. console.log(triangle, gCount);
  28931. }
  28932. return gCount > 1;
  28933. };
  28934. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  28935. var _this = this;
  28936. var targetCount = ~~(this.triangles.length * settings.quality);
  28937. var deletedTriangles = 0;
  28938. var triangleCount = this.triangles.length;
  28939. var iterationFunction = function (iteration, callback) {
  28940. setTimeout(function () {
  28941. if (iteration % 5 === 0) {
  28942. _this.updateMesh(iteration === 0);
  28943. }
  28944. for (var i = 0; i < _this.triangles.length; ++i) {
  28945. _this.triangles[i].isDirty = false;
  28946. }
  28947. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  28948. var trianglesIterator = function (i) {
  28949. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  28950. var t = _this.triangles[tIdx];
  28951. if (!t)
  28952. return;
  28953. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  28954. return;
  28955. }
  28956. for (var j = 0; j < 3; ++j) {
  28957. if (t.error[j] < threshold) {
  28958. var deleted0 = [];
  28959. var deleted1 = [];
  28960. var v0 = t.vertices[j];
  28961. var v1 = t.vertices[(j + 1) % 3];
  28962. if (v0.isBorder !== v1.isBorder)
  28963. continue;
  28964. var p = BABYLON.Vector3.Zero();
  28965. var n = BABYLON.Vector3.Zero();
  28966. var uv = BABYLON.Vector2.Zero();
  28967. var color = new BABYLON.Color4(0, 0, 0, 1);
  28968. _this.calculateError(v0, v1, p, n, uv, color);
  28969. var delTr = [];
  28970. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  28971. continue;
  28972. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  28973. continue;
  28974. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  28975. continue;
  28976. var uniqueArray = [];
  28977. delTr.forEach(function (deletedT) {
  28978. if (uniqueArray.indexOf(deletedT) === -1) {
  28979. deletedT.deletePending = true;
  28980. uniqueArray.push(deletedT);
  28981. }
  28982. });
  28983. if (uniqueArray.length % 2 != 0) {
  28984. continue;
  28985. }
  28986. v0.q = v1.q.add(v0.q);
  28987. v0.updatePosition(p);
  28988. var tStart = _this.references.length;
  28989. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  28990. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  28991. var tCount = _this.references.length - tStart;
  28992. if (tCount <= v0.triangleCount) {
  28993. if (tCount) {
  28994. for (var c = 0; c < tCount; c++) {
  28995. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  28996. }
  28997. }
  28998. }
  28999. else {
  29000. v0.triangleStart = tStart;
  29001. }
  29002. v0.triangleCount = tCount;
  29003. break;
  29004. }
  29005. }
  29006. };
  29007. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  29008. return (triangleCount - deletedTriangles <= targetCount);
  29009. });
  29010. }, 0);
  29011. };
  29012. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  29013. if (triangleCount - deletedTriangles <= targetCount)
  29014. loop.breakLoop();
  29015. else {
  29016. iterationFunction(loop.index, function () {
  29017. loop.executeNext();
  29018. });
  29019. }
  29020. }, function () {
  29021. setTimeout(function () {
  29022. //reconstruct this part of the mesh
  29023. _this.reconstructMesh(submeshIndex);
  29024. successCallback();
  29025. }, 0);
  29026. });
  29027. };
  29028. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  29029. var _this = this;
  29030. this.vertices = [];
  29031. this.triangles = [];
  29032. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29033. var indices = this._mesh.getIndices();
  29034. var submesh = this._mesh.subMeshes[submeshIndex];
  29035. var findInVertices = function (positionToSearch) {
  29036. if (optimizeMesh) {
  29037. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  29038. if (_this.vertices[ii].position.equals(positionToSearch)) {
  29039. return _this.vertices[ii];
  29040. }
  29041. }
  29042. }
  29043. return null;
  29044. };
  29045. var vertexReferences = [];
  29046. var vertexInit = function (i) {
  29047. var offset = i + submesh.verticesStart;
  29048. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  29049. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  29050. vertex.originalOffsets.push(offset);
  29051. if (vertex.id == _this.vertices.length) {
  29052. _this.vertices.push(vertex);
  29053. }
  29054. vertexReferences.push(vertex.id);
  29055. };
  29056. //var totalVertices = mesh.getTotalVertices();
  29057. var totalVertices = submesh.verticesCount;
  29058. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  29059. var indicesInit = function (i) {
  29060. var offset = (submesh.indexStart / 3) + i;
  29061. var pos = (offset * 3);
  29062. var i0 = indices[pos + 0];
  29063. var i1 = indices[pos + 1];
  29064. var i2 = indices[pos + 2];
  29065. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  29066. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  29067. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  29068. var triangle = new DecimationTriangle([v0, v1, v2]);
  29069. triangle.originalOffset = pos;
  29070. _this.triangles.push(triangle);
  29071. };
  29072. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  29073. _this.init(callback);
  29074. });
  29075. });
  29076. };
  29077. QuadraticErrorSimplification.prototype.init = function (callback) {
  29078. var _this = this;
  29079. var triangleInit1 = function (i) {
  29080. var t = _this.triangles[i];
  29081. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  29082. for (var j = 0; j < 3; j++) {
  29083. t.vertices[j].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, t.vertices[0].position))));
  29084. }
  29085. };
  29086. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  29087. var triangleInit2 = function (i) {
  29088. var t = _this.triangles[i];
  29089. for (var j = 0; j < 3; ++j) {
  29090. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  29091. }
  29092. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29093. };
  29094. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  29095. _this.initialized = true;
  29096. callback();
  29097. });
  29098. });
  29099. };
  29100. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  29101. var newTriangles = [];
  29102. var i;
  29103. for (i = 0; i < this.vertices.length; ++i) {
  29104. this.vertices[i].triangleCount = 0;
  29105. }
  29106. var t;
  29107. var j;
  29108. for (i = 0; i < this.triangles.length; ++i) {
  29109. if (!this.triangles[i].deleted) {
  29110. t = this.triangles[i];
  29111. for (j = 0; j < 3; ++j) {
  29112. t.vertices[j].triangleCount = 1;
  29113. }
  29114. newTriangles.push(t);
  29115. }
  29116. }
  29117. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  29118. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  29119. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  29120. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  29121. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29122. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29123. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  29124. var vertexCount = 0;
  29125. for (i = 0; i < this.vertices.length; ++i) {
  29126. var vertex = this.vertices[i];
  29127. vertex.id = vertexCount;
  29128. if (vertex.triangleCount) {
  29129. vertex.originalOffsets.forEach(function (originalOffset) {
  29130. newPositionData.push(vertex.position.x);
  29131. newPositionData.push(vertex.position.y);
  29132. newPositionData.push(vertex.position.z);
  29133. newNormalData.push(normalData[originalOffset * 3]);
  29134. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  29135. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  29136. if (uvs && uvs.length) {
  29137. newUVsData.push(uvs[(originalOffset * 2)]);
  29138. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  29139. }
  29140. else if (colorsData && colorsData.length) {
  29141. newColorsData.push(colorsData[(originalOffset * 4)]);
  29142. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  29143. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  29144. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  29145. }
  29146. ++vertexCount;
  29147. });
  29148. }
  29149. }
  29150. var startingIndex = this._reconstructedMesh.getTotalIndices();
  29151. var startingVertex = this._reconstructedMesh.getTotalVertices();
  29152. var submeshesArray = this._reconstructedMesh.subMeshes;
  29153. this._reconstructedMesh.subMeshes = [];
  29154. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  29155. var originalIndices = this._mesh.getIndices();
  29156. for (i = 0; i < newTriangles.length; ++i) {
  29157. var t = newTriangles[i];
  29158. //now get the new referencing point for each vertex
  29159. [0, 1, 2].forEach(function (idx) {
  29160. var id = originalIndices[t.originalOffset + idx];
  29161. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  29162. if (offset < 0)
  29163. offset = 0;
  29164. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  29165. });
  29166. }
  29167. //overwriting the old vertex buffers and indices.
  29168. this._reconstructedMesh.setIndices(newIndicesArray);
  29169. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  29170. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  29171. if (newUVsData.length > 0)
  29172. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  29173. if (newColorsData.length > 0)
  29174. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  29175. //create submesh
  29176. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  29177. if (submeshIndex > 0) {
  29178. this._reconstructedMesh.subMeshes = [];
  29179. submeshesArray.forEach(function (submesh) {
  29180. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  29181. });
  29182. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  29183. }
  29184. };
  29185. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  29186. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  29187. this._reconstructedMesh.material = this._mesh.material;
  29188. this._reconstructedMesh.parent = this._mesh.parent;
  29189. this._reconstructedMesh.isVisible = false;
  29190. };
  29191. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  29192. for (var i = 0; i < vertex1.triangleCount; ++i) {
  29193. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  29194. if (t.deleted)
  29195. continue;
  29196. var s = this.references[vertex1.triangleStart + i].vertexId;
  29197. var v1 = t.vertices[(s + 1) % 3];
  29198. var v2 = t.vertices[(s + 2) % 3];
  29199. if ((v1 === vertex2 || v2 === vertex2)) {
  29200. deletedArray[i] = true;
  29201. delTr.push(t);
  29202. continue;
  29203. }
  29204. var d1 = v1.position.subtract(point);
  29205. d1 = d1.normalize();
  29206. var d2 = v2.position.subtract(point);
  29207. d2 = d2.normalize();
  29208. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  29209. return true;
  29210. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  29211. deletedArray[i] = false;
  29212. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  29213. return true;
  29214. }
  29215. return false;
  29216. };
  29217. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  29218. var newDeleted = deletedTriangles;
  29219. for (var i = 0; i < vertex.triangleCount; ++i) {
  29220. var ref = this.references[vertex.triangleStart + i];
  29221. var t = this.triangles[ref.triangleId];
  29222. if (t.deleted)
  29223. continue;
  29224. if (deletedArray[i] && t.deletePending) {
  29225. t.deleted = true;
  29226. newDeleted++;
  29227. continue;
  29228. }
  29229. t.vertices[ref.vertexId] = origVertex;
  29230. t.isDirty = true;
  29231. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  29232. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  29233. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  29234. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29235. this.references.push(ref);
  29236. }
  29237. return newDeleted;
  29238. };
  29239. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  29240. for (var i = 0; i < this.vertices.length; ++i) {
  29241. var vCount = [];
  29242. var vId = [];
  29243. var v = this.vertices[i];
  29244. var j;
  29245. for (j = 0; j < v.triangleCount; ++j) {
  29246. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  29247. for (var ii = 0; ii < 3; ii++) {
  29248. var ofs = 0;
  29249. var vv = triangle.vertices[ii];
  29250. while (ofs < vCount.length) {
  29251. if (vId[ofs] === vv.id)
  29252. break;
  29253. ++ofs;
  29254. }
  29255. if (ofs === vCount.length) {
  29256. vCount.push(1);
  29257. vId.push(vv.id);
  29258. }
  29259. else {
  29260. vCount[ofs]++;
  29261. }
  29262. }
  29263. }
  29264. for (j = 0; j < vCount.length; ++j) {
  29265. if (vCount[j] === 1) {
  29266. this.vertices[vId[j]].isBorder = true;
  29267. }
  29268. else {
  29269. this.vertices[vId[j]].isBorder = false;
  29270. }
  29271. }
  29272. }
  29273. };
  29274. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  29275. if (identifyBorders === void 0) { identifyBorders = false; }
  29276. var i;
  29277. if (!identifyBorders) {
  29278. var newTrianglesVector = [];
  29279. for (i = 0; i < this.triangles.length; ++i) {
  29280. if (!this.triangles[i].deleted) {
  29281. newTrianglesVector.push(this.triangles[i]);
  29282. }
  29283. }
  29284. this.triangles = newTrianglesVector;
  29285. }
  29286. for (i = 0; i < this.vertices.length; ++i) {
  29287. this.vertices[i].triangleCount = 0;
  29288. this.vertices[i].triangleStart = 0;
  29289. }
  29290. var t;
  29291. var j;
  29292. var v;
  29293. for (i = 0; i < this.triangles.length; ++i) {
  29294. t = this.triangles[i];
  29295. for (j = 0; j < 3; ++j) {
  29296. v = t.vertices[j];
  29297. v.triangleCount++;
  29298. }
  29299. }
  29300. var tStart = 0;
  29301. for (i = 0; i < this.vertices.length; ++i) {
  29302. this.vertices[i].triangleStart = tStart;
  29303. tStart += this.vertices[i].triangleCount;
  29304. this.vertices[i].triangleCount = 0;
  29305. }
  29306. var newReferences = new Array(this.triangles.length * 3);
  29307. for (i = 0; i < this.triangles.length; ++i) {
  29308. t = this.triangles[i];
  29309. for (j = 0; j < 3; ++j) {
  29310. v = t.vertices[j];
  29311. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  29312. v.triangleCount++;
  29313. }
  29314. }
  29315. this.references = newReferences;
  29316. if (identifyBorders) {
  29317. this.identifyBorder();
  29318. }
  29319. };
  29320. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  29321. var x = point.x;
  29322. var y = point.y;
  29323. var z = point.z;
  29324. 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];
  29325. };
  29326. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  29327. var q = vertex1.q.add(vertex2.q);
  29328. var border = vertex1.isBorder && vertex2.isBorder;
  29329. var error = 0;
  29330. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  29331. if (qDet !== 0 && !border) {
  29332. if (!pointResult) {
  29333. pointResult = BABYLON.Vector3.Zero();
  29334. }
  29335. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  29336. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  29337. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  29338. error = this.vertexError(q, pointResult);
  29339. }
  29340. else {
  29341. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  29342. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  29343. var error1 = this.vertexError(q, vertex1.position);
  29344. var error2 = this.vertexError(q, vertex2.position);
  29345. var error3 = this.vertexError(q, p3);
  29346. error = Math.min(error1, error2, error3);
  29347. if (error === error1) {
  29348. if (pointResult) {
  29349. pointResult.copyFrom(vertex1.position);
  29350. }
  29351. }
  29352. else if (error === error2) {
  29353. if (pointResult) {
  29354. pointResult.copyFrom(vertex2.position);
  29355. }
  29356. }
  29357. else {
  29358. if (pointResult) {
  29359. pointResult.copyFrom(p3);
  29360. }
  29361. }
  29362. }
  29363. return error;
  29364. };
  29365. return QuadraticErrorSimplification;
  29366. })();
  29367. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  29368. })(BABYLON || (BABYLON = {}));
  29369. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  29370. (function (BABYLON) {
  29371. var Analyser = (function () {
  29372. function Analyser(scene) {
  29373. this.SMOOTHING = 0.75;
  29374. this.FFT_SIZE = 512;
  29375. this.BARGRAPHAMPLITUDE = 256;
  29376. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  29377. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  29378. this._scene = scene;
  29379. this._audioEngine = BABYLON.Engine.audioEngine;
  29380. if (this._audioEngine.canUseWebAudio) {
  29381. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  29382. this._webAudioAnalyser.minDecibels = -140;
  29383. this._webAudioAnalyser.maxDecibels = 0;
  29384. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  29385. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  29386. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  29387. }
  29388. }
  29389. Analyser.prototype.getFrequencyBinCount = function () {
  29390. if (this._audioEngine.canUseWebAudio) {
  29391. return this._webAudioAnalyser.frequencyBinCount;
  29392. }
  29393. else {
  29394. return 0;
  29395. }
  29396. };
  29397. Analyser.prototype.getByteFrequencyData = function () {
  29398. if (this._audioEngine.canUseWebAudio) {
  29399. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  29400. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  29401. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  29402. }
  29403. return this._byteFreqs;
  29404. };
  29405. Analyser.prototype.getByteTimeDomainData = function () {
  29406. if (this._audioEngine.canUseWebAudio) {
  29407. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  29408. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  29409. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  29410. }
  29411. return this._byteTime;
  29412. };
  29413. Analyser.prototype.getFloatFrequencyData = function () {
  29414. if (this._audioEngine.canUseWebAudio) {
  29415. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  29416. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  29417. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  29418. }
  29419. return this._floatFreqs;
  29420. };
  29421. Analyser.prototype.drawDebugCanvas = function () {
  29422. var _this = this;
  29423. if (this._audioEngine.canUseWebAudio) {
  29424. if (!this._debugCanvas) {
  29425. this._debugCanvas = document.createElement("canvas");
  29426. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  29427. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  29428. this._debugCanvas.style.position = "absolute";
  29429. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  29430. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  29431. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  29432. document.body.appendChild(this._debugCanvas);
  29433. this._registerFunc = function () {
  29434. _this.drawDebugCanvas();
  29435. };
  29436. this._scene.registerBeforeRender(this._registerFunc);
  29437. }
  29438. if (this._registerFunc) {
  29439. var workingArray = this.getByteFrequencyData();
  29440. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  29441. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  29442. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  29443. var value = workingArray[i];
  29444. var percent = value / this.BARGRAPHAMPLITUDE;
  29445. var height = this.DEBUGCANVASSIZE.height * percent;
  29446. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  29447. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  29448. var hue = i / this.getFrequencyBinCount() * 360;
  29449. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  29450. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  29451. }
  29452. }
  29453. }
  29454. };
  29455. Analyser.prototype.stopDebugCanvas = function () {
  29456. if (this._debugCanvas) {
  29457. this._scene.unregisterBeforeRender(this._registerFunc);
  29458. this._registerFunc = null;
  29459. document.body.removeChild(this._debugCanvas);
  29460. this._debugCanvas = null;
  29461. this._debugCanvasContext = null;
  29462. }
  29463. };
  29464. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  29465. if (this._audioEngine.canUseWebAudio) {
  29466. inputAudioNode.connect(this._webAudioAnalyser);
  29467. this._webAudioAnalyser.connect(outputAudioNode);
  29468. }
  29469. };
  29470. Analyser.prototype.dispose = function () {
  29471. if (this._audioEngine.canUseWebAudio) {
  29472. this._webAudioAnalyser.disconnect();
  29473. }
  29474. };
  29475. return Analyser;
  29476. })();
  29477. BABYLON.Analyser = Analyser;
  29478. })(BABYLON || (BABYLON = {}));
  29479. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  29480. (function (BABYLON) {
  29481. var DepthRenderer = (function () {
  29482. function DepthRenderer(scene, type) {
  29483. var _this = this;
  29484. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  29485. this._viewMatrix = BABYLON.Matrix.Zero();
  29486. this._projectionMatrix = BABYLON.Matrix.Zero();
  29487. this._transformMatrix = BABYLON.Matrix.Zero();
  29488. this._worldViewProjection = BABYLON.Matrix.Zero();
  29489. this._scene = scene;
  29490. var engine = scene.getEngine();
  29491. // Render target
  29492. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  29493. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29494. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29495. this._depthMap.refreshRate = 1;
  29496. this._depthMap.renderParticles = false;
  29497. this._depthMap.renderList = null;
  29498. // Custom render function
  29499. var renderSubMesh = function (subMesh) {
  29500. var mesh = subMesh.getRenderingMesh();
  29501. var scene = _this._scene;
  29502. var engine = scene.getEngine();
  29503. // Culling
  29504. engine.setState(subMesh.getMaterial().backFaceCulling);
  29505. // Managing instances
  29506. var batch = mesh._getInstancesRenderList(subMesh._id);
  29507. if (batch.mustReturn) {
  29508. return;
  29509. }
  29510. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  29511. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  29512. engine.enableEffect(_this._effect);
  29513. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  29514. var material = subMesh.getMaterial();
  29515. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  29516. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  29517. // Alpha test
  29518. if (material && material.needAlphaTesting()) {
  29519. var alphaTexture = material.getAlphaTestTexture();
  29520. _this._effect.setTexture("diffuseSampler", alphaTexture);
  29521. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29522. }
  29523. // Bones
  29524. if (mesh.useBones) {
  29525. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29526. }
  29527. // Draw
  29528. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  29529. }
  29530. };
  29531. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  29532. var index;
  29533. for (index = 0; index < opaqueSubMeshes.length; index++) {
  29534. renderSubMesh(opaqueSubMeshes.data[index]);
  29535. }
  29536. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  29537. renderSubMesh(alphaTestSubMeshes.data[index]);
  29538. }
  29539. };
  29540. }
  29541. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  29542. var defines = [];
  29543. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29544. var mesh = subMesh.getMesh();
  29545. var scene = mesh.getScene();
  29546. var material = subMesh.getMaterial();
  29547. // Alpha test
  29548. if (material && material.needAlphaTesting()) {
  29549. defines.push("#define ALPHATEST");
  29550. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29551. attribs.push(BABYLON.VertexBuffer.UVKind);
  29552. defines.push("#define UV1");
  29553. }
  29554. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29555. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29556. defines.push("#define UV2");
  29557. }
  29558. }
  29559. // Bones
  29560. if (mesh.useBones) {
  29561. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29562. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29563. defines.push("#define BONES");
  29564. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29565. }
  29566. // Instances
  29567. if (useInstances) {
  29568. defines.push("#define INSTANCES");
  29569. attribs.push("world0");
  29570. attribs.push("world1");
  29571. attribs.push("world2");
  29572. attribs.push("world3");
  29573. }
  29574. // Get correct effect
  29575. var join = defines.join("\n");
  29576. if (this._cachedDefines !== join) {
  29577. this._cachedDefines = join;
  29578. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  29579. }
  29580. return this._effect.isReady();
  29581. };
  29582. DepthRenderer.prototype.getDepthMap = function () {
  29583. return this._depthMap;
  29584. };
  29585. // Methods
  29586. DepthRenderer.prototype.dispose = function () {
  29587. this._depthMap.dispose();
  29588. };
  29589. return DepthRenderer;
  29590. })();
  29591. BABYLON.DepthRenderer = DepthRenderer;
  29592. })(BABYLON || (BABYLON = {}));
  29593. //# sourceMappingURL=babylon.depthRenderer.js.map
  29594. var BABYLON;
  29595. (function (BABYLON) {
  29596. var SSAORenderingPipeline = (function (_super) {
  29597. __extends(SSAORenderingPipeline, _super);
  29598. /**
  29599. * @constructor
  29600. * @param {string} name - The rendering pipeline name
  29601. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  29602. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, combineRatio: 1.0 }
  29603. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  29604. */
  29605. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  29606. var _this = this;
  29607. _super.call(this, scene.getEngine(), name);
  29608. // Members
  29609. /**
  29610. * The PassPostProcess id in the pipeline that contains the original scene color
  29611. * @type {string}
  29612. */
  29613. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  29614. /**
  29615. * The SSAO PostProcess id in the pipeline
  29616. * @type {string}
  29617. */
  29618. this.SSAORenderEffect = "SSAORenderEffect";
  29619. /**
  29620. * The horizontal blur PostProcess id in the pipeline
  29621. * @type {string}
  29622. */
  29623. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  29624. /**
  29625. * The vertical blur PostProcess id in the pipeline
  29626. * @type {string}
  29627. */
  29628. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  29629. /**
  29630. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  29631. * @type {string}
  29632. */
  29633. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  29634. /**
  29635. * The output strength of the SSAO post-process. Default value is 1.0.
  29636. * @type {number}
  29637. */
  29638. this.totalStrength = 1.0;
  29639. /**
  29640. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  29641. * @type {number}
  29642. */
  29643. this.radius = 0.0002;
  29644. /**
  29645. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  29646. * Must not be equal to fallOff and superior to fallOff.
  29647. * Default value is 0.0075
  29648. * @type {number}
  29649. */
  29650. this.area = 0.0075;
  29651. /**
  29652. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  29653. * Must not be equal to area and inferior to area.
  29654. * Default value is 0.0002
  29655. * @type {number}
  29656. */
  29657. this.fallOff = 0.0002;
  29658. this._firstUpdate = true;
  29659. this._scene = scene;
  29660. // Set up assets
  29661. this._createRandomTexture();
  29662. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  29663. var ssaoRatio = ratio.ssaoRatio || ratio;
  29664. var combineRatio = ratio.combineRatio || ratio;
  29665. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29666. this._createSSAOPostProcess(ssaoRatio);
  29667. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29668. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29669. this._createSSAOCombinePostProcess(combineRatio);
  29670. // Set up pipeline
  29671. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  29672. return _this._originalColorPostProcess;
  29673. }, true));
  29674. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  29675. return _this._ssaoPostProcess;
  29676. }, true));
  29677. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  29678. return _this._blurHPostProcess;
  29679. }, true));
  29680. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  29681. return _this._blurVPostProcess;
  29682. }, true));
  29683. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  29684. return _this._ssaoCombinePostProcess;
  29685. }, true));
  29686. // Finish
  29687. scene.postProcessRenderPipelineManager.addPipeline(this);
  29688. if (cameras)
  29689. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  29690. }
  29691. // Public Methods
  29692. /**
  29693. * Returns the horizontal blur PostProcess
  29694. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  29695. */
  29696. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  29697. return this._blurHPostProcess;
  29698. };
  29699. /**
  29700. * Returns the vertical blur PostProcess
  29701. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  29702. */
  29703. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  29704. return this._blurVPostProcess;
  29705. };
  29706. /**
  29707. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  29708. */
  29709. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  29710. if (disableDepthRender === void 0) { disableDepthRender = false; }
  29711. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  29712. this._originalColorPostProcess = undefined;
  29713. this._ssaoPostProcess = undefined;
  29714. this._blurHPostProcess = undefined;
  29715. this._blurVPostProcess = undefined;
  29716. this._ssaoCombinePostProcess = undefined;
  29717. this._randomTexture.dispose();
  29718. if (disableDepthRender)
  29719. this._scene.disableDepthRenderer();
  29720. };
  29721. // Private Methods
  29722. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  29723. var _this = this;
  29724. var sampleSphere = [
  29725. 0.5381,
  29726. 0.1856,
  29727. -0.4319,
  29728. 0.1379,
  29729. 0.2486,
  29730. 0.4430,
  29731. 0.3371,
  29732. 0.5679,
  29733. -0.0057,
  29734. -0.6999,
  29735. -0.0451,
  29736. -0.0019,
  29737. 0.0689,
  29738. -0.1598,
  29739. -0.8547,
  29740. 0.0560,
  29741. 0.0069,
  29742. -0.1843,
  29743. -0.0146,
  29744. 0.1402,
  29745. 0.0762,
  29746. 0.0100,
  29747. -0.1924,
  29748. -0.0344,
  29749. -0.3577,
  29750. -0.5301,
  29751. -0.4358,
  29752. -0.3169,
  29753. 0.1063,
  29754. 0.0158,
  29755. 0.0103,
  29756. -0.5869,
  29757. 0.0046,
  29758. -0.0897,
  29759. -0.4940,
  29760. 0.3287,
  29761. 0.7119,
  29762. -0.0154,
  29763. -0.0918,
  29764. -0.0533,
  29765. 0.0596,
  29766. -0.5411,
  29767. 0.0352,
  29768. -0.0631,
  29769. 0.5460,
  29770. -0.4776,
  29771. 0.2847,
  29772. -0.0271
  29773. ];
  29774. var samplesFactor = 1.0 / 16.0;
  29775. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius", "area", "fallOff"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29776. this._ssaoPostProcess.onApply = function (effect) {
  29777. if (_this._firstUpdate) {
  29778. effect.setArray3("sampleSphere", sampleSphere);
  29779. effect.setFloat("samplesFactor", samplesFactor);
  29780. effect.setFloat("randTextureTiles", 4.0 / ratio);
  29781. _this._firstUpdate = false;
  29782. }
  29783. effect.setFloat("totalStrength", _this.totalStrength);
  29784. effect.setFloat("radius", _this.radius);
  29785. effect.setFloat("area", _this.area);
  29786. effect.setFloat("fallOff", _this.fallOff);
  29787. effect.setTexture("textureSampler", _this._depthTexture);
  29788. effect.setTexture("randomSampler", _this._randomTexture);
  29789. };
  29790. };
  29791. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  29792. var _this = this;
  29793. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29794. this._ssaoCombinePostProcess.onApply = function (effect) {
  29795. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  29796. };
  29797. };
  29798. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  29799. var size = 512;
  29800. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  29801. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29802. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29803. var context = this._randomTexture.getContext();
  29804. var rand = function (min, max) {
  29805. return Math.random() * (max - min) + min;
  29806. };
  29807. for (var x = 0; x < size; x++) {
  29808. for (var y = 0; y < size; y++) {
  29809. var randVector = BABYLON.Vector3.Zero();
  29810. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  29811. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  29812. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  29813. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  29814. context.fillRect(x, y, 1, 1);
  29815. }
  29816. }
  29817. this._randomTexture.update(false);
  29818. };
  29819. return SSAORenderingPipeline;
  29820. })(BABYLON.PostProcessRenderPipeline);
  29821. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  29822. })(BABYLON || (BABYLON = {}));
  29823. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  29824. var BABYLON;
  29825. (function (BABYLON) {
  29826. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  29827. var VolumetricLightScatteringPostProcess = (function (_super) {
  29828. __extends(VolumetricLightScatteringPostProcess, _super);
  29829. /**
  29830. * @constructor
  29831. * @param {string} name - The post-process name
  29832. * @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)
  29833. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  29834. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  29835. * @param {number} samples - The post-process quality, default 100
  29836. * @param {number} samplingMode - The post-process filtering mode
  29837. * @param {BABYLON.Engine} engine - The babylon engine
  29838. * @param {boolean} reusable - If the post-process is reusable
  29839. */
  29840. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  29841. var _this = this;
  29842. if (samples === void 0) { samples = 100; }
  29843. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  29844. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  29845. this._screenCoordinates = BABYLON.Vector2.Zero();
  29846. /**
  29847. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  29848. * @type {boolean}
  29849. */
  29850. this.useCustomMeshPosition = false;
  29851. /**
  29852. * If the post-process should inverse the light scattering direction
  29853. * @type {boolean}
  29854. */
  29855. this.invert = true;
  29856. /**
  29857. * Array containing the excluded meshes not rendered in the internal pass
  29858. */
  29859. this.excludedMeshes = new Array();
  29860. this.exposure = 0.3;
  29861. this.decay = 0.96815;
  29862. this.weight = 0.58767;
  29863. this.density = 0.926;
  29864. var scene = camera.getScene();
  29865. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  29866. // Configure mesh
  29867. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  29868. // Configure
  29869. this._createPass(scene, ratio.passRatio || ratio);
  29870. this.onApply = function (effect) {
  29871. _this._updateMeshScreenCoordinates(scene);
  29872. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  29873. effect.setFloat("exposure", _this.exposure);
  29874. effect.setFloat("decay", _this.decay);
  29875. effect.setFloat("weight", _this.weight);
  29876. effect.setFloat("density", _this.density);
  29877. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  29878. };
  29879. }
  29880. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  29881. var mesh = subMesh.getMesh();
  29882. var defines = [];
  29883. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29884. var material = subMesh.getMaterial();
  29885. var needUV = false;
  29886. // Render this.mesh as default
  29887. if (mesh === this.mesh) {
  29888. defines.push("#define BASIC_RENDER");
  29889. defines.push("#define NEED_UV");
  29890. needUV = true;
  29891. }
  29892. // Alpha test
  29893. if (material) {
  29894. if (material.needAlphaTesting() || mesh === this.mesh)
  29895. defines.push("#define ALPHATEST");
  29896. if (material.opacityTexture !== undefined) {
  29897. defines.push("#define OPACITY");
  29898. if (material.opacityTexture.getAlphaFromRGB)
  29899. defines.push("#define OPACITYRGB");
  29900. if (!needUV)
  29901. defines.push("#define NEED_UV");
  29902. }
  29903. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29904. attribs.push(BABYLON.VertexBuffer.UVKind);
  29905. defines.push("#define UV1");
  29906. }
  29907. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29908. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29909. defines.push("#define UV2");
  29910. }
  29911. }
  29912. // Bones
  29913. if (mesh.useBones) {
  29914. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29915. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29916. defines.push("#define BONES");
  29917. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29918. }
  29919. // Instances
  29920. if (useInstances) {
  29921. defines.push("#define INSTANCES");
  29922. attribs.push("world0");
  29923. attribs.push("world1");
  29924. attribs.push("world2");
  29925. attribs.push("world3");
  29926. }
  29927. // Get correct effect
  29928. var join = defines.join("\n");
  29929. if (this._cachedDefines !== join) {
  29930. this._cachedDefines = join;
  29931. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel"], ["diffuseSampler", "opacitySampler"], join);
  29932. }
  29933. return this._volumetricLightScatteringPass.isReady();
  29934. };
  29935. /**
  29936. * Sets the new light position for light scattering effect
  29937. * @param {BABYLON.Vector3} The new custom light position
  29938. */
  29939. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  29940. this._customMeshPosition = position;
  29941. };
  29942. /**
  29943. * Returns the light position for light scattering effect
  29944. * @return {BABYLON.Vector3} The custom light position
  29945. */
  29946. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  29947. return this._customMeshPosition;
  29948. };
  29949. /**
  29950. * Disposes the internal assets and detaches the post-process from the camera
  29951. */
  29952. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  29953. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  29954. if (rttIndex !== -1) {
  29955. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  29956. }
  29957. this._volumetricLightScatteringRTT.dispose();
  29958. _super.prototype.dispose.call(this, camera);
  29959. };
  29960. /**
  29961. * Returns the render target texture used by the post-process
  29962. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  29963. */
  29964. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  29965. return this._volumetricLightScatteringRTT;
  29966. };
  29967. // Private methods
  29968. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  29969. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  29970. return true;
  29971. }
  29972. return false;
  29973. };
  29974. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  29975. var _this = this;
  29976. var engine = scene.getEngine();
  29977. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  29978. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29979. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29980. this._volumetricLightScatteringRTT.renderList = null;
  29981. this._volumetricLightScatteringRTT.renderParticles = false;
  29982. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  29983. // Custom render function for submeshes
  29984. var renderSubMesh = function (subMesh) {
  29985. var mesh = subMesh.getRenderingMesh();
  29986. if (_this._meshExcluded(mesh)) {
  29987. return;
  29988. }
  29989. var scene = mesh.getScene();
  29990. var engine = scene.getEngine();
  29991. // Culling
  29992. engine.setState(subMesh.getMaterial().backFaceCulling);
  29993. // Managing instances
  29994. var batch = mesh._getInstancesRenderList(subMesh._id);
  29995. if (batch.mustReturn) {
  29996. return;
  29997. }
  29998. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  29999. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  30000. engine.enableEffect(_this._volumetricLightScatteringPass);
  30001. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  30002. var material = subMesh.getMaterial();
  30003. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  30004. // Alpha test
  30005. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  30006. var alphaTexture = material.getAlphaTestTexture();
  30007. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  30008. if (alphaTexture) {
  30009. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  30010. }
  30011. if (material.opacityTexture !== undefined) {
  30012. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  30013. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  30014. }
  30015. }
  30016. // Bones
  30017. if (mesh.useBones) {
  30018. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  30019. }
  30020. // Draw
  30021. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  30022. }
  30023. };
  30024. // Render target texture callbacks
  30025. var savedSceneClearColor;
  30026. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  30027. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  30028. savedSceneClearColor = scene.clearColor;
  30029. scene.clearColor = sceneClearColor;
  30030. };
  30031. this._volumetricLightScatteringRTT.onAfterRender = function () {
  30032. scene.clearColor = savedSceneClearColor;
  30033. };
  30034. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  30035. var engine = scene.getEngine();
  30036. var index;
  30037. for (index = 0; index < opaqueSubMeshes.length; index++) {
  30038. renderSubMesh(opaqueSubMeshes.data[index]);
  30039. }
  30040. engine.setAlphaTesting(true);
  30041. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  30042. renderSubMesh(alphaTestSubMeshes.data[index]);
  30043. }
  30044. engine.setAlphaTesting(false);
  30045. if (transparentSubMeshes.length) {
  30046. for (index = 0; index < transparentSubMeshes.length; index++) {
  30047. var submesh = transparentSubMeshes.data[index];
  30048. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  30049. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  30050. }
  30051. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  30052. sortedArray.sort(function (a, b) {
  30053. // Alpha index first
  30054. if (a._alphaIndex > b._alphaIndex) {
  30055. return 1;
  30056. }
  30057. if (a._alphaIndex < b._alphaIndex) {
  30058. return -1;
  30059. }
  30060. // Then distance to camera
  30061. if (a._distanceToCamera < b._distanceToCamera) {
  30062. return 1;
  30063. }
  30064. if (a._distanceToCamera > b._distanceToCamera) {
  30065. return -1;
  30066. }
  30067. return 0;
  30068. });
  30069. // Render sub meshes
  30070. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  30071. for (index = 0; index < sortedArray.length; index++) {
  30072. renderSubMesh(sortedArray[index]);
  30073. }
  30074. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  30075. }
  30076. };
  30077. };
  30078. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  30079. var transform = scene.getTransformMatrix();
  30080. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  30081. this._screenCoordinates.x = pos.x / this._viewPort.width;
  30082. this._screenCoordinates.y = pos.y / this._viewPort.height;
  30083. if (this.invert)
  30084. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  30085. };
  30086. // Static methods
  30087. /**
  30088. * Creates a default mesh for the Volumeric Light Scattering post-process
  30089. * @param {string} The mesh name
  30090. * @param {BABYLON.Scene} The scene where to create the mesh
  30091. * @return {BABYLON.Mesh} the default mesh
  30092. */
  30093. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  30094. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  30095. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  30096. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  30097. return mesh;
  30098. };
  30099. return VolumetricLightScatteringPostProcess;
  30100. })(BABYLON.PostProcess);
  30101. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  30102. })(BABYLON || (BABYLON = {}));
  30103. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  30104. var BABYLON;
  30105. (function (BABYLON) {
  30106. var LensRenderingPipeline = (function (_super) {
  30107. __extends(LensRenderingPipeline, _super);
  30108. /**
  30109. * @constructor
  30110. *
  30111. * Effect parameters are as follow:
  30112. * {
  30113. * chromatic_aberration: number; // from 0 to x (1 for realism)
  30114. * edge_blur: number; // from 0 to x (1 for realism)
  30115. * distortion: number; // from 0 to x (1 for realism)
  30116. * grain_amount: number; // from 0 to 1
  30117. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  30118. * dof_focus_depth: number; // depth-of-field: focus depth; unset to disable (disabled by default)
  30119. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  30120. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  30121. * dof_gain: number; // depth-of-field: depthOfField gain; unset to disable (disabled by default)
  30122. * dof_threshold: number; // depth-of-field: depthOfField threshold (default: 1)
  30123. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  30124. * }
  30125. * Note: if an effect parameter is unset, effect is disabled
  30126. *
  30127. * @param {string} name - The rendering pipeline name
  30128. * @param {object} parameters - An object containing all parameters (see above)
  30129. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  30130. * @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)
  30131. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  30132. */
  30133. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  30134. var _this = this;
  30135. if (ratio === void 0) { ratio = 1.0; }
  30136. _super.call(this, scene.getEngine(), name);
  30137. // Lens effects can be of the following:
  30138. // - chromatic aberration (slight shift of RGB colors)
  30139. // - blur on the edge of the lens
  30140. // - lens distortion
  30141. // - depth-of-field blur & highlights enhancing
  30142. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  30143. // - grain effect (noise or custom texture)
  30144. // Two additional texture samplers are needed:
  30145. // - depth map (for depth-of-field)
  30146. // - grain texture
  30147. /**
  30148. * The chromatic aberration PostProcess id in the pipeline
  30149. * @type {string}
  30150. */
  30151. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  30152. /**
  30153. * The highlights enhancing PostProcess id in the pipeline
  30154. * @type {string}
  30155. */
  30156. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  30157. /**
  30158. * The depth-of-field PostProcess id in the pipeline
  30159. * @type {string}
  30160. */
  30161. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  30162. this._scene = scene;
  30163. // Fetch texture samplers
  30164. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  30165. if (parameters.grain_texture) {
  30166. this._grainTexture = parameters.grain_texture;
  30167. }
  30168. else {
  30169. this._createGrainTexture();
  30170. }
  30171. // save parameters
  30172. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  30173. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  30174. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  30175. this._distortion = parameters.distortion ? parameters.distortion : 0;
  30176. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  30177. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  30178. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  30179. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  30180. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  30181. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  30182. // Create effects
  30183. this._createChromaticAberrationPostProcess(ratio);
  30184. this._createHighlightsPostProcess(ratio);
  30185. this._createDepthOfFieldPostProcess(ratio);
  30186. // Set up pipeline
  30187. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () {
  30188. return _this._chromaticAberrationPostProcess;
  30189. }, true));
  30190. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () {
  30191. return _this._highlightsPostProcess;
  30192. }, true));
  30193. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () {
  30194. return _this._depthOfFieldPostProcess;
  30195. }, true));
  30196. if (this._highlightsGain == -1) {
  30197. this._disableEffect(this.HighlightsEnhancingEffect, null);
  30198. }
  30199. // Finish
  30200. scene.postProcessRenderPipelineManager.addPipeline(this);
  30201. if (cameras) {
  30202. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  30203. }
  30204. }
  30205. // public methods (self explanatory)
  30206. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) {
  30207. this._edgeBlur = amount;
  30208. };
  30209. LensRenderingPipeline.prototype.disableEdgeBlur = function () {
  30210. this._edgeBlur = 0;
  30211. };
  30212. LensRenderingPipeline.prototype.setGrainAmount = function (amount) {
  30213. this._grainAmount = amount;
  30214. };
  30215. LensRenderingPipeline.prototype.disableGrain = function () {
  30216. this._grainAmount = 0;
  30217. };
  30218. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) {
  30219. this._chromaticAberration = amount;
  30220. };
  30221. LensRenderingPipeline.prototype.disableChromaticAberration = function () {
  30222. this._chromaticAberration = 0;
  30223. };
  30224. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) {
  30225. this._distortion = amount;
  30226. };
  30227. LensRenderingPipeline.prototype.disableEdgeDistortion = function () {
  30228. this._distortion = 0;
  30229. };
  30230. LensRenderingPipeline.prototype.setFocusDepth = function (amount) {
  30231. this._dofDepth = amount;
  30232. };
  30233. LensRenderingPipeline.prototype.disableDepthOfField = function () {
  30234. this._dofDepth = -1;
  30235. };
  30236. LensRenderingPipeline.prototype.setAperture = function (amount) {
  30237. this._dofAperture = amount;
  30238. };
  30239. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  30240. this._dofPentagon = true;
  30241. };
  30242. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  30243. this._dofPentagon = false;
  30244. };
  30245. LensRenderingPipeline.prototype.enableNoiseBlur = function () {
  30246. this._blurNoise = true;
  30247. };
  30248. LensRenderingPipeline.prototype.disableNoiseBlur = function () {
  30249. this._blurNoise = false;
  30250. };
  30251. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  30252. this._highlightsGain = amount;
  30253. };
  30254. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  30255. if (this._highlightsGain == -1) {
  30256. this._highlightsGain = 1.0;
  30257. }
  30258. this._highlightsThreshold = amount;
  30259. };
  30260. LensRenderingPipeline.prototype.disableHighlights = function () {
  30261. this._highlightsGain = -1;
  30262. };
  30263. /**
  30264. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  30265. */
  30266. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  30267. if (disableDepthRender === void 0) { disableDepthRender = false; }
  30268. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  30269. this._chromaticAberrationPostProcess = undefined;
  30270. this._highlightsPostProcess = undefined;
  30271. this._depthOfFieldPostProcess = undefined;
  30272. this._grainTexture.dispose();
  30273. if (disableDepthRender)
  30274. this._scene.disableDepthRenderer();
  30275. };
  30276. // colors shifting and distortion
  30277. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  30278. var _this = this;
  30279. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30280. this._chromaticAberrationPostProcess.onApply = function (effect) {
  30281. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  30282. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  30283. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  30284. };
  30285. };
  30286. // highlights enhancing
  30287. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  30288. var _this = this;
  30289. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30290. this._highlightsPostProcess.onApply = function (effect) {
  30291. effect.setFloat('gain', _this._highlightsGain);
  30292. effect.setFloat('threshold', _this._highlightsThreshold);
  30293. effect.setBool('pentagon', _this._dofPentagon);
  30294. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  30295. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  30296. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  30297. };
  30298. };
  30299. // colors shifting and distortion
  30300. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  30301. var _this = this;
  30302. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  30303. "focus_depth",
  30304. "aperture",
  30305. "pentagon",
  30306. "maxZ",
  30307. "edge_blur",
  30308. "chromatic_aberration",
  30309. "distortion",
  30310. "blur_noise",
  30311. "grain_amount",
  30312. "screen_width",
  30313. "screen_height",
  30314. "highlights"
  30315. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30316. this._depthOfFieldPostProcess.onApply = function (effect) {
  30317. effect.setBool('blur_noise', _this._blurNoise);
  30318. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  30319. effect.setFloat('grain_amount', _this._grainAmount);
  30320. effect.setTexture("depthSampler", _this._depthTexture);
  30321. effect.setTexture("grainSampler", _this._grainTexture);
  30322. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  30323. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  30324. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  30325. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  30326. effect.setFloat('distortion', _this._distortion);
  30327. effect.setFloat('focus_depth', _this._dofDepth);
  30328. effect.setFloat('aperture', _this._dofAperture);
  30329. effect.setFloat('edge_blur', _this._edgeBlur);
  30330. effect.setBool('highlights', (_this._highlightsGain != -1));
  30331. };
  30332. };
  30333. // creates a black and white random noise texture, 512x512
  30334. LensRenderingPipeline.prototype._createGrainTexture = function () {
  30335. var size = 512;
  30336. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  30337. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30338. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30339. var context = this._grainTexture.getContext();
  30340. var rand = function (min, max) {
  30341. return Math.random() * (max - min) + min;
  30342. };
  30343. var value;
  30344. for (var x = 0; x < size; x++) {
  30345. for (var y = 0; y < size; y++) {
  30346. value = Math.floor(rand(0.42, 0.58) * 255);
  30347. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  30348. context.fillRect(x, y, 1, 1);
  30349. }
  30350. }
  30351. this._grainTexture.update(false);
  30352. };
  30353. return LensRenderingPipeline;
  30354. })(BABYLON.PostProcessRenderPipeline);
  30355. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  30356. })(BABYLON || (BABYLON = {}));
  30357. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map//
  30358. // This post-process allows the modification of rendered colors by using
  30359. // a 'look-up table' (LUT). This effect is also called Color Grading.
  30360. //
  30361. // The object needs to be provided an url to a texture containing the color
  30362. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  30363. // Use an image editing software to tweak the LUT to match your needs.
  30364. //
  30365. // For an example of a color LUT, see here:
  30366. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  30367. // For explanations on color grading, see here:
  30368. // http://udn.epicgames.com/Three/ColorGrading.html
  30369. //
  30370. var BABYLON;
  30371. (function (BABYLON) {
  30372. var ColorCorrectionPostProcess = (function (_super) {
  30373. __extends(ColorCorrectionPostProcess, _super);
  30374. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  30375. var _this = this;
  30376. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  30377. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  30378. this._colorTableTexture.anisotropicFilteringLevel = 1;
  30379. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30380. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30381. this.onApply = function (effect) {
  30382. effect.setTexture("colorTable", _this._colorTableTexture);
  30383. };
  30384. }
  30385. return ColorCorrectionPostProcess;
  30386. })(BABYLON.PostProcess);
  30387. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  30388. })(BABYLON || (BABYLON = {}));
  30389. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.mapvar BABYLON;
  30390. (function (BABYLON) {
  30391. var SmartCollection = (function () {
  30392. function SmartCollection(capacity) {
  30393. if (capacity === void 0) { capacity = 10; }
  30394. this.count = 0;
  30395. this._initialCapacity = capacity;
  30396. this.items = {};
  30397. this._keys = new Array(this._initialCapacity);
  30398. }
  30399. SmartCollection.prototype.add = function (key, item) {
  30400. if (this.items[key] != undefined) {
  30401. return -1;
  30402. }
  30403. this.items[key] = item;
  30404. //literal keys are always strings, but we keep source type of key in _keys array
  30405. this._keys[this.count++] = key;
  30406. if (this.count > this._keys.length) {
  30407. this._keys.length *= 2;
  30408. }
  30409. return this.count;
  30410. };
  30411. SmartCollection.prototype.remove = function (key) {
  30412. if (this.items[key] == undefined) {
  30413. return -1;
  30414. }
  30415. return this.removeItemOfIndex(this.indexOf(key));
  30416. };
  30417. SmartCollection.prototype.removeItemOfIndex = function (index) {
  30418. if (index < this.count && index > -1) {
  30419. delete this.items[this._keys[index]];
  30420. while (index < this.count) {
  30421. this._keys[index] = this._keys[index + 1];
  30422. index++;
  30423. }
  30424. }
  30425. else {
  30426. return -1;
  30427. }
  30428. return --this.count;
  30429. };
  30430. SmartCollection.prototype.indexOf = function (key) {
  30431. for (var i = 0; i !== this.count; i++) {
  30432. if (this._keys[i] === key) {
  30433. return i;
  30434. }
  30435. }
  30436. return -1;
  30437. };
  30438. SmartCollection.prototype.item = function (key) {
  30439. return this.items[key];
  30440. };
  30441. SmartCollection.prototype.getAllKeys = function () {
  30442. if (this.count > 0) {
  30443. var keys = new Array(this.count);
  30444. for (var i = 0; i < this.count; i++) {
  30445. keys[i] = this._keys[i];
  30446. }
  30447. return keys;
  30448. }
  30449. else {
  30450. return undefined;
  30451. }
  30452. };
  30453. SmartCollection.prototype.getKeyByIndex = function (index) {
  30454. if (index < this.count && index > -1) {
  30455. return this._keys[index];
  30456. }
  30457. else {
  30458. return undefined;
  30459. }
  30460. };
  30461. SmartCollection.prototype.getItemByIndex = function (index) {
  30462. if (index < this.count && index > -1) {
  30463. return this.items[this._keys[index]];
  30464. }
  30465. else {
  30466. return undefined;
  30467. }
  30468. };
  30469. SmartCollection.prototype.empty = function () {
  30470. if (this.count > 0) {
  30471. this.count = 0;
  30472. this.items = {};
  30473. this._keys = new Array(this._initialCapacity);
  30474. }
  30475. };
  30476. SmartCollection.prototype.forEach = function (block) {
  30477. var key;
  30478. for (key in this.items) {
  30479. if (this.items.hasOwnProperty(key)) {
  30480. block(this.items[key]);
  30481. }
  30482. }
  30483. };
  30484. return SmartCollection;
  30485. })();
  30486. BABYLON.SmartCollection = SmartCollection;
  30487. })(BABYLON || (BABYLON = {}));
  30488. //# sourceMappingURL=babylon.smartCollection.js.map