babylon.2.1-alpha.debug.js 1.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339
  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.reciprocal(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.reciprocalSqrt(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.reciprocalSqrt(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.reciprocalSqrt(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.reciprocalSqrt(tmp));
  1895. //cc.kmMat4Identity(pOut);
  1896. //pOut.mat[0] = s.x;
  1897. //pOut.mat[4] = s.y;
  1898. //pOut.mat[8] = s.z;
  1899. //pOut.mat[1] = u.x;
  1900. //pOut.mat[5] = u.y;
  1901. //pOut.mat[9] = u.z;
  1902. //pOut.mat[2] = -f.x;
  1903. //pOut.mat[6] = -f.y;
  1904. //pOut.mat[10] = -f.z;
  1905. var zero = SIMD.float32x4.splat(0.0);
  1906. s = SIMD.float32x4.neg(s);
  1907. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  1908. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  1909. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1910. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  1911. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  1912. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  1913. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1914. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  1915. // cc.kmMat4Translation(translate, -pEye.x, -pEye.y, -pEye.z);
  1916. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  1917. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  1918. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  1919. var b3 = SIMD.float32x4.neg(eye);
  1920. b3 = SIMD.float32x4.withW(b3, 1.0);
  1921. // cc.kmMat4Multiply(pOut, pOut, translate);
  1922. 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)))));
  1923. 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)))));
  1924. 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)))));
  1925. 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)))));
  1926. };
  1927. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1928. var matrix = Matrix.Zero();
  1929. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1930. return matrix;
  1931. };
  1932. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1933. var hw = 2.0 / width;
  1934. var hh = 2.0 / height;
  1935. var id = 1.0 / (zfar - znear);
  1936. var nid = znear / (znear - zfar);
  1937. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1938. };
  1939. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1940. var matrix = Matrix.Zero();
  1941. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1942. return matrix;
  1943. };
  1944. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1945. result.m[0] = 2.0 / (right - left);
  1946. result.m[1] = result.m[2] = result.m[3] = 0;
  1947. result.m[5] = 2.0 / (top - bottom);
  1948. result.m[4] = result.m[6] = result.m[7] = 0;
  1949. result.m[10] = -1.0 / (znear - zfar);
  1950. result.m[8] = result.m[9] = result.m[11] = 0;
  1951. result.m[12] = (left + right) / (left - right);
  1952. result.m[13] = (top + bottom) / (bottom - top);
  1953. result.m[14] = znear / (znear - zfar);
  1954. result.m[15] = 1.0;
  1955. };
  1956. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1957. var matrix = Matrix.Zero();
  1958. matrix.m[0] = (2.0 * znear) / width;
  1959. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1960. matrix.m[5] = (2.0 * znear) / height;
  1961. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1962. matrix.m[10] = -zfar / (znear - zfar);
  1963. matrix.m[8] = matrix.m[9] = 0.0;
  1964. matrix.m[11] = 1.0;
  1965. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1966. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1967. return matrix;
  1968. };
  1969. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1970. var matrix = Matrix.Zero();
  1971. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1972. return matrix;
  1973. };
  1974. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1975. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1976. var tan = 1.0 / (Math.tan(fov * 0.5));
  1977. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1978. if (v_fixed) {
  1979. result.m[0] = tan / aspect;
  1980. }
  1981. else {
  1982. result.m[0] = tan;
  1983. }
  1984. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1985. if (v_fixed) {
  1986. result.m[5] = tan;
  1987. }
  1988. else {
  1989. result.m[5] = tan * aspect;
  1990. }
  1991. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1992. result.m[8] = result.m[9] = 0.0;
  1993. result.m[10] = -zfar / (znear - zfar);
  1994. result.m[11] = 1.0;
  1995. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1996. result.m[14] = (znear * zfar) / (znear - zfar);
  1997. };
  1998. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1999. var cw = viewport.width;
  2000. var ch = viewport.height;
  2001. var cx = viewport.x;
  2002. var cy = viewport.y;
  2003. 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);
  2004. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2005. };
  2006. Matrix.Transpose = function (matrix) {
  2007. var result = new Matrix();
  2008. result.m[0] = matrix.m[0];
  2009. result.m[1] = matrix.m[4];
  2010. result.m[2] = matrix.m[8];
  2011. result.m[3] = matrix.m[12];
  2012. result.m[4] = matrix.m[1];
  2013. result.m[5] = matrix.m[5];
  2014. result.m[6] = matrix.m[9];
  2015. result.m[7] = matrix.m[13];
  2016. result.m[8] = matrix.m[2];
  2017. result.m[9] = matrix.m[6];
  2018. result.m[10] = matrix.m[10];
  2019. result.m[11] = matrix.m[14];
  2020. result.m[12] = matrix.m[3];
  2021. result.m[13] = matrix.m[7];
  2022. result.m[14] = matrix.m[11];
  2023. result.m[15] = matrix.m[15];
  2024. return result;
  2025. };
  2026. Matrix.Reflection = function (plane) {
  2027. var matrix = new Matrix();
  2028. Matrix.ReflectionToRef(plane, matrix);
  2029. return matrix;
  2030. };
  2031. Matrix.ReflectionToRef = function (plane, result) {
  2032. plane.normalize();
  2033. var x = plane.normal.x;
  2034. var y = plane.normal.y;
  2035. var z = plane.normal.z;
  2036. var temp = -2 * x;
  2037. var temp2 = -2 * y;
  2038. var temp3 = -2 * z;
  2039. result.m[0] = (temp * x) + 1;
  2040. result.m[1] = temp2 * x;
  2041. result.m[2] = temp3 * x;
  2042. result.m[3] = 0.0;
  2043. result.m[4] = temp * y;
  2044. result.m[5] = (temp2 * y) + 1;
  2045. result.m[6] = temp3 * y;
  2046. result.m[7] = 0.0;
  2047. result.m[8] = temp * z;
  2048. result.m[9] = temp2 * z;
  2049. result.m[10] = (temp3 * z) + 1;
  2050. result.m[11] = 0.0;
  2051. result.m[12] = temp * plane.d;
  2052. result.m[13] = temp2 * plane.d;
  2053. result.m[14] = temp3 * plane.d;
  2054. result.m[15] = 1.0;
  2055. };
  2056. Matrix._tempQuaternion = new Quaternion();
  2057. Matrix._xAxis = Vector3.Zero();
  2058. Matrix._yAxis = Vector3.Zero();
  2059. Matrix._zAxis = Vector3.Zero();
  2060. return Matrix;
  2061. })();
  2062. BABYLON.Matrix = Matrix;
  2063. var Plane = (function () {
  2064. function Plane(a, b, c, d) {
  2065. this.normal = new Vector3(a, b, c);
  2066. this.d = d;
  2067. }
  2068. Plane.prototype.asArray = function () {
  2069. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2070. };
  2071. // Methods
  2072. Plane.prototype.clone = function () {
  2073. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2074. };
  2075. Plane.prototype.normalize = function () {
  2076. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2077. var magnitude = 0;
  2078. if (norm !== 0) {
  2079. magnitude = 1.0 / norm;
  2080. }
  2081. this.normal.x *= magnitude;
  2082. this.normal.y *= magnitude;
  2083. this.normal.z *= magnitude;
  2084. this.d *= magnitude;
  2085. return this;
  2086. };
  2087. Plane.prototype.transform = function (transformation) {
  2088. var transposedMatrix = Matrix.Transpose(transformation);
  2089. var x = this.normal.x;
  2090. var y = this.normal.y;
  2091. var z = this.normal.z;
  2092. var d = this.d;
  2093. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2094. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2095. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2096. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2097. return new Plane(normalX, normalY, normalZ, finalD);
  2098. };
  2099. Plane.prototype.dotCoordinate = function (point) {
  2100. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2101. };
  2102. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2103. var x1 = point2.x - point1.x;
  2104. var y1 = point2.y - point1.y;
  2105. var z1 = point2.z - point1.z;
  2106. var x2 = point3.x - point1.x;
  2107. var y2 = point3.y - point1.y;
  2108. var z2 = point3.z - point1.z;
  2109. var yz = (y1 * z2) - (z1 * y2);
  2110. var xz = (z1 * x2) - (x1 * z2);
  2111. var xy = (x1 * y2) - (y1 * x2);
  2112. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2113. var invPyth;
  2114. if (pyth !== 0) {
  2115. invPyth = 1.0 / pyth;
  2116. }
  2117. else {
  2118. invPyth = 0;
  2119. }
  2120. this.normal.x = yz * invPyth;
  2121. this.normal.y = xz * invPyth;
  2122. this.normal.z = xy * invPyth;
  2123. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2124. return this;
  2125. };
  2126. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2127. var dot = Vector3.Dot(this.normal, direction);
  2128. return (dot <= epsilon);
  2129. };
  2130. Plane.prototype.signedDistanceTo = function (point) {
  2131. return Vector3.Dot(point, this.normal) + this.d;
  2132. };
  2133. // Statics
  2134. Plane.FromArray = function (array) {
  2135. return new Plane(array[0], array[1], array[2], array[3]);
  2136. };
  2137. Plane.FromPoints = function (point1, point2, point3) {
  2138. var result = new Plane(0, 0, 0, 0);
  2139. result.copyFromPoints(point1, point2, point3);
  2140. return result;
  2141. };
  2142. Plane.FromPositionAndNormal = function (origin, normal) {
  2143. var result = new Plane(0, 0, 0, 0);
  2144. normal.normalize();
  2145. result.normal = normal;
  2146. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2147. return result;
  2148. };
  2149. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2150. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2151. return Vector3.Dot(point, normal) + d;
  2152. };
  2153. return Plane;
  2154. })();
  2155. BABYLON.Plane = Plane;
  2156. var Viewport = (function () {
  2157. function Viewport(x, y, width, height) {
  2158. this.x = x;
  2159. this.y = y;
  2160. this.width = width;
  2161. this.height = height;
  2162. }
  2163. Viewport.prototype.toGlobal = function (engine) {
  2164. var width = engine.getRenderWidth();
  2165. var height = engine.getRenderHeight();
  2166. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2167. };
  2168. return Viewport;
  2169. })();
  2170. BABYLON.Viewport = Viewport;
  2171. var Frustum = (function () {
  2172. function Frustum() {
  2173. }
  2174. Frustum.GetPlanes = function (transform) {
  2175. var frustumPlanes = [];
  2176. for (var index = 0; index < 6; index++) {
  2177. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2178. }
  2179. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2180. return frustumPlanes;
  2181. };
  2182. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2183. // Near
  2184. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2185. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2186. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  2187. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2188. frustumPlanes[0].normalize();
  2189. // Far
  2190. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2191. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2192. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2193. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2194. frustumPlanes[1].normalize();
  2195. // Left
  2196. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2197. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2198. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2199. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2200. frustumPlanes[2].normalize();
  2201. // Right
  2202. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2203. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2204. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2205. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2206. frustumPlanes[3].normalize();
  2207. // Top
  2208. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2209. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2210. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2211. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2212. frustumPlanes[4].normalize();
  2213. // Bottom
  2214. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2215. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2216. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2217. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2218. frustumPlanes[5].normalize();
  2219. };
  2220. return Frustum;
  2221. })();
  2222. BABYLON.Frustum = Frustum;
  2223. var Ray = (function () {
  2224. function Ray(origin, direction, length) {
  2225. if (length === void 0) { length = Number.MAX_VALUE; }
  2226. this.origin = origin;
  2227. this.direction = direction;
  2228. this.length = length;
  2229. }
  2230. // Methods
  2231. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2232. var d = 0.0;
  2233. var maxValue = Number.MAX_VALUE;
  2234. if (Math.abs(this.direction.x) < 0.0000001) {
  2235. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2236. return false;
  2237. }
  2238. }
  2239. else {
  2240. var inv = 1.0 / this.direction.x;
  2241. var min = (minimum.x - this.origin.x) * inv;
  2242. var max = (maximum.x - this.origin.x) * inv;
  2243. if (max === -Infinity) {
  2244. max = Infinity;
  2245. }
  2246. if (min > max) {
  2247. var temp = min;
  2248. min = max;
  2249. max = temp;
  2250. }
  2251. d = Math.max(min, d);
  2252. maxValue = Math.min(max, maxValue);
  2253. if (d > maxValue) {
  2254. return false;
  2255. }
  2256. }
  2257. if (Math.abs(this.direction.y) < 0.0000001) {
  2258. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2259. return false;
  2260. }
  2261. }
  2262. else {
  2263. inv = 1.0 / this.direction.y;
  2264. min = (minimum.y - this.origin.y) * inv;
  2265. max = (maximum.y - this.origin.y) * inv;
  2266. if (max === -Infinity) {
  2267. max = Infinity;
  2268. }
  2269. if (min > max) {
  2270. temp = min;
  2271. min = max;
  2272. max = temp;
  2273. }
  2274. d = Math.max(min, d);
  2275. maxValue = Math.min(max, maxValue);
  2276. if (d > maxValue) {
  2277. return false;
  2278. }
  2279. }
  2280. if (Math.abs(this.direction.z) < 0.0000001) {
  2281. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2282. return false;
  2283. }
  2284. }
  2285. else {
  2286. inv = 1.0 / this.direction.z;
  2287. min = (minimum.z - this.origin.z) * inv;
  2288. max = (maximum.z - this.origin.z) * inv;
  2289. if (max === -Infinity) {
  2290. max = Infinity;
  2291. }
  2292. if (min > max) {
  2293. temp = min;
  2294. min = max;
  2295. max = temp;
  2296. }
  2297. d = Math.max(min, d);
  2298. maxValue = Math.min(max, maxValue);
  2299. if (d > maxValue) {
  2300. return false;
  2301. }
  2302. }
  2303. return true;
  2304. };
  2305. Ray.prototype.intersectsBox = function (box) {
  2306. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2307. };
  2308. Ray.prototype.intersectsSphere = function (sphere) {
  2309. var x = sphere.center.x - this.origin.x;
  2310. var y = sphere.center.y - this.origin.y;
  2311. var z = sphere.center.z - this.origin.z;
  2312. var pyth = (x * x) + (y * y) + (z * z);
  2313. var rr = sphere.radius * sphere.radius;
  2314. if (pyth <= rr) {
  2315. return true;
  2316. }
  2317. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2318. if (dot < 0.0) {
  2319. return false;
  2320. }
  2321. var temp = pyth - (dot * dot);
  2322. return temp <= rr;
  2323. };
  2324. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2325. if (!this._edge1) {
  2326. this._edge1 = Vector3.Zero();
  2327. this._edge2 = Vector3.Zero();
  2328. this._pvec = Vector3.Zero();
  2329. this._tvec = Vector3.Zero();
  2330. this._qvec = Vector3.Zero();
  2331. }
  2332. vertex1.subtractToRef(vertex0, this._edge1);
  2333. vertex2.subtractToRef(vertex0, this._edge2);
  2334. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2335. var det = Vector3.Dot(this._edge1, this._pvec);
  2336. if (det === 0) {
  2337. return null;
  2338. }
  2339. var invdet = 1 / det;
  2340. this.origin.subtractToRef(vertex0, this._tvec);
  2341. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2342. if (bu < 0 || bu > 1.0) {
  2343. return null;
  2344. }
  2345. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2346. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2347. if (bv < 0 || bu + bv > 1.0) {
  2348. return null;
  2349. }
  2350. //check if the distance is longer than the predefined length.
  2351. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2352. if (distance > this.length) {
  2353. return null;
  2354. }
  2355. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2356. };
  2357. // Statics
  2358. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2359. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2360. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2361. var direction = end.subtract(start);
  2362. direction.normalize();
  2363. return new Ray(start, direction);
  2364. };
  2365. /**
  2366. * 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
  2367. * transformed to the given world matrix.
  2368. * @param origin The origin point
  2369. * @param end The end point
  2370. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2371. */
  2372. Ray.CreateNewFromTo = function (origin, end, world) {
  2373. if (world === void 0) { world = Matrix.Identity(); }
  2374. var direction = end.subtract(origin);
  2375. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2376. direction.normalize();
  2377. return Ray.Transform(new Ray(origin, direction, length), world);
  2378. };
  2379. Ray.Transform = function (ray, matrix) {
  2380. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2381. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2382. return new Ray(newOrigin, newDirection, ray.length);
  2383. };
  2384. return Ray;
  2385. })();
  2386. BABYLON.Ray = Ray;
  2387. (function (Space) {
  2388. Space[Space["LOCAL"] = 0] = "LOCAL";
  2389. Space[Space["WORLD"] = 1] = "WORLD";
  2390. })(BABYLON.Space || (BABYLON.Space = {}));
  2391. var Space = BABYLON.Space;
  2392. var Axis = (function () {
  2393. function Axis() {
  2394. }
  2395. Axis.X = new Vector3(1, 0, 0);
  2396. Axis.Y = new Vector3(0, 1, 0);
  2397. Axis.Z = new Vector3(0, 0, 1);
  2398. return Axis;
  2399. })();
  2400. BABYLON.Axis = Axis;
  2401. ;
  2402. var BezierCurve = (function () {
  2403. function BezierCurve() {
  2404. }
  2405. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2406. // Extract X (which is equal to time here)
  2407. var f0 = 1 - 3 * x2 + 3 * x1;
  2408. var f1 = 3 * x2 - 6 * x1;
  2409. var f2 = 3 * x1;
  2410. var refinedT = t;
  2411. for (var i = 0; i < 5; i++) {
  2412. var refinedT2 = refinedT * refinedT;
  2413. var refinedT3 = refinedT2 * refinedT;
  2414. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2415. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2416. refinedT -= (x - t) * slope;
  2417. refinedT = Math.min(1, Math.max(0, refinedT));
  2418. }
  2419. // Resolve cubic bezier for the given x
  2420. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2421. };
  2422. return BezierCurve;
  2423. })();
  2424. BABYLON.BezierCurve = BezierCurve;
  2425. (function (Orientation) {
  2426. Orientation[Orientation["CW"] = 0] = "CW";
  2427. Orientation[Orientation["CCW"] = 1] = "CCW";
  2428. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2429. var Orientation = BABYLON.Orientation;
  2430. var Angle = (function () {
  2431. function Angle(radians) {
  2432. var _this = this;
  2433. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2434. this.radians = function () { return _this._radians; };
  2435. this._radians = radians;
  2436. if (this._radians < 0)
  2437. this._radians += (2 * Math.PI);
  2438. }
  2439. Angle.BetweenTwoPoints = function (a, b) {
  2440. var delta = b.subtract(a);
  2441. var theta = Math.atan2(delta.y, delta.x);
  2442. return new Angle(theta);
  2443. };
  2444. Angle.FromRadians = function (radians) {
  2445. return new Angle(radians);
  2446. };
  2447. Angle.FromDegrees = function (degrees) {
  2448. return new Angle(degrees * Math.PI / 180);
  2449. };
  2450. return Angle;
  2451. })();
  2452. BABYLON.Angle = Angle;
  2453. var Arc2 = (function () {
  2454. function Arc2(startPoint, midPoint, endPoint) {
  2455. this.startPoint = startPoint;
  2456. this.midPoint = midPoint;
  2457. this.endPoint = endPoint;
  2458. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2459. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2460. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2461. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2462. 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);
  2463. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2464. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2465. var a1 = this.startAngle.degrees();
  2466. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2467. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2468. // angles correction
  2469. if (a2 - a1 > +180.0)
  2470. a2 -= 360.0;
  2471. if (a2 - a1 < -180.0)
  2472. a2 += 360.0;
  2473. if (a3 - a2 > +180.0)
  2474. a3 -= 360.0;
  2475. if (a3 - a2 < -180.0)
  2476. a3 += 360.0;
  2477. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2478. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2479. }
  2480. return Arc2;
  2481. })();
  2482. BABYLON.Arc2 = Arc2;
  2483. var PathCursor = (function () {
  2484. function PathCursor(path) {
  2485. this.path = path;
  2486. this._onchange = new Array();
  2487. this.value = 0;
  2488. this.animations = new Array();
  2489. }
  2490. PathCursor.prototype.getPoint = function () {
  2491. var point = this.path.getPointAtLengthPosition(this.value);
  2492. return new Vector3(point.x, 0, point.y);
  2493. };
  2494. PathCursor.prototype.moveAhead = function (step) {
  2495. if (step === void 0) { step = 0.002; }
  2496. this.move(step);
  2497. return this;
  2498. };
  2499. PathCursor.prototype.moveBack = function (step) {
  2500. if (step === void 0) { step = 0.002; }
  2501. this.move(-step);
  2502. return this;
  2503. };
  2504. PathCursor.prototype.move = function (step) {
  2505. if (Math.abs(step) > 1) {
  2506. throw "step size should be less than 1.";
  2507. }
  2508. this.value += step;
  2509. this.ensureLimits();
  2510. this.raiseOnChange();
  2511. return this;
  2512. };
  2513. PathCursor.prototype.ensureLimits = function () {
  2514. while (this.value > 1) {
  2515. this.value -= 1;
  2516. }
  2517. while (this.value < 0) {
  2518. this.value += 1;
  2519. }
  2520. return this;
  2521. };
  2522. // used by animation engine
  2523. PathCursor.prototype.markAsDirty = function (propertyName) {
  2524. this.ensureLimits();
  2525. this.raiseOnChange();
  2526. return this;
  2527. };
  2528. PathCursor.prototype.raiseOnChange = function () {
  2529. var _this = this;
  2530. this._onchange.forEach(function (f) { return f(_this); });
  2531. return this;
  2532. };
  2533. PathCursor.prototype.onchange = function (f) {
  2534. this._onchange.push(f);
  2535. return this;
  2536. };
  2537. return PathCursor;
  2538. })();
  2539. BABYLON.PathCursor = PathCursor;
  2540. var Path2 = (function () {
  2541. function Path2(x, y) {
  2542. this._points = new Array();
  2543. this._length = 0;
  2544. this.closed = false;
  2545. this._points.push(new Vector2(x, y));
  2546. }
  2547. Path2.prototype.addLineTo = function (x, y) {
  2548. if (closed) {
  2549. BABYLON.Tools.Error("cannot add lines to closed paths");
  2550. return this;
  2551. }
  2552. var newPoint = new Vector2(x, y);
  2553. var previousPoint = this._points[this._points.length - 1];
  2554. this._points.push(newPoint);
  2555. this._length += newPoint.subtract(previousPoint).length();
  2556. return this;
  2557. };
  2558. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2559. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2560. if (closed) {
  2561. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2562. return this;
  2563. }
  2564. var startPoint = this._points[this._points.length - 1];
  2565. var midPoint = new Vector2(midX, midY);
  2566. var endPoint = new Vector2(endX, endY);
  2567. var arc = new Arc2(startPoint, midPoint, endPoint);
  2568. var increment = arc.angle.radians() / numberOfSegments;
  2569. if (arc.orientation === 0 /* CW */)
  2570. increment *= -1;
  2571. var currentAngle = arc.startAngle.radians() + increment;
  2572. for (var i = 0; i < numberOfSegments; i++) {
  2573. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2574. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2575. this.addLineTo(x, y);
  2576. currentAngle += increment;
  2577. }
  2578. return this;
  2579. };
  2580. Path2.prototype.close = function () {
  2581. this.closed = true;
  2582. return this;
  2583. };
  2584. Path2.prototype.length = function () {
  2585. var result = this._length;
  2586. if (!this.closed) {
  2587. var lastPoint = this._points[this._points.length - 1];
  2588. var firstPoint = this._points[0];
  2589. result += (firstPoint.subtract(lastPoint).length());
  2590. }
  2591. return result;
  2592. };
  2593. Path2.prototype.getPoints = function () {
  2594. return this._points;
  2595. };
  2596. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2597. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2598. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2599. return Vector2.Zero();
  2600. }
  2601. var lengthPosition = normalizedLengthPosition * this.length();
  2602. var previousOffset = 0;
  2603. for (var i = 0; i < this._points.length; i++) {
  2604. var j = (i + 1) % this._points.length;
  2605. var a = this._points[i];
  2606. var b = this._points[j];
  2607. var bToA = b.subtract(a);
  2608. var nextOffset = (bToA.length() + previousOffset);
  2609. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2610. var dir = bToA.normalize();
  2611. var localOffset = lengthPosition - previousOffset;
  2612. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2613. }
  2614. previousOffset = nextOffset;
  2615. }
  2616. BABYLON.Tools.Error("internal error");
  2617. return Vector2.Zero();
  2618. };
  2619. Path2.StartingAt = function (x, y) {
  2620. return new Path2(x, y);
  2621. };
  2622. return Path2;
  2623. })();
  2624. BABYLON.Path2 = Path2;
  2625. var Path3D = (function () {
  2626. function Path3D(path) {
  2627. this.path = path;
  2628. this._curve = new Array();
  2629. this._distances = new Array();
  2630. this._tangents = new Array();
  2631. this._normals = new Array();
  2632. this._binormals = new Array();
  2633. this._curve = path.slice(); // copy array
  2634. this._compute();
  2635. }
  2636. Path3D.prototype.getCurve = function () {
  2637. return this._curve;
  2638. };
  2639. Path3D.prototype.getTangents = function () {
  2640. return this._tangents;
  2641. };
  2642. Path3D.prototype.getNormals = function () {
  2643. return this._normals;
  2644. };
  2645. Path3D.prototype.getBinormals = function () {
  2646. return this._binormals;
  2647. };
  2648. Path3D.prototype.getDistances = function () {
  2649. return this._distances;
  2650. };
  2651. Path3D.prototype.update = function (path) {
  2652. for (var i = 0; i < path.length; i++) {
  2653. this._curve[i] = path[i];
  2654. }
  2655. this._compute();
  2656. return this;
  2657. };
  2658. // private function compute() : computes tangents, normals and binormals
  2659. Path3D.prototype._compute = function () {
  2660. var l = this._curve.length;
  2661. // first and last tangents
  2662. this._tangents[0] = this._curve[1].subtract(this._curve[0]);
  2663. this._tangents[0].normalize();
  2664. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2665. this._tangents[l - 1].normalize();
  2666. // normals and binormals at first point : arbitrary vector with _normalVector()
  2667. var tg0 = this._tangents[0];
  2668. var pp0 = this._normalVector(this._curve[0], tg0);
  2669. this._normals[0] = pp0;
  2670. this._normals[0].normalize();
  2671. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2672. this._normals[0].normalize();
  2673. this._distances[0] = 0;
  2674. // normals and binormals : next points
  2675. var prev; // previous vector (segment)
  2676. var cur; // current vector (segment)
  2677. var curTang; // current tangent
  2678. var prevNorm; // previous normal
  2679. var prevBinor; // previous binormal
  2680. for (var i = 1; i < l; i++) {
  2681. // tangents
  2682. prev = this._curve[i].subtract(this._curve[i - 1]);
  2683. if (i < l - 1) {
  2684. cur = this._curve[i + 1].subtract(this._curve[i]);
  2685. this._tangents[i] = prev.add(cur);
  2686. this._tangents[i].normalize();
  2687. }
  2688. this._distances[i] = this._distances[i - 1] + prev.length();
  2689. // normals and binormals
  2690. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2691. curTang = this._tangents[i];
  2692. prevNorm = this._normals[i - 1];
  2693. prevBinor = this._binormals[i - 1];
  2694. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2695. this._normals[i].normalize();
  2696. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2697. this._binormals[i].normalize();
  2698. }
  2699. };
  2700. // private function normalVector(v0, vt) :
  2701. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2702. Path3D.prototype._normalVector = function (v0, vt) {
  2703. var point;
  2704. if (vt.x !== 1) {
  2705. point = new Vector3(1, 0, 0);
  2706. }
  2707. else if (vt.y !== 1) {
  2708. point = new Vector3(0, 1, 0);
  2709. }
  2710. else if (vt.z !== 1) {
  2711. point = new Vector3(0, 0, 1);
  2712. }
  2713. var normal0 = Vector3.Cross(vt, point);
  2714. normal0.normalize();
  2715. return normal0;
  2716. };
  2717. return Path3D;
  2718. })();
  2719. BABYLON.Path3D = Path3D;
  2720. var Curve3 = (function () {
  2721. function Curve3(points) {
  2722. this._points = points;
  2723. }
  2724. // QuadraticBezier(origin_V3, control_V3, destination_V3 )
  2725. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2726. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2727. var bez = new Array();
  2728. var step = 1 / nbPoints;
  2729. var equation = function (t, val0, val1, val2) {
  2730. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2731. return res;
  2732. };
  2733. for (var i = 0; i <= 1; i += step) {
  2734. 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)));
  2735. }
  2736. return new Curve3(bez);
  2737. };
  2738. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3)
  2739. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2740. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2741. var bez = new Array();
  2742. var step = 1 / nbPoints;
  2743. var equation = function (t, val0, val1, val2, val3) {
  2744. 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;
  2745. return res;
  2746. };
  2747. for (var i = 0; i <= 1; i += step) {
  2748. 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)));
  2749. }
  2750. return new Curve3(bez);
  2751. };
  2752. Curve3.prototype.getPoints = function () {
  2753. return this._points;
  2754. };
  2755. Curve3.prototype.continue = function (curve) {
  2756. var lastPoint = this._points[this._points.length - 1];
  2757. var continuedPoints = this._points.slice();
  2758. var curvePoints = curve.getPoints();
  2759. for (var i = 1; i < curvePoints.length; i++) {
  2760. continuedPoints.push(curvePoints[i].add(lastPoint));
  2761. }
  2762. return new Curve3(continuedPoints);
  2763. };
  2764. return Curve3;
  2765. })();
  2766. BABYLON.Curve3 = Curve3;
  2767. // Vertex formats
  2768. var PositionNormalVertex = (function () {
  2769. function PositionNormalVertex(position, normal) {
  2770. if (position === void 0) { position = Vector3.Zero(); }
  2771. if (normal === void 0) { normal = Vector3.Up(); }
  2772. this.position = position;
  2773. this.normal = normal;
  2774. }
  2775. PositionNormalVertex.prototype.clone = function () {
  2776. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2777. };
  2778. return PositionNormalVertex;
  2779. })();
  2780. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2781. var PositionNormalTextureVertex = (function () {
  2782. function PositionNormalTextureVertex(position, normal, uv) {
  2783. if (position === void 0) { position = Vector3.Zero(); }
  2784. if (normal === void 0) { normal = Vector3.Up(); }
  2785. if (uv === void 0) { uv = Vector2.Zero(); }
  2786. this.position = position;
  2787. this.normal = normal;
  2788. this.uv = uv;
  2789. }
  2790. PositionNormalTextureVertex.prototype.clone = function () {
  2791. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2792. };
  2793. return PositionNormalTextureVertex;
  2794. })();
  2795. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2796. // SIMD
  2797. if (window.SIMD !== undefined) {
  2798. // Replace functions
  2799. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  2800. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  2801. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  2802. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  2803. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  2804. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  2805. get: function () {
  2806. return this._data[0];
  2807. },
  2808. set: function (value) {
  2809. if (!this._data) {
  2810. this._data = new Float32Array(3);
  2811. }
  2812. this._data[0] = value;
  2813. }
  2814. });
  2815. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  2816. get: function () {
  2817. return this._data[1];
  2818. },
  2819. set: function (value) {
  2820. this._data[1] = value;
  2821. }
  2822. });
  2823. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  2824. get: function () {
  2825. return this._data[2];
  2826. },
  2827. set: function (value) {
  2828. this._data[2] = value;
  2829. }
  2830. });
  2831. }
  2832. })(BABYLON || (BABYLON = {}));
  2833. //# sourceMappingURL=babylon.math.js.mapvar BABYLON;
  2834. (function (BABYLON) {
  2835. // Screenshots
  2836. var screenshotCanvas;
  2837. var cloneValue = function (source, destinationObject) {
  2838. if (!source)
  2839. return null;
  2840. if (source instanceof BABYLON.Mesh) {
  2841. return null;
  2842. }
  2843. if (source instanceof BABYLON.SubMesh) {
  2844. return source.clone(destinationObject);
  2845. }
  2846. else if (source.clone) {
  2847. return source.clone();
  2848. }
  2849. return null;
  2850. };
  2851. var Tools = (function () {
  2852. function Tools() {
  2853. }
  2854. Tools.GetFilename = function (path) {
  2855. var index = path.lastIndexOf("/");
  2856. if (index < 0)
  2857. return path;
  2858. return path.substring(index + 1);
  2859. };
  2860. Tools.GetDOMTextContent = function (element) {
  2861. var result = "";
  2862. var child = element.firstChild;
  2863. while (child) {
  2864. if (child.nodeType === 3) {
  2865. result += child.textContent;
  2866. }
  2867. child = child.nextSibling;
  2868. }
  2869. return result;
  2870. };
  2871. Tools.ToDegrees = function (angle) {
  2872. return angle * 180 / Math.PI;
  2873. };
  2874. Tools.ToRadians = function (angle) {
  2875. return angle * Math.PI / 180;
  2876. };
  2877. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2878. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2879. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2880. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2881. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2882. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2883. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2884. }
  2885. return {
  2886. minimum: minimum,
  2887. maximum: maximum
  2888. };
  2889. };
  2890. Tools.ExtractMinAndMax = function (positions, start, count) {
  2891. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2892. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2893. for (var index = start; index < start + count; index++) {
  2894. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2895. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2896. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2897. }
  2898. return {
  2899. minimum: minimum,
  2900. maximum: maximum
  2901. };
  2902. };
  2903. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2904. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2905. return undefined;
  2906. return Array.isArray(obj) ? obj : [obj];
  2907. };
  2908. // Misc.
  2909. Tools.GetPointerPrefix = function () {
  2910. var eventPrefix = "pointer";
  2911. // Check if hand.js is referenced or if the browser natively supports pointer events
  2912. if (!navigator.pointerEnabled) {
  2913. eventPrefix = "mouse";
  2914. }
  2915. return eventPrefix;
  2916. };
  2917. Tools.QueueNewFrame = function (func) {
  2918. if (window.requestAnimationFrame)
  2919. window.requestAnimationFrame(func);
  2920. else if (window.msRequestAnimationFrame)
  2921. window.msRequestAnimationFrame(func);
  2922. else if (window.webkitRequestAnimationFrame)
  2923. window.webkitRequestAnimationFrame(func);
  2924. else if (window.mozRequestAnimationFrame)
  2925. window.mozRequestAnimationFrame(func);
  2926. else if (window.oRequestAnimationFrame)
  2927. window.oRequestAnimationFrame(func);
  2928. else {
  2929. window.setTimeout(func, 16);
  2930. }
  2931. };
  2932. Tools.RequestFullscreen = function (element) {
  2933. if (element.requestFullscreen)
  2934. element.requestFullscreen();
  2935. else if (element.msRequestFullscreen)
  2936. element.msRequestFullscreen();
  2937. else if (element.webkitRequestFullscreen)
  2938. element.webkitRequestFullscreen();
  2939. else if (element.mozRequestFullScreen)
  2940. element.mozRequestFullScreen();
  2941. };
  2942. Tools.ExitFullscreen = function () {
  2943. if (document.exitFullscreen) {
  2944. document.exitFullscreen();
  2945. }
  2946. else if (document.mozCancelFullScreen) {
  2947. document.mozCancelFullScreen();
  2948. }
  2949. else if (document.webkitCancelFullScreen) {
  2950. document.webkitCancelFullScreen();
  2951. }
  2952. else if (document.msCancelFullScreen) {
  2953. document.msCancelFullScreen();
  2954. }
  2955. };
  2956. // External files
  2957. Tools.CleanUrl = function (url) {
  2958. url = url.replace(/#/mg, "%23");
  2959. return url;
  2960. };
  2961. Tools.LoadImage = function (url, onload, onerror, database) {
  2962. url = Tools.CleanUrl(url);
  2963. var img = new Image();
  2964. if (url.substr(0, 5) !== "data:")
  2965. img.crossOrigin = 'anonymous';
  2966. img.onload = function () {
  2967. onload(img);
  2968. };
  2969. img.onerror = function (err) {
  2970. onerror(img, err);
  2971. };
  2972. var noIndexedDB = function () {
  2973. img.src = url;
  2974. };
  2975. var loadFromIndexedDB = function () {
  2976. database.loadImageFromDB(url, img);
  2977. };
  2978. //ANY database to do!
  2979. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2980. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2981. }
  2982. else {
  2983. if (url.indexOf("file:") === -1) {
  2984. noIndexedDB();
  2985. }
  2986. else {
  2987. try {
  2988. var textureName = url.substring(5);
  2989. var blobURL;
  2990. try {
  2991. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2992. }
  2993. catch (ex) {
  2994. // Chrome doesn't support oneTimeOnly parameter
  2995. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2996. }
  2997. img.src = blobURL;
  2998. }
  2999. catch (e) {
  3000. Tools.Log("Error while trying to load texture: " + textureName);
  3001. img.src = null;
  3002. }
  3003. }
  3004. }
  3005. return img;
  3006. };
  3007. //ANY
  3008. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  3009. url = Tools.CleanUrl(url);
  3010. var noIndexedDB = function () {
  3011. var request = new XMLHttpRequest();
  3012. var loadUrl = Tools.BaseUrl + url;
  3013. request.open('GET', loadUrl, true);
  3014. if (useArrayBuffer) {
  3015. request.responseType = "arraybuffer";
  3016. }
  3017. request.onprogress = progressCallBack;
  3018. request.onreadystatechange = function () {
  3019. if (request.readyState === 4) {
  3020. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  3021. callback(!useArrayBuffer ? request.responseText : request.response);
  3022. }
  3023. else {
  3024. if (onError) {
  3025. onError();
  3026. }
  3027. else {
  3028. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  3029. }
  3030. }
  3031. }
  3032. };
  3033. request.send(null);
  3034. };
  3035. var loadFromIndexedDB = function () {
  3036. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  3037. };
  3038. if (url.indexOf("file:") !== -1) {
  3039. var fileName = url.substring(5);
  3040. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  3041. }
  3042. else {
  3043. // Caching all files
  3044. if (database && database.enableSceneOffline) {
  3045. database.openAsync(loadFromIndexedDB, noIndexedDB);
  3046. }
  3047. else {
  3048. noIndexedDB();
  3049. }
  3050. }
  3051. };
  3052. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  3053. var reader = new FileReader();
  3054. reader.onload = function (e) {
  3055. //target doesn't have result from ts 1.3
  3056. callback(e.target['result']);
  3057. };
  3058. reader.onprogress = progressCallback;
  3059. reader.readAsDataURL(fileToLoad);
  3060. };
  3061. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  3062. var reader = new FileReader();
  3063. reader.onerror = function (e) {
  3064. Tools.Log("Error while reading file: " + fileToLoad.name);
  3065. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  3066. };
  3067. reader.onload = function (e) {
  3068. //target doesn't have result from ts 1.3
  3069. callback(e.target['result']);
  3070. };
  3071. reader.onprogress = progressCallBack;
  3072. if (!useArrayBuffer) {
  3073. // Asynchronous read
  3074. reader.readAsText(fileToLoad);
  3075. }
  3076. else {
  3077. reader.readAsArrayBuffer(fileToLoad);
  3078. }
  3079. };
  3080. // Misc.
  3081. Tools.Clamp = function (value, min, max) {
  3082. if (min === void 0) { min = 0; }
  3083. if (max === void 0) { max = 1; }
  3084. return Math.min(max, Math.max(min, value));
  3085. };
  3086. // Returns -1 when value is a negative number and
  3087. // +1 when value is a positive number.
  3088. Tools.Sign = function (value) {
  3089. value = +value; // convert to a number
  3090. if (value === 0 || isNaN(value))
  3091. return value;
  3092. return value > 0 ? 1 : -1;
  3093. };
  3094. Tools.Format = function (value, decimals) {
  3095. if (decimals === void 0) { decimals = 2; }
  3096. return value.toFixed(decimals);
  3097. };
  3098. Tools.CheckExtends = function (v, min, max) {
  3099. if (v.x < min.x)
  3100. min.x = v.x;
  3101. if (v.y < min.y)
  3102. min.y = v.y;
  3103. if (v.z < min.z)
  3104. min.z = v.z;
  3105. if (v.x > max.x)
  3106. max.x = v.x;
  3107. if (v.y > max.y)
  3108. max.y = v.y;
  3109. if (v.z > max.z)
  3110. max.z = v.z;
  3111. };
  3112. Tools.WithinEpsilon = function (a, b, epsilon) {
  3113. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  3114. var num = a - b;
  3115. return -epsilon <= num && num <= epsilon;
  3116. };
  3117. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  3118. for (var prop in source) {
  3119. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  3120. continue;
  3121. }
  3122. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  3123. continue;
  3124. }
  3125. var sourceValue = source[prop];
  3126. var typeOfSourceValue = typeof sourceValue;
  3127. if (typeOfSourceValue === "function") {
  3128. continue;
  3129. }
  3130. if (typeOfSourceValue === "object") {
  3131. if (sourceValue instanceof Array) {
  3132. destination[prop] = [];
  3133. if (sourceValue.length > 0) {
  3134. if (typeof sourceValue[0] == "object") {
  3135. for (var index = 0; index < sourceValue.length; index++) {
  3136. var clonedValue = cloneValue(sourceValue[index], destination);
  3137. if (destination[prop].indexOf(clonedValue) === -1) {
  3138. destination[prop].push(clonedValue);
  3139. }
  3140. }
  3141. }
  3142. else {
  3143. destination[prop] = sourceValue.slice(0);
  3144. }
  3145. }
  3146. }
  3147. else {
  3148. destination[prop] = cloneValue(sourceValue, destination);
  3149. }
  3150. }
  3151. else {
  3152. destination[prop] = sourceValue;
  3153. }
  3154. }
  3155. };
  3156. Tools.IsEmpty = function (obj) {
  3157. for (var i in obj) {
  3158. return false;
  3159. }
  3160. return true;
  3161. };
  3162. Tools.RegisterTopRootEvents = function (events) {
  3163. for (var index = 0; index < events.length; index++) {
  3164. var event = events[index];
  3165. window.addEventListener(event.name, event.handler, false);
  3166. try {
  3167. if (window.parent) {
  3168. window.parent.addEventListener(event.name, event.handler, false);
  3169. }
  3170. }
  3171. catch (e) {
  3172. }
  3173. }
  3174. };
  3175. Tools.UnregisterTopRootEvents = function (events) {
  3176. for (var index = 0; index < events.length; index++) {
  3177. var event = events[index];
  3178. window.removeEventListener(event.name, event.handler);
  3179. try {
  3180. if (window.parent) {
  3181. window.parent.removeEventListener(event.name, event.handler);
  3182. }
  3183. }
  3184. catch (e) {
  3185. }
  3186. }
  3187. };
  3188. Tools.DumpFramebuffer = function (width, height, engine) {
  3189. // Read the contents of the framebuffer
  3190. var numberOfChannelsByLine = width * 4;
  3191. var halfHeight = height / 2;
  3192. //Reading datas from WebGL
  3193. var data = engine.readPixels(0, 0, width, height);
  3194. for (var i = 0; i < halfHeight; i++) {
  3195. for (var j = 0; j < numberOfChannelsByLine; j++) {
  3196. var currentCell = j + i * numberOfChannelsByLine;
  3197. var targetLine = height - i - 1;
  3198. var targetCell = j + targetLine * numberOfChannelsByLine;
  3199. var temp = data[currentCell];
  3200. data[currentCell] = data[targetCell];
  3201. data[targetCell] = temp;
  3202. }
  3203. }
  3204. // Create a 2D canvas to store the result
  3205. if (!screenshotCanvas) {
  3206. screenshotCanvas = document.createElement('canvas');
  3207. }
  3208. screenshotCanvas.width = width;
  3209. screenshotCanvas.height = height;
  3210. var context = screenshotCanvas.getContext('2d');
  3211. // Copy the pixels to a 2D canvas
  3212. var imageData = context.createImageData(width, height);
  3213. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  3214. var castData = imageData.data;
  3215. castData.set(data);
  3216. context.putImageData(imageData, 0, 0);
  3217. var base64Image = screenshotCanvas.toDataURL();
  3218. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  3219. if (("download" in document.createElement("a"))) {
  3220. var a = window.document.createElement("a");
  3221. a.href = base64Image;
  3222. var date = new Date();
  3223. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  3224. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  3225. window.document.body.appendChild(a);
  3226. a.addEventListener("click", function () {
  3227. a.parentElement.removeChild(a);
  3228. });
  3229. a.click();
  3230. }
  3231. else {
  3232. var newWindow = window.open("");
  3233. var img = newWindow.document.createElement("img");
  3234. img.src = base64Image;
  3235. newWindow.document.body.appendChild(img);
  3236. }
  3237. };
  3238. Tools.CreateScreenshot = function (engine, camera, size) {
  3239. var width;
  3240. var height;
  3241. var scene = camera.getScene();
  3242. var previousCamera = null;
  3243. if (scene.activeCamera !== camera) {
  3244. previousCamera = scene.activeCamera;
  3245. scene.activeCamera = camera;
  3246. }
  3247. //If a precision value is specified
  3248. if (size.precision) {
  3249. width = Math.round(engine.getRenderWidth() * size.precision);
  3250. height = Math.round(width / engine.getAspectRatio(camera));
  3251. size = { width: width, height: height };
  3252. }
  3253. else if (size.width && size.height) {
  3254. width = size.width;
  3255. height = size.height;
  3256. }
  3257. else if (size.width && !size.height) {
  3258. width = size.width;
  3259. height = Math.round(width / engine.getAspectRatio(camera));
  3260. size = { width: width, height: height };
  3261. }
  3262. else if (size.height && !size.width) {
  3263. height = size.height;
  3264. width = Math.round(height * engine.getAspectRatio(camera));
  3265. size = { width: width, height: height };
  3266. }
  3267. else if (!isNaN(size)) {
  3268. height = size;
  3269. width = size;
  3270. }
  3271. else {
  3272. Tools.Error("Invalid 'size' parameter !");
  3273. return;
  3274. }
  3275. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  3276. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  3277. texture.renderList = scene.meshes;
  3278. texture.onAfterRender = function () {
  3279. Tools.DumpFramebuffer(width, height, engine);
  3280. };
  3281. scene.incrementRenderId();
  3282. texture.render(true);
  3283. texture.dispose();
  3284. if (previousCamera) {
  3285. scene.activeCamera = previousCamera;
  3286. }
  3287. };
  3288. // XHR response validator for local file scenario
  3289. Tools.ValidateXHRData = function (xhr, dataType) {
  3290. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  3291. if (dataType === void 0) { dataType = 7; }
  3292. try {
  3293. if (dataType & 1) {
  3294. if (xhr.responseText && xhr.responseText.length > 0) {
  3295. return true;
  3296. }
  3297. else if (dataType === 1) {
  3298. return false;
  3299. }
  3300. }
  3301. if (dataType & 2) {
  3302. // Check header width and height since there is no "TGA" magic number
  3303. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  3304. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  3305. return true;
  3306. }
  3307. else if (dataType === 2) {
  3308. return false;
  3309. }
  3310. }
  3311. if (dataType & 4) {
  3312. // Check for the "DDS" magic number
  3313. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  3314. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  3315. return true;
  3316. }
  3317. else {
  3318. return false;
  3319. }
  3320. }
  3321. }
  3322. catch (e) {
  3323. }
  3324. return false;
  3325. };
  3326. Object.defineProperty(Tools, "NoneLogLevel", {
  3327. get: function () {
  3328. return Tools._NoneLogLevel;
  3329. },
  3330. enumerable: true,
  3331. configurable: true
  3332. });
  3333. Object.defineProperty(Tools, "MessageLogLevel", {
  3334. get: function () {
  3335. return Tools._MessageLogLevel;
  3336. },
  3337. enumerable: true,
  3338. configurable: true
  3339. });
  3340. Object.defineProperty(Tools, "WarningLogLevel", {
  3341. get: function () {
  3342. return Tools._WarningLogLevel;
  3343. },
  3344. enumerable: true,
  3345. configurable: true
  3346. });
  3347. Object.defineProperty(Tools, "ErrorLogLevel", {
  3348. get: function () {
  3349. return Tools._ErrorLogLevel;
  3350. },
  3351. enumerable: true,
  3352. configurable: true
  3353. });
  3354. Object.defineProperty(Tools, "AllLogLevel", {
  3355. get: function () {
  3356. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  3357. },
  3358. enumerable: true,
  3359. configurable: true
  3360. });
  3361. Tools._AddLogEntry = function (entry) {
  3362. Tools._LogCache = entry + Tools._LogCache;
  3363. if (Tools.OnNewCacheEntry) {
  3364. Tools.OnNewCacheEntry(entry);
  3365. }
  3366. };
  3367. Tools._FormatMessage = function (message) {
  3368. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  3369. var date = new Date();
  3370. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  3371. };
  3372. Tools._LogDisabled = function (message) {
  3373. // nothing to do
  3374. };
  3375. Tools._LogEnabled = function (message) {
  3376. var formattedMessage = Tools._FormatMessage(message);
  3377. console.log("BJS - " + formattedMessage);
  3378. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  3379. Tools._AddLogEntry(entry);
  3380. };
  3381. Tools._WarnDisabled = function (message) {
  3382. // nothing to do
  3383. };
  3384. Tools._WarnEnabled = function (message) {
  3385. var formattedMessage = Tools._FormatMessage(message);
  3386. console.warn("BJS - " + formattedMessage);
  3387. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  3388. Tools._AddLogEntry(entry);
  3389. };
  3390. Tools._ErrorDisabled = function (message) {
  3391. // nothing to do
  3392. };
  3393. Tools._ErrorEnabled = function (message) {
  3394. var formattedMessage = Tools._FormatMessage(message);
  3395. console.error("BJS - " + formattedMessage);
  3396. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  3397. Tools._AddLogEntry(entry);
  3398. };
  3399. Object.defineProperty(Tools, "LogCache", {
  3400. get: function () {
  3401. return Tools._LogCache;
  3402. },
  3403. enumerable: true,
  3404. configurable: true
  3405. });
  3406. Object.defineProperty(Tools, "LogLevels", {
  3407. set: function (level) {
  3408. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  3409. Tools.Log = Tools._LogEnabled;
  3410. }
  3411. else {
  3412. Tools.Log = Tools._LogDisabled;
  3413. }
  3414. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  3415. Tools.Warn = Tools._WarnEnabled;
  3416. }
  3417. else {
  3418. Tools.Warn = Tools._WarnDisabled;
  3419. }
  3420. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  3421. Tools.Error = Tools._ErrorEnabled;
  3422. }
  3423. else {
  3424. Tools.Error = Tools._ErrorDisabled;
  3425. }
  3426. },
  3427. enumerable: true,
  3428. configurable: true
  3429. });
  3430. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  3431. get: function () {
  3432. return Tools._PerformanceNoneLogLevel;
  3433. },
  3434. enumerable: true,
  3435. configurable: true
  3436. });
  3437. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  3438. get: function () {
  3439. return Tools._PerformanceUserMarkLogLevel;
  3440. },
  3441. enumerable: true,
  3442. configurable: true
  3443. });
  3444. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  3445. get: function () {
  3446. return Tools._PerformanceConsoleLogLevel;
  3447. },
  3448. enumerable: true,
  3449. configurable: true
  3450. });
  3451. Object.defineProperty(Tools, "PerformanceLogLevel", {
  3452. set: function (level) {
  3453. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  3454. Tools.StartPerformanceCounter = Tools._StartUserMark;
  3455. Tools.EndPerformanceCounter = Tools._EndUserMark;
  3456. return;
  3457. }
  3458. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  3459. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  3460. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  3461. return;
  3462. }
  3463. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3464. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3465. },
  3466. enumerable: true,
  3467. configurable: true
  3468. });
  3469. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  3470. };
  3471. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  3472. };
  3473. Tools._StartUserMark = function (counterName, condition) {
  3474. if (condition === void 0) { condition = true; }
  3475. if (!condition || !Tools._performance.mark) {
  3476. return;
  3477. }
  3478. Tools._performance.mark(counterName + "-Begin");
  3479. };
  3480. Tools._EndUserMark = function (counterName, condition) {
  3481. if (condition === void 0) { condition = true; }
  3482. if (!condition || !Tools._performance.mark) {
  3483. return;
  3484. }
  3485. Tools._performance.mark(counterName + "-End");
  3486. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  3487. };
  3488. Tools._StartPerformanceConsole = function (counterName, condition) {
  3489. if (condition === void 0) { condition = true; }
  3490. if (!condition) {
  3491. return;
  3492. }
  3493. Tools._StartUserMark(counterName, condition);
  3494. if (console.time) {
  3495. console.time(counterName);
  3496. }
  3497. };
  3498. Tools._EndPerformanceConsole = function (counterName, condition) {
  3499. if (condition === void 0) { condition = true; }
  3500. if (!condition) {
  3501. return;
  3502. }
  3503. Tools._EndUserMark(counterName, condition);
  3504. if (console.time) {
  3505. console.timeEnd(counterName);
  3506. }
  3507. };
  3508. Object.defineProperty(Tools, "Now", {
  3509. get: function () {
  3510. if (window.performance && window.performance.now) {
  3511. return window.performance.now();
  3512. }
  3513. return new Date().getTime();
  3514. },
  3515. enumerable: true,
  3516. configurable: true
  3517. });
  3518. // Deprecated
  3519. Tools.GetFps = function () {
  3520. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  3521. return 0;
  3522. };
  3523. Tools.BaseUrl = "";
  3524. Tools.GetExponantOfTwo = function (value, max) {
  3525. var count = 1;
  3526. do {
  3527. count *= 2;
  3528. } while (count < value);
  3529. if (count > max)
  3530. count = max;
  3531. return count;
  3532. };
  3533. // Logs
  3534. Tools._NoneLogLevel = 0;
  3535. Tools._MessageLogLevel = 1;
  3536. Tools._WarningLogLevel = 2;
  3537. Tools._ErrorLogLevel = 4;
  3538. Tools._LogCache = "";
  3539. Tools.Log = Tools._LogEnabled;
  3540. Tools.Warn = Tools._WarnEnabled;
  3541. Tools.Error = Tools._ErrorEnabled;
  3542. // Performances
  3543. Tools._PerformanceNoneLogLevel = 0;
  3544. Tools._PerformanceUserMarkLogLevel = 1;
  3545. Tools._PerformanceConsoleLogLevel = 2;
  3546. Tools._performance = window.performance;
  3547. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3548. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3549. return Tools;
  3550. })();
  3551. BABYLON.Tools = Tools;
  3552. /**
  3553. * An implementation of a loop for asynchronous functions.
  3554. */
  3555. var AsyncLoop = (function () {
  3556. /**
  3557. * Constroctor.
  3558. * @param iterations the number of iterations.
  3559. * @param _fn the function to run each iteration
  3560. * @param _successCallback the callback that will be called upon succesful execution
  3561. * @param offset starting offset.
  3562. */
  3563. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3564. if (offset === void 0) { offset = 0; }
  3565. this.iterations = iterations;
  3566. this._fn = _fn;
  3567. this._successCallback = _successCallback;
  3568. this.index = offset - 1;
  3569. this._done = false;
  3570. }
  3571. /**
  3572. * Execute the next iteration. Must be called after the last iteration was finished.
  3573. */
  3574. AsyncLoop.prototype.executeNext = function () {
  3575. if (!this._done) {
  3576. if (this.index + 1 < this.iterations) {
  3577. ++this.index;
  3578. this._fn(this);
  3579. }
  3580. else {
  3581. this.breakLoop();
  3582. }
  3583. }
  3584. };
  3585. /**
  3586. * Break the loop and run the success callback.
  3587. */
  3588. AsyncLoop.prototype.breakLoop = function () {
  3589. this._done = true;
  3590. this._successCallback();
  3591. };
  3592. /**
  3593. * Helper function
  3594. */
  3595. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3596. if (offset === void 0) { offset = 0; }
  3597. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3598. loop.executeNext();
  3599. return loop;
  3600. };
  3601. /**
  3602. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3603. * @param iterations total number of iterations
  3604. * @param syncedIterations number of synchronous iterations in each async iteration.
  3605. * @param fn the function to call each iteration.
  3606. * @param callback a success call back that will be called when iterating stops.
  3607. * @param breakFunction a break condition (optional)
  3608. * @param timeout timeout settings for the setTimeout function. default - 0.
  3609. * @constructor
  3610. */
  3611. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3612. if (timeout === void 0) { timeout = 0; }
  3613. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3614. if (breakFunction && breakFunction())
  3615. loop.breakLoop();
  3616. else {
  3617. setTimeout(function () {
  3618. for (var i = 0; i < syncedIterations; ++i) {
  3619. var iteration = (loop.index * syncedIterations) + i;
  3620. if (iteration >= iterations)
  3621. break;
  3622. fn(iteration);
  3623. if (breakFunction && breakFunction()) {
  3624. loop.breakLoop();
  3625. break;
  3626. }
  3627. }
  3628. loop.executeNext();
  3629. }, timeout);
  3630. }
  3631. }, callback);
  3632. };
  3633. return AsyncLoop;
  3634. })();
  3635. BABYLON.AsyncLoop = AsyncLoop;
  3636. })(BABYLON || (BABYLON = {}));
  3637. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3638. (function (BABYLON) {
  3639. var _DepthCullingState = (function () {
  3640. function _DepthCullingState() {
  3641. this._isDepthTestDirty = false;
  3642. this._isDepthMaskDirty = false;
  3643. this._isDepthFuncDirty = false;
  3644. this._isCullFaceDirty = false;
  3645. this._isCullDirty = false;
  3646. this._isZOffsetDirty = false;
  3647. }
  3648. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3649. get: function () {
  3650. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  3651. },
  3652. enumerable: true,
  3653. configurable: true
  3654. });
  3655. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  3656. get: function () {
  3657. return this._zOffset;
  3658. },
  3659. set: function (value) {
  3660. if (this._zOffset === value) {
  3661. return;
  3662. }
  3663. this._zOffset = value;
  3664. this._isZOffsetDirty = true;
  3665. },
  3666. enumerable: true,
  3667. configurable: true
  3668. });
  3669. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3670. get: function () {
  3671. return this._cullFace;
  3672. },
  3673. set: function (value) {
  3674. if (this._cullFace === value) {
  3675. return;
  3676. }
  3677. this._cullFace = value;
  3678. this._isCullFaceDirty = true;
  3679. },
  3680. enumerable: true,
  3681. configurable: true
  3682. });
  3683. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3684. get: function () {
  3685. return this._cull;
  3686. },
  3687. set: function (value) {
  3688. if (this._cull === value) {
  3689. return;
  3690. }
  3691. this._cull = value;
  3692. this._isCullDirty = true;
  3693. },
  3694. enumerable: true,
  3695. configurable: true
  3696. });
  3697. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3698. get: function () {
  3699. return this._depthFunc;
  3700. },
  3701. set: function (value) {
  3702. if (this._depthFunc === value) {
  3703. return;
  3704. }
  3705. this._depthFunc = value;
  3706. this._isDepthFuncDirty = true;
  3707. },
  3708. enumerable: true,
  3709. configurable: true
  3710. });
  3711. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3712. get: function () {
  3713. return this._depthMask;
  3714. },
  3715. set: function (value) {
  3716. if (this._depthMask === value) {
  3717. return;
  3718. }
  3719. this._depthMask = value;
  3720. this._isDepthMaskDirty = true;
  3721. },
  3722. enumerable: true,
  3723. configurable: true
  3724. });
  3725. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3726. get: function () {
  3727. return this._depthTest;
  3728. },
  3729. set: function (value) {
  3730. if (this._depthTest === value) {
  3731. return;
  3732. }
  3733. this._depthTest = value;
  3734. this._isDepthTestDirty = true;
  3735. },
  3736. enumerable: true,
  3737. configurable: true
  3738. });
  3739. _DepthCullingState.prototype.reset = function () {
  3740. this._depthMask = true;
  3741. this._depthTest = true;
  3742. this._depthFunc = null;
  3743. this._cull = null;
  3744. this._cullFace = null;
  3745. this._zOffset = 0;
  3746. this._isDepthTestDirty = true;
  3747. this._isDepthMaskDirty = true;
  3748. this._isDepthFuncDirty = false;
  3749. this._isCullFaceDirty = false;
  3750. this._isCullDirty = false;
  3751. this._isZOffsetDirty = false;
  3752. };
  3753. _DepthCullingState.prototype.apply = function (gl) {
  3754. if (!this.isDirty) {
  3755. return;
  3756. }
  3757. // Cull
  3758. if (this._isCullDirty) {
  3759. if (this.cull) {
  3760. gl.enable(gl.CULL_FACE);
  3761. }
  3762. else {
  3763. gl.disable(gl.CULL_FACE);
  3764. }
  3765. this._isCullDirty = false;
  3766. }
  3767. // Cull face
  3768. if (this._isCullFaceDirty) {
  3769. gl.cullFace(this.cullFace);
  3770. this._isCullFaceDirty = false;
  3771. }
  3772. // Depth mask
  3773. if (this._isDepthMaskDirty) {
  3774. gl.depthMask(this.depthMask);
  3775. this._isDepthMaskDirty = false;
  3776. }
  3777. // Depth test
  3778. if (this._isDepthTestDirty) {
  3779. if (this.depthTest) {
  3780. gl.enable(gl.DEPTH_TEST);
  3781. }
  3782. else {
  3783. gl.disable(gl.DEPTH_TEST);
  3784. }
  3785. this._isDepthTestDirty = false;
  3786. }
  3787. // Depth func
  3788. if (this._isDepthFuncDirty) {
  3789. gl.depthFunc(this.depthFunc);
  3790. this._isDepthFuncDirty = false;
  3791. }
  3792. // zOffset
  3793. if (this._isZOffsetDirty) {
  3794. if (this.zOffset) {
  3795. gl.enable(gl.POLYGON_OFFSET_FILL);
  3796. gl.polygonOffset(this.zOffset, 0);
  3797. }
  3798. else {
  3799. gl.disable(gl.POLYGON_OFFSET_FILL);
  3800. }
  3801. this._isZOffsetDirty = false;
  3802. }
  3803. };
  3804. return _DepthCullingState;
  3805. })();
  3806. BABYLON._DepthCullingState = _DepthCullingState;
  3807. var _AlphaState = (function () {
  3808. function _AlphaState() {
  3809. this._isAlphaBlendDirty = false;
  3810. this._isBlendFunctionParametersDirty = false;
  3811. this._alphaBlend = false;
  3812. this._blendFunctionParameters = new Array(4);
  3813. }
  3814. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3815. get: function () {
  3816. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3817. },
  3818. enumerable: true,
  3819. configurable: true
  3820. });
  3821. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3822. get: function () {
  3823. return this._alphaBlend;
  3824. },
  3825. set: function (value) {
  3826. if (this._alphaBlend === value) {
  3827. return;
  3828. }
  3829. this._alphaBlend = value;
  3830. this._isAlphaBlendDirty = true;
  3831. },
  3832. enumerable: true,
  3833. configurable: true
  3834. });
  3835. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3836. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3837. return;
  3838. }
  3839. this._blendFunctionParameters[0] = value0;
  3840. this._blendFunctionParameters[1] = value1;
  3841. this._blendFunctionParameters[2] = value2;
  3842. this._blendFunctionParameters[3] = value3;
  3843. this._isBlendFunctionParametersDirty = true;
  3844. };
  3845. _AlphaState.prototype.reset = function () {
  3846. this._alphaBlend = false;
  3847. this._blendFunctionParameters[0] = null;
  3848. this._blendFunctionParameters[1] = null;
  3849. this._blendFunctionParameters[2] = null;
  3850. this._blendFunctionParameters[3] = null;
  3851. this._isAlphaBlendDirty = true;
  3852. this._isBlendFunctionParametersDirty = false;
  3853. };
  3854. _AlphaState.prototype.apply = function (gl) {
  3855. if (!this.isDirty) {
  3856. return;
  3857. }
  3858. // Alpha blend
  3859. if (this._isAlphaBlendDirty) {
  3860. if (this._alphaBlend) {
  3861. gl.enable(gl.BLEND);
  3862. }
  3863. else {
  3864. gl.disable(gl.BLEND);
  3865. }
  3866. this._isAlphaBlendDirty = false;
  3867. }
  3868. // Alpha function
  3869. if (this._isBlendFunctionParametersDirty) {
  3870. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3871. this._isBlendFunctionParametersDirty = false;
  3872. }
  3873. };
  3874. return _AlphaState;
  3875. })();
  3876. BABYLON._AlphaState = _AlphaState;
  3877. var compileShader = function (gl, source, type, defines) {
  3878. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3879. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3880. gl.compileShader(shader);
  3881. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3882. throw new Error(gl.getShaderInfoLog(shader));
  3883. }
  3884. return shader;
  3885. };
  3886. var getWebGLTextureType = function (gl, type) {
  3887. var textureType = gl.UNSIGNED_BYTE;
  3888. if (type === Engine.TEXTURETYPE_FLOAT)
  3889. textureType = gl.FLOAT;
  3890. return textureType;
  3891. };
  3892. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3893. var magFilter = gl.NEAREST;
  3894. var minFilter = gl.NEAREST;
  3895. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3896. magFilter = gl.LINEAR;
  3897. if (generateMipMaps) {
  3898. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3899. }
  3900. else {
  3901. minFilter = gl.LINEAR;
  3902. }
  3903. }
  3904. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3905. magFilter = gl.LINEAR;
  3906. if (generateMipMaps) {
  3907. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3908. }
  3909. else {
  3910. minFilter = gl.LINEAR;
  3911. }
  3912. }
  3913. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3914. magFilter = gl.NEAREST;
  3915. if (generateMipMaps) {
  3916. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3917. }
  3918. else {
  3919. minFilter = gl.NEAREST;
  3920. }
  3921. }
  3922. return {
  3923. min: minFilter,
  3924. mag: magFilter
  3925. };
  3926. };
  3927. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3928. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3929. var engine = scene.getEngine();
  3930. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3931. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3932. gl.bindTexture(gl.TEXTURE_2D, texture);
  3933. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3934. processFunction(potWidth, potHeight);
  3935. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3936. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3937. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3938. if (!noMipmap && !isCompressed) {
  3939. gl.generateMipmap(gl.TEXTURE_2D);
  3940. }
  3941. gl.bindTexture(gl.TEXTURE_2D, null);
  3942. engine._activeTexturesCache = [];
  3943. texture._baseWidth = width;
  3944. texture._baseHeight = height;
  3945. texture._width = potWidth;
  3946. texture._height = potHeight;
  3947. texture.isReady = true;
  3948. texture.samplingMode = samplingMode;
  3949. scene._removePendingData(texture);
  3950. };
  3951. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3952. var onload = function () {
  3953. loadedImages[index] = img;
  3954. loadedImages._internalCount++;
  3955. scene._removePendingData(img);
  3956. if (loadedImages._internalCount === 6) {
  3957. onfinish(loadedImages);
  3958. }
  3959. };
  3960. var onerror = function () {
  3961. scene._removePendingData(img);
  3962. };
  3963. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3964. scene._addPendingData(img);
  3965. };
  3966. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3967. var loadedImages = [];
  3968. loadedImages._internalCount = 0;
  3969. for (var index = 0; index < 6; index++) {
  3970. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3971. }
  3972. };
  3973. var EngineCapabilities = (function () {
  3974. function EngineCapabilities() {
  3975. }
  3976. return EngineCapabilities;
  3977. })();
  3978. BABYLON.EngineCapabilities = EngineCapabilities;
  3979. /**
  3980. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  3981. */
  3982. var Engine = (function () {
  3983. /**
  3984. * @constructor
  3985. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  3986. * @param {boolean} [antialias] - enable antialias
  3987. * @param options - further options to be sent to the getContext function
  3988. */
  3989. function Engine(canvas, antialias, options) {
  3990. var _this = this;
  3991. // Public members
  3992. this.isFullscreen = false;
  3993. this.isPointerLock = false;
  3994. this.cullBackFaces = true;
  3995. this.renderEvenInBackground = true;
  3996. this.scenes = new Array();
  3997. this._windowIsBackground = false;
  3998. this._loadingDivBackgroundColor = "black";
  3999. this._drawCalls = 0;
  4000. this._renderingQueueLaunched = false;
  4001. this._activeRenderLoops = [];
  4002. // FPS
  4003. this.fpsRange = 60;
  4004. this.previousFramesDuration = [];
  4005. this.fps = 60;
  4006. this.deltaTime = 0;
  4007. // States
  4008. this._depthCullingState = new _DepthCullingState();
  4009. this._alphaState = new _AlphaState();
  4010. this._alphaMode = Engine.ALPHA_DISABLE;
  4011. // Cache
  4012. this._loadedTexturesCache = new Array();
  4013. this._activeTexturesCache = new Array();
  4014. this._compiledEffects = {};
  4015. this._uintIndicesCurrentlySet = false;
  4016. this._renderingCanvas = canvas;
  4017. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4018. options = options || {};
  4019. options.antialias = antialias;
  4020. try {
  4021. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  4022. }
  4023. catch (e) {
  4024. throw new Error("WebGL not supported");
  4025. }
  4026. if (!this._gl) {
  4027. throw new Error("WebGL not supported");
  4028. }
  4029. this._onBlur = function () {
  4030. _this._windowIsBackground = true;
  4031. };
  4032. this._onFocus = function () {
  4033. _this._windowIsBackground = false;
  4034. };
  4035. window.addEventListener("blur", this._onBlur);
  4036. window.addEventListener("focus", this._onFocus);
  4037. // Viewport
  4038. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  4039. this.resize();
  4040. // Caps
  4041. this._caps = new EngineCapabilities();
  4042. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  4043. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  4044. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  4045. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  4046. // Infos
  4047. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  4048. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  4049. if (rendererInfo != null) {
  4050. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  4051. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  4052. }
  4053. if (!this._glVendor) {
  4054. this._glVendor = "Unknown vendor";
  4055. }
  4056. if (!this._glRenderer) {
  4057. this._glRenderer = "Unknown renderer";
  4058. }
  4059. // Extensions
  4060. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  4061. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  4062. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  4063. 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');
  4064. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  4065. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  4066. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  4067. // Depth buffer
  4068. this.setDepthBuffer(true);
  4069. this.setDepthFunctionToLessOrEqual();
  4070. this.setDepthWrite(true);
  4071. // Fullscreen
  4072. this._onFullscreenChange = function () {
  4073. if (document.fullscreen !== undefined) {
  4074. _this.isFullscreen = document.fullscreen;
  4075. }
  4076. else if (document.mozFullScreen !== undefined) {
  4077. _this.isFullscreen = document.mozFullScreen;
  4078. }
  4079. else if (document.webkitIsFullScreen !== undefined) {
  4080. _this.isFullscreen = document.webkitIsFullScreen;
  4081. }
  4082. else if (document.msIsFullScreen !== undefined) {
  4083. _this.isFullscreen = document.msIsFullScreen;
  4084. }
  4085. // Pointer lock
  4086. if (_this.isFullscreen && _this._pointerLockRequested) {
  4087. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  4088. if (canvas.requestPointerLock) {
  4089. canvas.requestPointerLock();
  4090. }
  4091. }
  4092. };
  4093. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  4094. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  4095. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  4096. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  4097. // Pointer lock
  4098. this._onPointerLockChange = function () {
  4099. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  4100. };
  4101. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  4102. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  4103. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  4104. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  4105. if (!Engine.audioEngine) {
  4106. Engine.audioEngine = new BABYLON.AudioEngine();
  4107. }
  4108. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  4109. }
  4110. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  4111. get: function () {
  4112. return Engine._ALPHA_DISABLE;
  4113. },
  4114. enumerable: true,
  4115. configurable: true
  4116. });
  4117. Object.defineProperty(Engine, "ALPHA_ADD", {
  4118. get: function () {
  4119. return Engine._ALPHA_ADD;
  4120. },
  4121. enumerable: true,
  4122. configurable: true
  4123. });
  4124. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  4125. get: function () {
  4126. return Engine._ALPHA_COMBINE;
  4127. },
  4128. enumerable: true,
  4129. configurable: true
  4130. });
  4131. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  4132. get: function () {
  4133. return Engine._DELAYLOADSTATE_NONE;
  4134. },
  4135. enumerable: true,
  4136. configurable: true
  4137. });
  4138. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  4139. get: function () {
  4140. return Engine._DELAYLOADSTATE_LOADED;
  4141. },
  4142. enumerable: true,
  4143. configurable: true
  4144. });
  4145. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  4146. get: function () {
  4147. return Engine._DELAYLOADSTATE_LOADING;
  4148. },
  4149. enumerable: true,
  4150. configurable: true
  4151. });
  4152. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  4153. get: function () {
  4154. return Engine._DELAYLOADSTATE_NOTLOADED;
  4155. },
  4156. enumerable: true,
  4157. configurable: true
  4158. });
  4159. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  4160. get: function () {
  4161. return Engine._TEXTUREFORMAT_ALPHA;
  4162. },
  4163. enumerable: true,
  4164. configurable: true
  4165. });
  4166. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  4167. get: function () {
  4168. return Engine._TEXTUREFORMAT_LUMINANCE;
  4169. },
  4170. enumerable: true,
  4171. configurable: true
  4172. });
  4173. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  4174. get: function () {
  4175. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  4176. },
  4177. enumerable: true,
  4178. configurable: true
  4179. });
  4180. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  4181. get: function () {
  4182. return Engine._TEXTUREFORMAT_RGB;
  4183. },
  4184. enumerable: true,
  4185. configurable: true
  4186. });
  4187. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  4188. get: function () {
  4189. return Engine._TEXTUREFORMAT_RGBA;
  4190. },
  4191. enumerable: true,
  4192. configurable: true
  4193. });
  4194. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  4195. get: function () {
  4196. return Engine._TEXTURETYPE_UNSIGNED_INT;
  4197. },
  4198. enumerable: true,
  4199. configurable: true
  4200. });
  4201. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  4202. get: function () {
  4203. return Engine._TEXTURETYPE_FLOAT;
  4204. },
  4205. enumerable: true,
  4206. configurable: true
  4207. });
  4208. Object.defineProperty(Engine, "Version", {
  4209. get: function () {
  4210. return "2.1.0 alpha";
  4211. },
  4212. enumerable: true,
  4213. configurable: true
  4214. });
  4215. Engine.prototype._prepareWorkingCanvas = function () {
  4216. if (this._workingCanvas) {
  4217. return;
  4218. }
  4219. this._workingCanvas = document.createElement("canvas");
  4220. this._workingContext = this._workingCanvas.getContext("2d");
  4221. };
  4222. Engine.prototype.getGlInfo = function () {
  4223. return {
  4224. vendor: this._glVendor,
  4225. renderer: this._glRenderer,
  4226. version: this._glVersion
  4227. };
  4228. };
  4229. Engine.prototype.getAspectRatio = function (camera) {
  4230. var viewport = camera.viewport;
  4231. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  4232. };
  4233. Engine.prototype.getRenderWidth = function () {
  4234. if (this._currentRenderTarget) {
  4235. return this._currentRenderTarget._width;
  4236. }
  4237. return this._renderingCanvas.width;
  4238. };
  4239. Engine.prototype.getRenderHeight = function () {
  4240. if (this._currentRenderTarget) {
  4241. return this._currentRenderTarget._height;
  4242. }
  4243. return this._renderingCanvas.height;
  4244. };
  4245. Engine.prototype.getRenderingCanvas = function () {
  4246. return this._renderingCanvas;
  4247. };
  4248. Engine.prototype.getRenderingCanvasClientRect = function () {
  4249. return this._renderingCanvas.getBoundingClientRect();
  4250. };
  4251. Engine.prototype.setHardwareScalingLevel = function (level) {
  4252. this._hardwareScalingLevel = level;
  4253. this.resize();
  4254. };
  4255. Engine.prototype.getHardwareScalingLevel = function () {
  4256. return this._hardwareScalingLevel;
  4257. };
  4258. Engine.prototype.getLoadedTexturesCache = function () {
  4259. return this._loadedTexturesCache;
  4260. };
  4261. Engine.prototype.getCaps = function () {
  4262. return this._caps;
  4263. };
  4264. Object.defineProperty(Engine.prototype, "drawCalls", {
  4265. get: function () {
  4266. return this._drawCalls;
  4267. },
  4268. enumerable: true,
  4269. configurable: true
  4270. });
  4271. // Methods
  4272. Engine.prototype.resetDrawCalls = function () {
  4273. this._drawCalls = 0;
  4274. };
  4275. Engine.prototype.setDepthFunctionToGreater = function () {
  4276. this._depthCullingState.depthFunc = this._gl.GREATER;
  4277. };
  4278. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  4279. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  4280. };
  4281. Engine.prototype.setDepthFunctionToLess = function () {
  4282. this._depthCullingState.depthFunc = this._gl.LESS;
  4283. };
  4284. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  4285. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  4286. };
  4287. /**
  4288. * stop executing a render loop function and remove it from the execution array
  4289. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  4290. */
  4291. Engine.prototype.stopRenderLoop = function (renderFunction) {
  4292. if (!renderFunction) {
  4293. this._activeRenderLoops = [];
  4294. return;
  4295. }
  4296. var index = this._activeRenderLoops.indexOf(renderFunction);
  4297. if (index >= 0) {
  4298. this._activeRenderLoops.splice(index, 1);
  4299. }
  4300. };
  4301. Engine.prototype._renderLoop = function () {
  4302. var _this = this;
  4303. var shouldRender = true;
  4304. if (!this.renderEvenInBackground && this._windowIsBackground) {
  4305. shouldRender = false;
  4306. }
  4307. if (shouldRender) {
  4308. // Start new frame
  4309. this.beginFrame();
  4310. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  4311. var renderFunction = this._activeRenderLoops[index];
  4312. renderFunction();
  4313. }
  4314. // Present
  4315. this.endFrame();
  4316. }
  4317. if (this._activeRenderLoops.length > 0) {
  4318. // Register new frame
  4319. BABYLON.Tools.QueueNewFrame(function () {
  4320. _this._renderLoop();
  4321. });
  4322. }
  4323. else {
  4324. this._renderingQueueLaunched = false;
  4325. }
  4326. };
  4327. /**
  4328. * Register and execute a render loop. The engine can have more than one render function.
  4329. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  4330. * @example
  4331. * engine.runRenderLoop(function () {
  4332. * scene.render()
  4333. * })
  4334. */
  4335. Engine.prototype.runRenderLoop = function (renderFunction) {
  4336. var _this = this;
  4337. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  4338. return;
  4339. }
  4340. this._activeRenderLoops.push(renderFunction);
  4341. if (!this._renderingQueueLaunched) {
  4342. this._renderingQueueLaunched = true;
  4343. BABYLON.Tools.QueueNewFrame(function () {
  4344. _this._renderLoop();
  4345. });
  4346. }
  4347. };
  4348. /**
  4349. * Toggle full screen mode.
  4350. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  4351. */
  4352. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  4353. if (this.isFullscreen) {
  4354. BABYLON.Tools.ExitFullscreen();
  4355. }
  4356. else {
  4357. this._pointerLockRequested = requestPointerLock;
  4358. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  4359. }
  4360. };
  4361. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  4362. this.applyStates();
  4363. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  4364. if (this._depthCullingState.depthMask) {
  4365. this._gl.clearDepth(1.0);
  4366. }
  4367. var mode = 0;
  4368. if (backBuffer)
  4369. mode |= this._gl.COLOR_BUFFER_BIT;
  4370. if (depthStencil && this._depthCullingState.depthMask)
  4371. mode |= this._gl.DEPTH_BUFFER_BIT;
  4372. this._gl.clear(mode);
  4373. };
  4374. /**
  4375. * Set the WebGL's viewport
  4376. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  4377. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  4378. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  4379. */
  4380. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  4381. var width = requiredWidth || this._renderingCanvas.width;
  4382. var height = requiredHeight || this._renderingCanvas.height;
  4383. var x = viewport.x || 0;
  4384. var y = viewport.y || 0;
  4385. this._cachedViewport = viewport;
  4386. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  4387. };
  4388. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  4389. this._cachedViewport = null;
  4390. this._gl.viewport(x, y, width, height);
  4391. };
  4392. Engine.prototype.beginFrame = function () {
  4393. this._measureFps();
  4394. };
  4395. Engine.prototype.endFrame = function () {
  4396. //this.flushFramebuffer();
  4397. };
  4398. /**
  4399. * resize the view according to the canvas' size.
  4400. * @example
  4401. * window.addEventListener("resize", function () {
  4402. * engine.resize();
  4403. * });
  4404. */
  4405. Engine.prototype.resize = function () {
  4406. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  4407. };
  4408. /**
  4409. * force a specific size of the canvas
  4410. * @param {number} width - the new canvas' width
  4411. * @param {number} height - the new canvas' height
  4412. */
  4413. Engine.prototype.setSize = function (width, height) {
  4414. this._renderingCanvas.width = width;
  4415. this._renderingCanvas.height = height;
  4416. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4417. };
  4418. Engine.prototype.bindFramebuffer = function (texture) {
  4419. this._currentRenderTarget = texture;
  4420. var gl = this._gl;
  4421. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  4422. this._gl.viewport(0, 0, texture._width, texture._height);
  4423. this.wipeCaches();
  4424. };
  4425. Engine.prototype.unBindFramebuffer = function (texture) {
  4426. this._currentRenderTarget = null;
  4427. if (texture.generateMipMaps) {
  4428. var gl = this._gl;
  4429. gl.bindTexture(gl.TEXTURE_2D, texture);
  4430. gl.generateMipmap(gl.TEXTURE_2D);
  4431. gl.bindTexture(gl.TEXTURE_2D, null);
  4432. }
  4433. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4434. };
  4435. Engine.prototype.flushFramebuffer = function () {
  4436. this._gl.flush();
  4437. };
  4438. Engine.prototype.restoreDefaultFramebuffer = function () {
  4439. this._currentRenderTarget = null;
  4440. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4441. this.setViewport(this._cachedViewport);
  4442. this.wipeCaches();
  4443. };
  4444. // VBOs
  4445. Engine.prototype._resetVertexBufferBinding = function () {
  4446. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  4447. this._cachedVertexBuffers = null;
  4448. };
  4449. Engine.prototype.createVertexBuffer = function (vertices) {
  4450. var vbo = this._gl.createBuffer();
  4451. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4452. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  4453. this._resetVertexBufferBinding();
  4454. vbo.references = 1;
  4455. return vbo;
  4456. };
  4457. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  4458. var vbo = this._gl.createBuffer();
  4459. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4460. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4461. this._resetVertexBufferBinding();
  4462. vbo.references = 1;
  4463. return vbo;
  4464. };
  4465. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  4466. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4467. if (offset === undefined) {
  4468. offset = 0;
  4469. }
  4470. if (vertices instanceof Float32Array) {
  4471. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  4472. }
  4473. else {
  4474. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  4475. }
  4476. this._resetVertexBufferBinding();
  4477. };
  4478. Engine.prototype._resetIndexBufferBinding = function () {
  4479. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  4480. this._cachedIndexBuffer = null;
  4481. };
  4482. Engine.prototype.createIndexBuffer = function (indices) {
  4483. var vbo = this._gl.createBuffer();
  4484. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  4485. // Check for 32 bits indices
  4486. var arrayBuffer;
  4487. var need32Bits = false;
  4488. if (this._caps.uintIndices) {
  4489. for (var index = 0; index < indices.length; index++) {
  4490. if (indices[index] > 65535) {
  4491. need32Bits = true;
  4492. break;
  4493. }
  4494. }
  4495. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  4496. }
  4497. else {
  4498. arrayBuffer = new Uint16Array(indices);
  4499. }
  4500. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  4501. this._resetIndexBufferBinding();
  4502. vbo.references = 1;
  4503. vbo.is32Bits = need32Bits;
  4504. return vbo;
  4505. };
  4506. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  4507. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  4508. this._cachedVertexBuffers = vertexBuffer;
  4509. this._cachedEffectForVertexBuffers = effect;
  4510. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4511. var offset = 0;
  4512. for (var index = 0; index < vertexDeclaration.length; index++) {
  4513. var order = effect.getAttributeLocation(index);
  4514. if (order >= 0) {
  4515. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  4516. }
  4517. offset += vertexDeclaration[index] * 4;
  4518. }
  4519. }
  4520. if (this._cachedIndexBuffer !== indexBuffer) {
  4521. this._cachedIndexBuffer = indexBuffer;
  4522. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4523. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4524. }
  4525. };
  4526. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  4527. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  4528. this._cachedVertexBuffers = vertexBuffers;
  4529. this._cachedEffectForVertexBuffers = effect;
  4530. var attributes = effect.getAttributesNames();
  4531. for (var index = 0; index < attributes.length; index++) {
  4532. var order = effect.getAttributeLocation(index);
  4533. if (order >= 0) {
  4534. var vertexBuffer = vertexBuffers[attributes[index]];
  4535. if (!vertexBuffer) {
  4536. continue;
  4537. }
  4538. var stride = vertexBuffer.getStrideSize();
  4539. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  4540. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  4541. }
  4542. }
  4543. }
  4544. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  4545. this._cachedIndexBuffer = indexBuffer;
  4546. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4547. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4548. }
  4549. };
  4550. Engine.prototype._releaseBuffer = function (buffer) {
  4551. buffer.references--;
  4552. if (buffer.references === 0) {
  4553. this._gl.deleteBuffer(buffer);
  4554. return true;
  4555. }
  4556. return false;
  4557. };
  4558. Engine.prototype.createInstancesBuffer = function (capacity) {
  4559. var buffer = this._gl.createBuffer();
  4560. buffer.capacity = capacity;
  4561. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  4562. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4563. return buffer;
  4564. };
  4565. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  4566. this._gl.deleteBuffer(buffer);
  4567. };
  4568. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  4569. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4570. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  4571. for (var index = 0; index < 4; index++) {
  4572. var offsetLocation = offsetLocations[index];
  4573. this._gl.enableVertexAttribArray(offsetLocation);
  4574. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  4575. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  4576. }
  4577. };
  4578. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  4579. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4580. for (var index = 0; index < 4; index++) {
  4581. var offsetLocation = offsetLocations[index];
  4582. this._gl.disableVertexAttribArray(offsetLocation);
  4583. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4584. }
  4585. };
  4586. Engine.prototype.applyStates = function () {
  4587. this._depthCullingState.apply(this._gl);
  4588. this._alphaState.apply(this._gl);
  4589. };
  4590. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4591. // Apply states
  4592. this.applyStates();
  4593. this._drawCalls++;
  4594. // Render
  4595. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4596. if (instancesCount) {
  4597. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4598. return;
  4599. }
  4600. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4601. };
  4602. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4603. // Apply states
  4604. this.applyStates();
  4605. this._drawCalls++;
  4606. if (instancesCount) {
  4607. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4608. return;
  4609. }
  4610. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4611. };
  4612. // Shaders
  4613. Engine.prototype._releaseEffect = function (effect) {
  4614. if (this._compiledEffects[effect._key]) {
  4615. delete this._compiledEffects[effect._key];
  4616. if (effect.getProgram()) {
  4617. this._gl.deleteProgram(effect.getProgram());
  4618. }
  4619. }
  4620. };
  4621. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4622. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4623. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4624. var name = vertex + "+" + fragment + "@" + defines;
  4625. if (this._compiledEffects[name]) {
  4626. return this._compiledEffects[name];
  4627. }
  4628. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4629. effect._key = name;
  4630. this._compiledEffects[name] = effect;
  4631. return effect;
  4632. };
  4633. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4634. if (uniformsNames === void 0) { uniformsNames = []; }
  4635. if (samplers === void 0) { samplers = []; }
  4636. if (defines === void 0) { defines = ""; }
  4637. return this.createEffect({
  4638. vertex: "particles",
  4639. fragmentElement: fragmentName
  4640. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4641. };
  4642. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4643. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4644. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4645. var shaderProgram = this._gl.createProgram();
  4646. this._gl.attachShader(shaderProgram, vertexShader);
  4647. this._gl.attachShader(shaderProgram, fragmentShader);
  4648. this._gl.linkProgram(shaderProgram);
  4649. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4650. if (!linked) {
  4651. var error = this._gl.getProgramInfoLog(shaderProgram);
  4652. if (error) {
  4653. throw new Error(error);
  4654. }
  4655. }
  4656. this._gl.deleteShader(vertexShader);
  4657. this._gl.deleteShader(fragmentShader);
  4658. return shaderProgram;
  4659. };
  4660. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4661. var results = [];
  4662. for (var index = 0; index < uniformsNames.length; index++) {
  4663. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4664. }
  4665. return results;
  4666. };
  4667. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4668. var results = [];
  4669. for (var index = 0; index < attributesNames.length; index++) {
  4670. try {
  4671. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4672. }
  4673. catch (e) {
  4674. results.push(-1);
  4675. }
  4676. }
  4677. return results;
  4678. };
  4679. Engine.prototype.enableEffect = function (effect) {
  4680. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4681. if (effect && effect.onBind) {
  4682. effect.onBind(effect);
  4683. }
  4684. return;
  4685. }
  4686. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4687. // Use program
  4688. this._gl.useProgram(effect.getProgram());
  4689. for (var i in this._vertexAttribArrays) {
  4690. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4691. continue;
  4692. }
  4693. this._vertexAttribArrays[i] = false;
  4694. this._gl.disableVertexAttribArray(i);
  4695. }
  4696. var attributesCount = effect.getAttributesCount();
  4697. for (var index = 0; index < attributesCount; index++) {
  4698. // Attributes
  4699. var order = effect.getAttributeLocation(index);
  4700. if (order >= 0) {
  4701. this._vertexAttribArrays[order] = true;
  4702. this._gl.enableVertexAttribArray(order);
  4703. }
  4704. }
  4705. this._currentEffect = effect;
  4706. if (effect.onBind) {
  4707. effect.onBind(effect);
  4708. }
  4709. };
  4710. Engine.prototype.setArray = function (uniform, array) {
  4711. if (!uniform)
  4712. return;
  4713. this._gl.uniform1fv(uniform, array);
  4714. };
  4715. Engine.prototype.setArray2 = function (uniform, array) {
  4716. if (!uniform || array.length % 2 !== 0)
  4717. return;
  4718. this._gl.uniform2fv(uniform, array);
  4719. };
  4720. Engine.prototype.setArray3 = function (uniform, array) {
  4721. if (!uniform || array.length % 3 !== 0)
  4722. return;
  4723. this._gl.uniform3fv(uniform, array);
  4724. };
  4725. Engine.prototype.setArray4 = function (uniform, array) {
  4726. if (!uniform || array.length % 4 !== 0)
  4727. return;
  4728. this._gl.uniform4fv(uniform, array);
  4729. };
  4730. Engine.prototype.setMatrices = function (uniform, matrices) {
  4731. if (!uniform)
  4732. return;
  4733. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4734. };
  4735. Engine.prototype.setMatrix = function (uniform, matrix) {
  4736. if (!uniform)
  4737. return;
  4738. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4739. };
  4740. Engine.prototype.setFloat = function (uniform, value) {
  4741. if (!uniform)
  4742. return;
  4743. this._gl.uniform1f(uniform, value);
  4744. };
  4745. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4746. if (!uniform)
  4747. return;
  4748. this._gl.uniform2f(uniform, x, y);
  4749. };
  4750. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4751. if (!uniform)
  4752. return;
  4753. this._gl.uniform3f(uniform, x, y, z);
  4754. };
  4755. Engine.prototype.setBool = function (uniform, bool) {
  4756. if (!uniform)
  4757. return;
  4758. this._gl.uniform1i(uniform, bool);
  4759. };
  4760. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4761. if (!uniform)
  4762. return;
  4763. this._gl.uniform4f(uniform, x, y, z, w);
  4764. };
  4765. Engine.prototype.setColor3 = function (uniform, color3) {
  4766. if (!uniform)
  4767. return;
  4768. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4769. };
  4770. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4771. if (!uniform)
  4772. return;
  4773. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4774. };
  4775. // States
  4776. Engine.prototype.setState = function (culling, zOffset, force) {
  4777. if (zOffset === void 0) { zOffset = 0; }
  4778. // Culling
  4779. if (this._depthCullingState.cull !== culling || force) {
  4780. if (culling) {
  4781. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4782. this._depthCullingState.cull = true;
  4783. }
  4784. else {
  4785. this._depthCullingState.cull = false;
  4786. }
  4787. }
  4788. // Z offset
  4789. this._depthCullingState.zOffset = zOffset;
  4790. };
  4791. Engine.prototype.setDepthBuffer = function (enable) {
  4792. this._depthCullingState.depthTest = enable;
  4793. };
  4794. Engine.prototype.getDepthWrite = function () {
  4795. return this._depthCullingState.depthMask;
  4796. };
  4797. Engine.prototype.setDepthWrite = function (enable) {
  4798. this._depthCullingState.depthMask = enable;
  4799. };
  4800. Engine.prototype.setColorWrite = function (enable) {
  4801. this._gl.colorMask(enable, enable, enable, enable);
  4802. };
  4803. Engine.prototype.setAlphaMode = function (mode) {
  4804. switch (mode) {
  4805. case Engine.ALPHA_DISABLE:
  4806. this.setDepthWrite(true);
  4807. this._alphaState.alphaBlend = false;
  4808. break;
  4809. case Engine.ALPHA_COMBINE:
  4810. this.setDepthWrite(false);
  4811. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4812. this._alphaState.alphaBlend = true;
  4813. break;
  4814. case Engine.ALPHA_ADD:
  4815. this.setDepthWrite(false);
  4816. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4817. this._alphaState.alphaBlend = true;
  4818. break;
  4819. }
  4820. this._alphaMode = mode;
  4821. };
  4822. Engine.prototype.getAlphaMode = function () {
  4823. return this._alphaMode;
  4824. };
  4825. Engine.prototype.setAlphaTesting = function (enable) {
  4826. this._alphaTest = enable;
  4827. };
  4828. Engine.prototype.getAlphaTesting = function () {
  4829. return this._alphaTest;
  4830. };
  4831. // Textures
  4832. Engine.prototype.wipeCaches = function () {
  4833. this._activeTexturesCache = [];
  4834. this._currentEffect = null;
  4835. this._depthCullingState.reset();
  4836. this._alphaState.reset();
  4837. this._cachedVertexBuffers = null;
  4838. this._cachedIndexBuffer = null;
  4839. this._cachedEffectForVertexBuffers = null;
  4840. };
  4841. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4842. var gl = this._gl;
  4843. gl.bindTexture(gl.TEXTURE_2D, texture);
  4844. var magFilter = gl.NEAREST;
  4845. var minFilter = gl.NEAREST;
  4846. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4847. magFilter = gl.LINEAR;
  4848. minFilter = gl.LINEAR;
  4849. }
  4850. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4851. magFilter = gl.LINEAR;
  4852. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4853. }
  4854. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4855. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4856. gl.bindTexture(gl.TEXTURE_2D, null);
  4857. texture.samplingMode = samplingMode;
  4858. };
  4859. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4860. var _this = this;
  4861. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4862. if (onLoad === void 0) { onLoad = null; }
  4863. if (onError === void 0) { onError = null; }
  4864. if (buffer === void 0) { buffer = null; }
  4865. var texture = this._gl.createTexture();
  4866. var extension;
  4867. var fromData = false;
  4868. if (url.substr(0, 5) === "data:") {
  4869. fromData = true;
  4870. }
  4871. if (!fromData)
  4872. extension = url.substr(url.length - 4, 4).toLowerCase();
  4873. else {
  4874. var oldUrl = url;
  4875. fromData = oldUrl.split(':');
  4876. url = oldUrl;
  4877. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4878. }
  4879. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4880. var isTGA = (extension === ".tga");
  4881. scene._addPendingData(texture);
  4882. texture.url = url;
  4883. texture.noMipmap = noMipmap;
  4884. texture.references = 1;
  4885. this._loadedTexturesCache.push(texture);
  4886. var onerror = function () {
  4887. scene._removePendingData(texture);
  4888. if (onError) {
  4889. onError();
  4890. }
  4891. };
  4892. if (isTGA) {
  4893. var callback = function (arrayBuffer) {
  4894. var data = new Uint8Array(arrayBuffer);
  4895. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4896. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4897. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4898. if (onLoad) {
  4899. onLoad();
  4900. }
  4901. }, samplingMode);
  4902. };
  4903. if (!(fromData instanceof Array))
  4904. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4905. callback(arrayBuffer);
  4906. }, onerror, scene.database, true);
  4907. else
  4908. callback(buffer);
  4909. }
  4910. else if (isDDS) {
  4911. callback = function (data) {
  4912. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4913. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4914. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4915. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4916. if (onLoad) {
  4917. onLoad();
  4918. }
  4919. }, samplingMode);
  4920. };
  4921. if (!(fromData instanceof Array))
  4922. BABYLON.Tools.LoadFile(url, function (data) {
  4923. callback(data);
  4924. }, onerror, scene.database, true);
  4925. else
  4926. callback(buffer);
  4927. }
  4928. else {
  4929. var onload = function (img) {
  4930. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4931. var isPot = (img.width === potWidth && img.height === potHeight);
  4932. if (!isPot) {
  4933. _this._prepareWorkingCanvas();
  4934. _this._workingCanvas.width = potWidth;
  4935. _this._workingCanvas.height = potHeight;
  4936. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4937. _this._workingContext.imageSmoothingEnabled = false;
  4938. _this._workingContext.mozImageSmoothingEnabled = false;
  4939. _this._workingContext.oImageSmoothingEnabled = false;
  4940. _this._workingContext.webkitImageSmoothingEnabled = false;
  4941. _this._workingContext.msImageSmoothingEnabled = false;
  4942. }
  4943. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4944. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4945. _this._workingContext.imageSmoothingEnabled = true;
  4946. _this._workingContext.mozImageSmoothingEnabled = true;
  4947. _this._workingContext.oImageSmoothingEnabled = true;
  4948. _this._workingContext.webkitImageSmoothingEnabled = true;
  4949. _this._workingContext.msImageSmoothingEnabled = true;
  4950. }
  4951. }
  4952. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4953. if (onLoad) {
  4954. onLoad();
  4955. }
  4956. }, samplingMode);
  4957. };
  4958. if (!(fromData instanceof Array))
  4959. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4960. else
  4961. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4962. }
  4963. return texture;
  4964. };
  4965. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4966. var texture = this._gl.createTexture();
  4967. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4968. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4969. // Format
  4970. var internalFormat = this._gl.RGBA;
  4971. switch (format) {
  4972. case Engine.TEXTUREFORMAT_ALPHA:
  4973. internalFormat = this._gl.ALPHA;
  4974. break;
  4975. case Engine.TEXTUREFORMAT_LUMINANCE:
  4976. internalFormat = this._gl.LUMINANCE;
  4977. break;
  4978. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4979. internalFormat = this._gl.LUMINANCE_ALPHA;
  4980. break;
  4981. case Engine.TEXTUREFORMAT_RGB:
  4982. internalFormat = this._gl.RGB;
  4983. break;
  4984. case Engine.TEXTUREFORMAT_RGBA:
  4985. internalFormat = this._gl.RGBA;
  4986. break;
  4987. }
  4988. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4989. if (generateMipMaps) {
  4990. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4991. }
  4992. // Filters
  4993. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4994. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4995. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4996. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4997. this._activeTexturesCache = [];
  4998. texture._baseWidth = width;
  4999. texture._baseHeight = height;
  5000. texture._width = width;
  5001. texture._height = height;
  5002. texture.isReady = true;
  5003. texture.references = 1;
  5004. texture.samplingMode = samplingMode;
  5005. this._loadedTexturesCache.push(texture);
  5006. return texture;
  5007. };
  5008. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  5009. var texture = this._gl.createTexture();
  5010. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  5011. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  5012. this._activeTexturesCache = [];
  5013. texture._baseWidth = width;
  5014. texture._baseHeight = height;
  5015. texture._width = width;
  5016. texture._height = height;
  5017. texture.isReady = false;
  5018. texture.generateMipMaps = generateMipMaps;
  5019. texture.references = 1;
  5020. texture.samplingMode = samplingMode;
  5021. this.updateTextureSamplingMode(samplingMode, texture);
  5022. this._loadedTexturesCache.push(texture);
  5023. return texture;
  5024. };
  5025. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  5026. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  5027. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5028. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  5029. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  5030. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5031. };
  5032. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  5033. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5034. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  5035. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  5036. if (texture.generateMipMaps) {
  5037. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  5038. }
  5039. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5040. this._activeTexturesCache = [];
  5041. texture.isReady = true;
  5042. };
  5043. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  5044. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5045. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  5046. // Scale the video if it is a NPOT using the current working canvas
  5047. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  5048. if (!texture._workingCanvas) {
  5049. texture._workingCanvas = document.createElement("canvas");
  5050. texture._workingContext = texture._workingCanvas.getContext("2d");
  5051. texture._workingCanvas.width = texture._width;
  5052. texture._workingCanvas.height = texture._height;
  5053. }
  5054. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  5055. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  5056. }
  5057. else {
  5058. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  5059. }
  5060. if (texture.generateMipMaps) {
  5061. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  5062. }
  5063. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5064. this._activeTexturesCache = [];
  5065. texture.isReady = true;
  5066. };
  5067. Engine.prototype.createRenderTargetTexture = function (size, options) {
  5068. // old version had a "generateMipMaps" arg instead of options.
  5069. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  5070. // in the same way, generateDepthBuffer is defaulted to true
  5071. var generateMipMaps = false;
  5072. var generateDepthBuffer = true;
  5073. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  5074. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  5075. if (options !== undefined) {
  5076. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  5077. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  5078. type = options.type === undefined ? type : options.type;
  5079. if (options.samplingMode !== undefined) {
  5080. samplingMode = options.samplingMode;
  5081. }
  5082. if (type === Engine.TEXTURETYPE_FLOAT) {
  5083. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  5084. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  5085. }
  5086. }
  5087. var gl = this._gl;
  5088. var texture = gl.createTexture();
  5089. gl.bindTexture(gl.TEXTURE_2D, texture);
  5090. var width = size.width || size;
  5091. var height = size.height || size;
  5092. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  5093. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  5094. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  5095. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  5096. }
  5097. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5098. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5099. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5100. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5101. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  5102. var depthBuffer;
  5103. // Create the depth buffer
  5104. if (generateDepthBuffer) {
  5105. depthBuffer = gl.createRenderbuffer();
  5106. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  5107. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  5108. }
  5109. // Create the framebuffer
  5110. var framebuffer = gl.createFramebuffer();
  5111. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  5112. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5113. if (generateDepthBuffer) {
  5114. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  5115. }
  5116. // Unbind
  5117. gl.bindTexture(gl.TEXTURE_2D, null);
  5118. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  5119. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5120. texture._framebuffer = framebuffer;
  5121. if (generateDepthBuffer) {
  5122. texture._depthBuffer = depthBuffer;
  5123. }
  5124. texture._width = width;
  5125. texture._height = height;
  5126. texture.isReady = true;
  5127. texture.generateMipMaps = generateMipMaps;
  5128. texture.references = 1;
  5129. texture.samplingMode = samplingMode;
  5130. this._activeTexturesCache = [];
  5131. this._loadedTexturesCache.push(texture);
  5132. return texture;
  5133. };
  5134. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  5135. var _this = this;
  5136. var gl = this._gl;
  5137. var texture = gl.createTexture();
  5138. texture.isCube = true;
  5139. texture.url = rootUrl;
  5140. texture.references = 1;
  5141. this._loadedTexturesCache.push(texture);
  5142. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  5143. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  5144. if (isDDS) {
  5145. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  5146. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  5147. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  5148. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5149. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  5150. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  5151. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  5152. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5153. }
  5154. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  5155. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  5156. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5157. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5158. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5159. _this._activeTexturesCache = [];
  5160. texture._width = info.width;
  5161. texture._height = info.height;
  5162. texture.isReady = true;
  5163. }, null, null, true);
  5164. }
  5165. else {
  5166. cascadeLoad(rootUrl, scene, function (imgs) {
  5167. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  5168. var height = width;
  5169. _this._prepareWorkingCanvas();
  5170. _this._workingCanvas.width = width;
  5171. _this._workingCanvas.height = height;
  5172. var faces = [
  5173. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  5174. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  5175. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  5176. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  5177. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  5178. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  5179. ];
  5180. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5181. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  5182. for (var index = 0; index < faces.length; index++) {
  5183. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  5184. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  5185. }
  5186. if (!noMipmap) {
  5187. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5188. }
  5189. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  5190. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  5191. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5192. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5193. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5194. _this._activeTexturesCache = [];
  5195. texture._width = width;
  5196. texture._height = height;
  5197. texture.isReady = true;
  5198. }, extensions);
  5199. }
  5200. return texture;
  5201. };
  5202. Engine.prototype._releaseTexture = function (texture) {
  5203. var gl = this._gl;
  5204. if (texture._framebuffer) {
  5205. gl.deleteFramebuffer(texture._framebuffer);
  5206. }
  5207. if (texture._depthBuffer) {
  5208. gl.deleteRenderbuffer(texture._depthBuffer);
  5209. }
  5210. gl.deleteTexture(texture);
  5211. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  5212. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5213. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5214. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  5215. this._activeTexturesCache[channel] = null;
  5216. }
  5217. var index = this._loadedTexturesCache.indexOf(texture);
  5218. if (index !== -1) {
  5219. this._loadedTexturesCache.splice(index, 1);
  5220. }
  5221. };
  5222. Engine.prototype.bindSamplers = function (effect) {
  5223. this._gl.useProgram(effect.getProgram());
  5224. var samplers = effect.getSamplers();
  5225. for (var index = 0; index < samplers.length; index++) {
  5226. var uniform = effect.getUniform(samplers[index]);
  5227. this._gl.uniform1i(uniform, index);
  5228. }
  5229. this._currentEffect = null;
  5230. };
  5231. Engine.prototype._bindTexture = function (channel, texture) {
  5232. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5233. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5234. this._activeTexturesCache[channel] = null;
  5235. };
  5236. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  5237. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  5238. };
  5239. Engine.prototype.setTexture = function (channel, texture) {
  5240. if (channel < 0) {
  5241. return;
  5242. }
  5243. // Not ready?
  5244. if (!texture || !texture.isReady()) {
  5245. if (this._activeTexturesCache[channel] != null) {
  5246. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5247. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5248. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  5249. this._activeTexturesCache[channel] = null;
  5250. }
  5251. return;
  5252. }
  5253. // Video
  5254. if (texture instanceof BABYLON.VideoTexture) {
  5255. if (texture.update()) {
  5256. this._activeTexturesCache[channel] = null;
  5257. }
  5258. }
  5259. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  5260. texture.delayLoad();
  5261. return;
  5262. }
  5263. if (this._activeTexturesCache[channel] === texture) {
  5264. return;
  5265. }
  5266. this._activeTexturesCache[channel] = texture;
  5267. var internalTexture = texture.getInternalTexture();
  5268. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5269. if (internalTexture.isCube) {
  5270. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  5271. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  5272. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  5273. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  5274. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  5275. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  5276. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  5277. }
  5278. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  5279. }
  5280. else {
  5281. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  5282. if (internalTexture._cachedWrapU !== texture.wrapU) {
  5283. internalTexture._cachedWrapU = texture.wrapU;
  5284. switch (texture.wrapU) {
  5285. case BABYLON.Texture.WRAP_ADDRESSMODE:
  5286. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  5287. break;
  5288. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  5289. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  5290. break;
  5291. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  5292. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  5293. break;
  5294. }
  5295. }
  5296. if (internalTexture._cachedWrapV !== texture.wrapV) {
  5297. internalTexture._cachedWrapV = texture.wrapV;
  5298. switch (texture.wrapV) {
  5299. case BABYLON.Texture.WRAP_ADDRESSMODE:
  5300. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  5301. break;
  5302. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  5303. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  5304. break;
  5305. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  5306. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  5307. break;
  5308. }
  5309. }
  5310. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  5311. }
  5312. };
  5313. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  5314. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  5315. var value = texture.anisotropicFilteringLevel;
  5316. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5317. value = 1;
  5318. }
  5319. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  5320. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  5321. texture._cachedAnisotropicFilteringLevel = value;
  5322. }
  5323. };
  5324. Engine.prototype.readPixels = function (x, y, width, height) {
  5325. var data = new Uint8Array(height * width * 4);
  5326. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  5327. return data;
  5328. };
  5329. // Dispose
  5330. Engine.prototype.dispose = function () {
  5331. this.hideLoadingUI();
  5332. this.stopRenderLoop();
  5333. while (this.scenes.length) {
  5334. this.scenes[0].dispose();
  5335. }
  5336. // Release audio engine
  5337. Engine.audioEngine.dispose();
  5338. for (var name in this._compiledEffects) {
  5339. this._gl.deleteProgram(this._compiledEffects[name]._program);
  5340. }
  5341. for (var i in this._vertexAttribArrays) {
  5342. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5343. continue;
  5344. }
  5345. this._gl.disableVertexAttribArray(i);
  5346. }
  5347. // Events
  5348. window.removeEventListener("blur", this._onBlur);
  5349. window.removeEventListener("focus", this._onFocus);
  5350. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  5351. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  5352. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  5353. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  5354. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  5355. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  5356. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  5357. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  5358. };
  5359. // Loading screen
  5360. Engine.prototype.displayLoadingUI = function () {
  5361. var _this = this;
  5362. this._loadingDiv = document.createElement("div");
  5363. this._loadingDiv.style.opacity = "0";
  5364. this._loadingDiv.style.transition = "opacity 1.5s ease";
  5365. // Loading text
  5366. this._loadingTextDiv = document.createElement("div");
  5367. this._loadingTextDiv.style.position = "absolute";
  5368. this._loadingTextDiv.style.left = "0";
  5369. this._loadingTextDiv.style.top = "50%";
  5370. this._loadingTextDiv.style.marginTop = "80px";
  5371. this._loadingTextDiv.style.width = "100%";
  5372. this._loadingTextDiv.style.height = "20px";
  5373. this._loadingTextDiv.style.fontFamily = "Arial";
  5374. this._loadingTextDiv.style.fontSize = "14px";
  5375. this._loadingTextDiv.style.color = "white";
  5376. this._loadingTextDiv.style.textAlign = "center";
  5377. this._loadingTextDiv.innerHTML = "Loading";
  5378. this._loadingDiv.appendChild(this._loadingTextDiv);
  5379. // Loading img
  5380. var imgBack = new Image();
  5381. 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==";
  5382. imgBack.style.position = "absolute";
  5383. imgBack.style.left = "50%";
  5384. imgBack.style.top = "50%";
  5385. imgBack.style.marginLeft = "-50px";
  5386. imgBack.style.marginTop = "-50px";
  5387. imgBack.style.transition = "transform 1.0s ease";
  5388. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  5389. var deg = 360;
  5390. var onTransitionEnd = function () {
  5391. deg += 360;
  5392. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  5393. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  5394. };
  5395. imgBack.addEventListener("transitionend", onTransitionEnd);
  5396. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  5397. this._loadingDiv.appendChild(imgBack);
  5398. // front image
  5399. var imgFront = new Image();
  5400. 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=";
  5401. imgFront.style.position = "absolute";
  5402. imgFront.style.left = "50%";
  5403. imgFront.style.top = "50%";
  5404. imgFront.style.marginLeft = "-50px";
  5405. imgFront.style.marginTop = "-50px";
  5406. this._loadingDiv.appendChild(imgFront);
  5407. // Resize
  5408. this._resizeLoadingUI = function () {
  5409. var canvasRect = _this.getRenderingCanvasClientRect();
  5410. _this._loadingDiv.style.position = "absolute";
  5411. _this._loadingDiv.style.left = canvasRect.left + "px";
  5412. _this._loadingDiv.style.top = canvasRect.top + "px";
  5413. _this._loadingDiv.style.width = canvasRect.width + "px";
  5414. _this._loadingDiv.style.height = canvasRect.height + "px";
  5415. };
  5416. this._resizeLoadingUI();
  5417. window.addEventListener("resize", this._resizeLoadingUI);
  5418. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5419. document.body.appendChild(this._loadingDiv);
  5420. setTimeout(function () {
  5421. _this._loadingDiv.style.opacity = "1";
  5422. imgBack.style.transform = "rotateZ(360deg)";
  5423. imgBack.style.webkitTransform = "rotateZ(360deg)";
  5424. }, 0);
  5425. };
  5426. Object.defineProperty(Engine.prototype, "loadingUIText", {
  5427. set: function (text) {
  5428. if (!this._loadingDiv) {
  5429. return;
  5430. }
  5431. this._loadingTextDiv.innerHTML = text;
  5432. },
  5433. enumerable: true,
  5434. configurable: true
  5435. });
  5436. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  5437. get: function () {
  5438. return this._loadingDivBackgroundColor;
  5439. },
  5440. set: function (color) {
  5441. this._loadingDivBackgroundColor = color;
  5442. if (!this._loadingDiv) {
  5443. return;
  5444. }
  5445. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5446. },
  5447. enumerable: true,
  5448. configurable: true
  5449. });
  5450. Engine.prototype.hideLoadingUI = function () {
  5451. var _this = this;
  5452. if (!this._loadingDiv) {
  5453. return;
  5454. }
  5455. var onTransitionEnd = function () {
  5456. if (!_this._loadingDiv) {
  5457. return;
  5458. }
  5459. document.body.removeChild(_this._loadingDiv);
  5460. window.removeEventListener("resize", _this._resizeLoadingUI);
  5461. _this._loadingDiv = null;
  5462. };
  5463. this._loadingDiv.style.opacity = "0";
  5464. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  5465. };
  5466. // FPS
  5467. Engine.prototype.getFps = function () {
  5468. return this.fps;
  5469. };
  5470. Engine.prototype.getDeltaTime = function () {
  5471. return this.deltaTime;
  5472. };
  5473. Engine.prototype._measureFps = function () {
  5474. this.previousFramesDuration.push(BABYLON.Tools.Now);
  5475. var length = this.previousFramesDuration.length;
  5476. if (length >= 2) {
  5477. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  5478. }
  5479. if (length >= this.fpsRange) {
  5480. if (length > this.fpsRange) {
  5481. this.previousFramesDuration.splice(0, 1);
  5482. length = this.previousFramesDuration.length;
  5483. }
  5484. var sum = 0;
  5485. for (var id = 0; id < length - 1; id++) {
  5486. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  5487. }
  5488. this.fps = 1000.0 / (sum / (length - 1));
  5489. }
  5490. };
  5491. // Statics
  5492. Engine.isSupported = function () {
  5493. try {
  5494. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  5495. if (navigator.isCocoonJS) {
  5496. return true;
  5497. }
  5498. var tempcanvas = document.createElement("canvas");
  5499. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  5500. return gl != null && !!window.WebGLRenderingContext;
  5501. }
  5502. catch (e) {
  5503. return false;
  5504. }
  5505. };
  5506. // Const statics
  5507. Engine._ALPHA_DISABLE = 0;
  5508. Engine._ALPHA_ADD = 1;
  5509. Engine._ALPHA_COMBINE = 2;
  5510. Engine._DELAYLOADSTATE_NONE = 0;
  5511. Engine._DELAYLOADSTATE_LOADED = 1;
  5512. Engine._DELAYLOADSTATE_LOADING = 2;
  5513. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  5514. Engine._TEXTUREFORMAT_ALPHA = 0;
  5515. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  5516. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  5517. Engine._TEXTUREFORMAT_RGB = 4;
  5518. Engine._TEXTUREFORMAT_RGBA = 4;
  5519. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  5520. Engine._TEXTURETYPE_FLOAT = 1;
  5521. // Updatable statics so stick with vars here
  5522. Engine.Epsilon = 0.001;
  5523. Engine.CollisionsEpsilon = 0.001;
  5524. Engine.ShadersRepository = "Babylon/Shaders/";
  5525. return Engine;
  5526. })();
  5527. BABYLON.Engine = Engine;
  5528. })(BABYLON || (BABYLON = {}));
  5529. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  5530. (function (BABYLON) {
  5531. /**
  5532. * Node is the basic class for all scene objects (Mesh, Light Camera).
  5533. */
  5534. var Node = (function () {
  5535. /**
  5536. * @constructor
  5537. * @param {string} name - the name and id to be given to this node
  5538. * @param {BABYLON.Scene} the scene this node will be added to
  5539. */
  5540. function Node(name, scene) {
  5541. this.state = "";
  5542. this.animations = new Array();
  5543. this._childrenFlag = -1;
  5544. this._isEnabled = true;
  5545. this._isReady = true;
  5546. this._currentRenderId = -1;
  5547. this._parentRenderId = -1;
  5548. this.name = name;
  5549. this.id = name;
  5550. this._scene = scene;
  5551. this._initCache();
  5552. }
  5553. Node.prototype.getScene = function () {
  5554. return this._scene;
  5555. };
  5556. Node.prototype.getEngine = function () {
  5557. return this._scene.getEngine();
  5558. };
  5559. // override it in derived class
  5560. Node.prototype.getWorldMatrix = function () {
  5561. return BABYLON.Matrix.Identity();
  5562. };
  5563. // override it in derived class if you add new variables to the cache
  5564. // and call the parent class method
  5565. Node.prototype._initCache = function () {
  5566. this._cache = {};
  5567. this._cache.parent = undefined;
  5568. };
  5569. Node.prototype.updateCache = function (force) {
  5570. if (!force && this.isSynchronized())
  5571. return;
  5572. this._cache.parent = this.parent;
  5573. this._updateCache();
  5574. };
  5575. // override it in derived class if you add new variables to the cache
  5576. // and call the parent class method if !ignoreParentClass
  5577. Node.prototype._updateCache = function (ignoreParentClass) {
  5578. };
  5579. // override it in derived class if you add new variables to the cache
  5580. Node.prototype._isSynchronized = function () {
  5581. return true;
  5582. };
  5583. Node.prototype.isSynchronizedWithParent = function () {
  5584. if (!this.parent) {
  5585. return true;
  5586. }
  5587. if (this._parentRenderId !== this.parent._currentRenderId) {
  5588. return false;
  5589. }
  5590. this._parentRenderId = this.parent._currentRenderId;
  5591. return this.parent._currentRenderId <= this._currentRenderId && this.parent.isSynchronized();
  5592. };
  5593. Node.prototype.isSynchronized = function (updateCache) {
  5594. var check = this.hasNewParent();
  5595. check = check || !this.isSynchronizedWithParent();
  5596. check = check || !this._isSynchronized();
  5597. if (updateCache)
  5598. this.updateCache(true);
  5599. return !check;
  5600. };
  5601. Node.prototype.hasNewParent = function (update) {
  5602. if (this._cache.parent === this.parent)
  5603. return false;
  5604. if (update)
  5605. this._cache.parent = this.parent;
  5606. return true;
  5607. };
  5608. /**
  5609. * Is this node ready to be used/rendered
  5610. * @return {boolean} is it ready
  5611. */
  5612. Node.prototype.isReady = function () {
  5613. return this._isReady;
  5614. };
  5615. /**
  5616. * Is this node enabled.
  5617. * If the node has a parent and is enabled, the parent will be inspected as well.
  5618. * @return {boolean} whether this node (and its parent) is enabled.
  5619. * @see setEnabled
  5620. */
  5621. Node.prototype.isEnabled = function () {
  5622. if (!this._isEnabled) {
  5623. return false;
  5624. }
  5625. if (this.parent) {
  5626. return this.parent.isEnabled();
  5627. }
  5628. return true;
  5629. };
  5630. /**
  5631. * Set the enabled state of this node.
  5632. * @param {boolean} value - the new enabled state
  5633. * @see isEnabled
  5634. */
  5635. Node.prototype.setEnabled = function (value) {
  5636. this._isEnabled = value;
  5637. };
  5638. /**
  5639. * Is this node a descendant of the given node.
  5640. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5641. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5642. * @see parent
  5643. */
  5644. Node.prototype.isDescendantOf = function (ancestor) {
  5645. if (this.parent) {
  5646. if (this.parent === ancestor) {
  5647. return true;
  5648. }
  5649. return this.parent.isDescendantOf(ancestor);
  5650. }
  5651. return false;
  5652. };
  5653. Node.prototype._getDescendants = function (list, results) {
  5654. for (var index = 0; index < list.length; index++) {
  5655. var item = list[index];
  5656. if (item.isDescendantOf(this)) {
  5657. results.push(item);
  5658. }
  5659. }
  5660. };
  5661. /**
  5662. * Will return all nodes that have this node as parent.
  5663. * @return {BABYLON.Node[]} all children nodes of all types.
  5664. */
  5665. Node.prototype.getDescendants = function () {
  5666. var results = [];
  5667. this._getDescendants(this._scene.meshes, results);
  5668. this._getDescendants(this._scene.lights, results);
  5669. this._getDescendants(this._scene.cameras, results);
  5670. return results;
  5671. };
  5672. Node.prototype._setReady = function (state) {
  5673. if (state == this._isReady) {
  5674. return;
  5675. }
  5676. if (!state) {
  5677. this._isReady = false;
  5678. return;
  5679. }
  5680. this._isReady = true;
  5681. if (this.onReady) {
  5682. this.onReady(this);
  5683. }
  5684. };
  5685. return Node;
  5686. })();
  5687. BABYLON.Node = Node;
  5688. })(BABYLON || (BABYLON = {}));
  5689. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5690. (function (BABYLON) {
  5691. var BoundingSphere = (function () {
  5692. function BoundingSphere(minimum, maximum) {
  5693. this.minimum = minimum;
  5694. this.maximum = maximum;
  5695. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5696. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5697. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5698. this.radius = distance * 0.5;
  5699. this.centerWorld = BABYLON.Vector3.Zero();
  5700. this._update(BABYLON.Matrix.Identity());
  5701. }
  5702. // Methods
  5703. BoundingSphere.prototype._update = function (world) {
  5704. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5705. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5706. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5707. };
  5708. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5709. for (var i = 0; i < 6; i++) {
  5710. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5711. return false;
  5712. }
  5713. return true;
  5714. };
  5715. BoundingSphere.prototype.intersectsPoint = function (point) {
  5716. var x = this.centerWorld.x - point.x;
  5717. var y = this.centerWorld.y - point.y;
  5718. var z = this.centerWorld.z - point.z;
  5719. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5720. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5721. return false;
  5722. return true;
  5723. };
  5724. // Statics
  5725. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5726. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5727. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5728. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5729. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5730. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5731. return false;
  5732. return true;
  5733. };
  5734. return BoundingSphere;
  5735. })();
  5736. BABYLON.BoundingSphere = BoundingSphere;
  5737. })(BABYLON || (BABYLON = {}));
  5738. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5739. (function (BABYLON) {
  5740. var BoundingBox = (function () {
  5741. function BoundingBox(minimum, maximum) {
  5742. this.minimum = minimum;
  5743. this.maximum = maximum;
  5744. this.vectors = new Array();
  5745. this.vectorsWorld = new Array();
  5746. // Bounding vectors
  5747. this.vectors.push(this.minimum.clone());
  5748. this.vectors.push(this.maximum.clone());
  5749. this.vectors.push(this.minimum.clone());
  5750. this.vectors[2].x = this.maximum.x;
  5751. this.vectors.push(this.minimum.clone());
  5752. this.vectors[3].y = this.maximum.y;
  5753. this.vectors.push(this.minimum.clone());
  5754. this.vectors[4].z = this.maximum.z;
  5755. this.vectors.push(this.maximum.clone());
  5756. this.vectors[5].z = this.minimum.z;
  5757. this.vectors.push(this.maximum.clone());
  5758. this.vectors[6].x = this.minimum.x;
  5759. this.vectors.push(this.maximum.clone());
  5760. this.vectors[7].y = this.minimum.y;
  5761. // OBB
  5762. this.center = this.maximum.add(this.minimum).scale(0.5);
  5763. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5764. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5765. for (var index = 0; index < this.vectors.length; index++) {
  5766. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5767. }
  5768. this.minimumWorld = BABYLON.Vector3.Zero();
  5769. this.maximumWorld = BABYLON.Vector3.Zero();
  5770. this._update(BABYLON.Matrix.Identity());
  5771. }
  5772. // Methods
  5773. BoundingBox.prototype.getWorldMatrix = function () {
  5774. return this._worldMatrix;
  5775. };
  5776. BoundingBox.prototype._update = function (world) {
  5777. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5778. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5779. for (var index = 0; index < this.vectors.length; index++) {
  5780. var v = this.vectorsWorld[index];
  5781. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5782. if (v.x < this.minimumWorld.x)
  5783. this.minimumWorld.x = v.x;
  5784. if (v.y < this.minimumWorld.y)
  5785. this.minimumWorld.y = v.y;
  5786. if (v.z < this.minimumWorld.z)
  5787. this.minimumWorld.z = v.z;
  5788. if (v.x > this.maximumWorld.x)
  5789. this.maximumWorld.x = v.x;
  5790. if (v.y > this.maximumWorld.y)
  5791. this.maximumWorld.y = v.y;
  5792. if (v.z > this.maximumWorld.z)
  5793. this.maximumWorld.z = v.z;
  5794. }
  5795. // OBB
  5796. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5797. this.center.scaleInPlace(0.5);
  5798. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5799. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5800. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5801. this._worldMatrix = world;
  5802. };
  5803. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5804. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5805. };
  5806. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5807. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5808. };
  5809. BoundingBox.prototype.intersectsPoint = function (point) {
  5810. var delta = BABYLON.Engine.Epsilon;
  5811. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5812. return false;
  5813. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5814. return false;
  5815. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5816. return false;
  5817. return true;
  5818. };
  5819. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5820. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5821. };
  5822. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5823. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5824. return false;
  5825. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5826. return false;
  5827. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5828. return false;
  5829. return true;
  5830. };
  5831. // Statics
  5832. BoundingBox.Intersects = function (box0, box1) {
  5833. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5834. return false;
  5835. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5836. return false;
  5837. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5838. return false;
  5839. return true;
  5840. };
  5841. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5842. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5843. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5844. return (num <= (sphereRadius * sphereRadius));
  5845. };
  5846. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5847. for (var p = 0; p < 6; p++) {
  5848. for (var i = 0; i < 8; i++) {
  5849. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5850. return false;
  5851. }
  5852. }
  5853. }
  5854. return true;
  5855. };
  5856. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5857. for (var p = 0; p < 6; p++) {
  5858. var inCount = 8;
  5859. for (var i = 0; i < 8; i++) {
  5860. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5861. --inCount;
  5862. }
  5863. else {
  5864. break;
  5865. }
  5866. }
  5867. if (inCount === 0)
  5868. return false;
  5869. }
  5870. return true;
  5871. };
  5872. return BoundingBox;
  5873. })();
  5874. BABYLON.BoundingBox = BoundingBox;
  5875. })(BABYLON || (BABYLON = {}));
  5876. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5877. (function (BABYLON) {
  5878. var computeBoxExtents = function (axis, box) {
  5879. var p = BABYLON.Vector3.Dot(box.center, axis);
  5880. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5881. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5882. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5883. var r = r0 + r1 + r2;
  5884. return {
  5885. min: p - r,
  5886. max: p + r
  5887. };
  5888. };
  5889. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5890. var axisOverlap = function (axis, box0, box1) {
  5891. var result0 = computeBoxExtents(axis, box0);
  5892. var result1 = computeBoxExtents(axis, box1);
  5893. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5894. };
  5895. var BoundingInfo = (function () {
  5896. function BoundingInfo(minimum, maximum) {
  5897. this.minimum = minimum;
  5898. this.maximum = maximum;
  5899. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5900. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5901. }
  5902. // Methods
  5903. BoundingInfo.prototype._update = function (world) {
  5904. this.boundingBox._update(world);
  5905. this.boundingSphere._update(world);
  5906. };
  5907. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5908. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5909. return false;
  5910. return this.boundingBox.isInFrustum(frustumPlanes);
  5911. };
  5912. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5913. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5914. };
  5915. BoundingInfo.prototype._checkCollision = function (collider) {
  5916. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5917. };
  5918. BoundingInfo.prototype.intersectsPoint = function (point) {
  5919. if (!this.boundingSphere.centerWorld) {
  5920. return false;
  5921. }
  5922. if (!this.boundingSphere.intersectsPoint(point)) {
  5923. return false;
  5924. }
  5925. if (!this.boundingBox.intersectsPoint(point)) {
  5926. return false;
  5927. }
  5928. return true;
  5929. };
  5930. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5931. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5932. return false;
  5933. }
  5934. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5935. return false;
  5936. }
  5937. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5938. return false;
  5939. }
  5940. if (!precise) {
  5941. return true;
  5942. }
  5943. var box0 = this.boundingBox;
  5944. var box1 = boundingInfo.boundingBox;
  5945. if (!axisOverlap(box0.directions[0], box0, box1))
  5946. return false;
  5947. if (!axisOverlap(box0.directions[1], box0, box1))
  5948. return false;
  5949. if (!axisOverlap(box0.directions[2], box0, box1))
  5950. return false;
  5951. if (!axisOverlap(box1.directions[0], box0, box1))
  5952. return false;
  5953. if (!axisOverlap(box1.directions[1], box0, box1))
  5954. return false;
  5955. if (!axisOverlap(box1.directions[2], box0, box1))
  5956. return false;
  5957. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5958. return false;
  5959. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5960. return false;
  5961. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5962. return false;
  5963. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5964. return false;
  5965. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5966. return false;
  5967. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5968. return false;
  5969. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5970. return false;
  5971. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5972. return false;
  5973. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5974. return false;
  5975. return true;
  5976. };
  5977. return BoundingInfo;
  5978. })();
  5979. BABYLON.BoundingInfo = BoundingInfo;
  5980. })(BABYLON || (BABYLON = {}));
  5981. //# sourceMappingURL=babylon.boundingInfo.js.map
  5982. var BABYLON;
  5983. (function (BABYLON) {
  5984. var Light = (function (_super) {
  5985. __extends(Light, _super);
  5986. function Light(name, scene) {
  5987. _super.call(this, name, scene);
  5988. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5989. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5990. this.intensity = 1.0;
  5991. this.range = Number.MAX_VALUE;
  5992. this.includeOnlyWithLayerMask = 0;
  5993. this.includedOnlyMeshes = new Array();
  5994. this.excludedMeshes = new Array();
  5995. this._excludedMeshesIds = new Array();
  5996. this._includedOnlyMeshesIds = new Array();
  5997. scene.addLight(this);
  5998. }
  5999. Light.prototype.getShadowGenerator = function () {
  6000. return this._shadowGenerator;
  6001. };
  6002. Light.prototype.getAbsolutePosition = function () {
  6003. return BABYLON.Vector3.Zero();
  6004. };
  6005. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  6006. };
  6007. Light.prototype._getWorldMatrix = function () {
  6008. return BABYLON.Matrix.Identity();
  6009. };
  6010. Light.prototype.canAffectMesh = function (mesh) {
  6011. if (!mesh) {
  6012. return true;
  6013. }
  6014. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  6015. return false;
  6016. }
  6017. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  6018. return false;
  6019. }
  6020. if (this.includeOnlyWithLayerMask !== 0 && this.includeOnlyWithLayerMask !== mesh.layerMask) {
  6021. return false;
  6022. }
  6023. return true;
  6024. };
  6025. Light.prototype.getWorldMatrix = function () {
  6026. this._currentRenderId = this.getScene().getRenderId();
  6027. var worldMatrix = this._getWorldMatrix();
  6028. if (this.parent && this.parent.getWorldMatrix) {
  6029. if (!this._parentedWorldMatrix) {
  6030. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  6031. }
  6032. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  6033. return this._parentedWorldMatrix;
  6034. }
  6035. return worldMatrix;
  6036. };
  6037. Light.prototype.dispose = function () {
  6038. if (this._shadowGenerator) {
  6039. this._shadowGenerator.dispose();
  6040. this._shadowGenerator = null;
  6041. }
  6042. // Remove from scene
  6043. this.getScene().removeLight(this);
  6044. };
  6045. return Light;
  6046. })(BABYLON.Node);
  6047. BABYLON.Light = Light;
  6048. })(BABYLON || (BABYLON = {}));
  6049. //# sourceMappingURL=babylon.light.js.map
  6050. var BABYLON;
  6051. (function (BABYLON) {
  6052. var PointLight = (function (_super) {
  6053. __extends(PointLight, _super);
  6054. function PointLight(name, position, scene) {
  6055. _super.call(this, name, scene);
  6056. this.position = position;
  6057. }
  6058. PointLight.prototype.getAbsolutePosition = function () {
  6059. return this._transformedPosition ? this._transformedPosition : this.position;
  6060. };
  6061. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  6062. if (this.parent && this.parent.getWorldMatrix) {
  6063. if (!this._transformedPosition) {
  6064. this._transformedPosition = BABYLON.Vector3.Zero();
  6065. }
  6066. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  6067. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  6068. return;
  6069. }
  6070. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  6071. };
  6072. PointLight.prototype.getShadowGenerator = function () {
  6073. return null;
  6074. };
  6075. PointLight.prototype._getWorldMatrix = function () {
  6076. if (!this._worldMatrix) {
  6077. this._worldMatrix = BABYLON.Matrix.Identity();
  6078. }
  6079. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6080. return this._worldMatrix;
  6081. };
  6082. return PointLight;
  6083. })(BABYLON.Light);
  6084. BABYLON.PointLight = PointLight;
  6085. })(BABYLON || (BABYLON = {}));
  6086. //# sourceMappingURL=babylon.pointLight.js.map
  6087. var BABYLON;
  6088. (function (BABYLON) {
  6089. var SpotLight = (function (_super) {
  6090. __extends(SpotLight, _super);
  6091. function SpotLight(name, position, direction, angle, exponent, scene) {
  6092. _super.call(this, name, scene);
  6093. this.position = position;
  6094. this.direction = direction;
  6095. this.angle = angle;
  6096. this.exponent = exponent;
  6097. }
  6098. SpotLight.prototype.getAbsolutePosition = function () {
  6099. return this.transformedPosition ? this.transformedPosition : this.position;
  6100. };
  6101. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  6102. var activeCamera = this.getScene().activeCamera;
  6103. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  6104. };
  6105. SpotLight.prototype.supportsVSM = function () {
  6106. return true;
  6107. };
  6108. SpotLight.prototype.needRefreshPerFrame = function () {
  6109. return false;
  6110. };
  6111. SpotLight.prototype.setDirectionToTarget = function (target) {
  6112. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  6113. return this.direction;
  6114. };
  6115. SpotLight.prototype.computeTransformedPosition = function () {
  6116. if (this.parent && this.parent.getWorldMatrix) {
  6117. if (!this.transformedPosition) {
  6118. this.transformedPosition = BABYLON.Vector3.Zero();
  6119. }
  6120. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  6121. return true;
  6122. }
  6123. return false;
  6124. };
  6125. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  6126. var normalizeDirection;
  6127. if (this.parent && this.parent.getWorldMatrix) {
  6128. if (!this._transformedDirection) {
  6129. this._transformedDirection = BABYLON.Vector3.Zero();
  6130. }
  6131. this.computeTransformedPosition();
  6132. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  6133. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  6134. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  6135. }
  6136. else {
  6137. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  6138. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6139. }
  6140. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  6141. };
  6142. SpotLight.prototype._getWorldMatrix = function () {
  6143. if (!this._worldMatrix) {
  6144. this._worldMatrix = BABYLON.Matrix.Identity();
  6145. }
  6146. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6147. return this._worldMatrix;
  6148. };
  6149. return SpotLight;
  6150. })(BABYLON.Light);
  6151. BABYLON.SpotLight = SpotLight;
  6152. })(BABYLON || (BABYLON = {}));
  6153. //# sourceMappingURL=babylon.spotLight.js.map
  6154. var BABYLON;
  6155. (function (BABYLON) {
  6156. var DirectionalLight = (function (_super) {
  6157. __extends(DirectionalLight, _super);
  6158. function DirectionalLight(name, direction, scene) {
  6159. _super.call(this, name, scene);
  6160. this.direction = direction;
  6161. this.shadowOrthoScale = 0.5;
  6162. this.position = direction.scale(-1);
  6163. }
  6164. DirectionalLight.prototype.getAbsolutePosition = function () {
  6165. return this.transformedPosition ? this.transformedPosition : this.position;
  6166. };
  6167. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  6168. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  6169. return this.direction;
  6170. };
  6171. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  6172. var orthoLeft = Number.MAX_VALUE;
  6173. var orthoRight = Number.MIN_VALUE;
  6174. var orthoTop = Number.MIN_VALUE;
  6175. var orthoBottom = Number.MAX_VALUE;
  6176. var tempVector3 = BABYLON.Vector3.Zero();
  6177. var activeCamera = this.getScene().activeCamera;
  6178. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  6179. var mesh = renderList[meshIndex];
  6180. if (!mesh) {
  6181. continue;
  6182. }
  6183. var boundingInfo = mesh.getBoundingInfo();
  6184. if (!boundingInfo) {
  6185. continue;
  6186. }
  6187. var boundingBox = boundingInfo.boundingBox;
  6188. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  6189. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  6190. if (tempVector3.x < orthoLeft)
  6191. orthoLeft = tempVector3.x;
  6192. if (tempVector3.y < orthoBottom)
  6193. orthoBottom = tempVector3.y;
  6194. if (tempVector3.x > orthoRight)
  6195. orthoRight = tempVector3.x;
  6196. if (tempVector3.y > orthoTop)
  6197. orthoTop = tempVector3.y;
  6198. }
  6199. }
  6200. var xOffset = orthoRight - orthoLeft;
  6201. var yOffset = orthoTop - orthoBottom;
  6202. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  6203. };
  6204. DirectionalLight.prototype.supportsVSM = function () {
  6205. return true;
  6206. };
  6207. DirectionalLight.prototype.needRefreshPerFrame = function () {
  6208. return true;
  6209. };
  6210. DirectionalLight.prototype.computeTransformedPosition = function () {
  6211. if (this.parent && this.parent.getWorldMatrix) {
  6212. if (!this.transformedPosition) {
  6213. this.transformedPosition = BABYLON.Vector3.Zero();
  6214. }
  6215. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  6216. return true;
  6217. }
  6218. return false;
  6219. };
  6220. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  6221. if (this.parent && this.parent.getWorldMatrix) {
  6222. if (!this._transformedDirection) {
  6223. this._transformedDirection = BABYLON.Vector3.Zero();
  6224. }
  6225. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  6226. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  6227. return;
  6228. }
  6229. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  6230. };
  6231. DirectionalLight.prototype._getWorldMatrix = function () {
  6232. if (!this._worldMatrix) {
  6233. this._worldMatrix = BABYLON.Matrix.Identity();
  6234. }
  6235. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6236. return this._worldMatrix;
  6237. };
  6238. return DirectionalLight;
  6239. })(BABYLON.Light);
  6240. BABYLON.DirectionalLight = DirectionalLight;
  6241. })(BABYLON || (BABYLON = {}));
  6242. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  6243. (function (BABYLON) {
  6244. var ShadowGenerator = (function () {
  6245. function ShadowGenerator(mapSize, light) {
  6246. var _this = this;
  6247. // Members
  6248. this._filter = ShadowGenerator.FILTER_NONE;
  6249. this.blurScale = 2;
  6250. this._blurBoxOffset = 0;
  6251. this._bias = 0.00005;
  6252. this._darkness = 0;
  6253. this._transparencyShadow = false;
  6254. this._viewMatrix = BABYLON.Matrix.Zero();
  6255. this._projectionMatrix = BABYLON.Matrix.Zero();
  6256. this._transformMatrix = BABYLON.Matrix.Zero();
  6257. this._worldViewProjection = BABYLON.Matrix.Zero();
  6258. this._light = light;
  6259. this._scene = light.getScene();
  6260. this._mapSize = mapSize;
  6261. light._shadowGenerator = this;
  6262. // Render target
  6263. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  6264. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6265. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6266. this._shadowMap.anisotropicFilteringLevel = 1;
  6267. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6268. this._shadowMap.renderParticles = false;
  6269. this._shadowMap.onAfterUnbind = function () {
  6270. if (!_this.useBlurVarianceShadowMap) {
  6271. return;
  6272. }
  6273. if (!_this._shadowMap2) {
  6274. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  6275. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6276. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6277. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  6278. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  6279. _this._downSamplePostprocess.onApply = function (effect) {
  6280. effect.setTexture("textureSampler", _this._shadowMap);
  6281. };
  6282. _this.blurBoxOffset = 1;
  6283. }
  6284. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  6285. };
  6286. // Custom render function
  6287. var renderSubMesh = function (subMesh) {
  6288. var mesh = subMesh.getRenderingMesh();
  6289. var scene = _this._scene;
  6290. var engine = scene.getEngine();
  6291. // Culling
  6292. engine.setState(subMesh.getMaterial().backFaceCulling);
  6293. // Managing instances
  6294. var batch = mesh._getInstancesRenderList(subMesh._id);
  6295. if (batch.mustReturn) {
  6296. return;
  6297. }
  6298. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  6299. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  6300. engine.enableEffect(_this._effect);
  6301. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  6302. var material = subMesh.getMaterial();
  6303. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  6304. // Alpha test
  6305. if (material && material.needAlphaTesting()) {
  6306. var alphaTexture = material.getAlphaTestTexture();
  6307. _this._effect.setTexture("diffuseSampler", alphaTexture);
  6308. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  6309. }
  6310. // Bones
  6311. if (mesh.useBones) {
  6312. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  6313. }
  6314. // Draw
  6315. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  6316. }
  6317. else {
  6318. // Need to reset refresh rate of the shadowMap
  6319. _this._shadowMap.resetRefreshCounter();
  6320. }
  6321. };
  6322. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  6323. var index;
  6324. for (index = 0; index < opaqueSubMeshes.length; index++) {
  6325. renderSubMesh(opaqueSubMeshes.data[index]);
  6326. }
  6327. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  6328. renderSubMesh(alphaTestSubMeshes.data[index]);
  6329. }
  6330. if (_this._transparencyShadow) {
  6331. for (index = 0; index < transparentSubMeshes.length; index++) {
  6332. renderSubMesh(transparentSubMeshes.data[index]);
  6333. }
  6334. }
  6335. };
  6336. this._shadowMap.onClear = function (engine) {
  6337. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  6338. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  6339. }
  6340. else {
  6341. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  6342. }
  6343. };
  6344. }
  6345. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  6346. // Static
  6347. get: function () {
  6348. return ShadowGenerator._FILTER_NONE;
  6349. },
  6350. enumerable: true,
  6351. configurable: true
  6352. });
  6353. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  6354. get: function () {
  6355. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  6356. },
  6357. enumerable: true,
  6358. configurable: true
  6359. });
  6360. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  6361. get: function () {
  6362. return ShadowGenerator._FILTER_POISSONSAMPLING;
  6363. },
  6364. enumerable: true,
  6365. configurable: true
  6366. });
  6367. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  6368. get: function () {
  6369. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  6370. },
  6371. enumerable: true,
  6372. configurable: true
  6373. });
  6374. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  6375. get: function () {
  6376. return this._bias;
  6377. },
  6378. set: function (bias) {
  6379. this._bias = bias;
  6380. },
  6381. enumerable: true,
  6382. configurable: true
  6383. });
  6384. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  6385. get: function () {
  6386. return this._blurBoxOffset;
  6387. },
  6388. set: function (value) {
  6389. var _this = this;
  6390. if (this._blurBoxOffset === value) {
  6391. return;
  6392. }
  6393. this._blurBoxOffset = value;
  6394. if (this._boxBlurPostprocess) {
  6395. this._boxBlurPostprocess.dispose();
  6396. }
  6397. 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);
  6398. this._boxBlurPostprocess.onApply = function (effect) {
  6399. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  6400. };
  6401. },
  6402. enumerable: true,
  6403. configurable: true
  6404. });
  6405. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  6406. get: function () {
  6407. return this._filter;
  6408. },
  6409. set: function (value) {
  6410. if (this._filter === value) {
  6411. return;
  6412. }
  6413. this._filter = value;
  6414. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6415. this._shadowMap.anisotropicFilteringLevel = 16;
  6416. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  6417. }
  6418. else {
  6419. this._shadowMap.anisotropicFilteringLevel = 1;
  6420. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6421. }
  6422. },
  6423. enumerable: true,
  6424. configurable: true
  6425. });
  6426. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  6427. get: function () {
  6428. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  6429. },
  6430. set: function (value) {
  6431. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6432. },
  6433. enumerable: true,
  6434. configurable: true
  6435. });
  6436. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  6437. get: function () {
  6438. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING || (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP || this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  6439. },
  6440. set: function (value) {
  6441. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  6442. },
  6443. enumerable: true,
  6444. configurable: true
  6445. });
  6446. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  6447. get: function () {
  6448. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  6449. },
  6450. set: function (value) {
  6451. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6452. },
  6453. enumerable: true,
  6454. configurable: true
  6455. });
  6456. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  6457. var defines = [];
  6458. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6459. defines.push("#define VSM");
  6460. }
  6461. var attribs = [BABYLON.VertexBuffer.PositionKind];
  6462. var mesh = subMesh.getMesh();
  6463. var material = subMesh.getMaterial();
  6464. // Alpha test
  6465. if (material && material.needAlphaTesting()) {
  6466. defines.push("#define ALPHATEST");
  6467. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  6468. attribs.push(BABYLON.VertexBuffer.UVKind);
  6469. defines.push("#define UV1");
  6470. }
  6471. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  6472. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  6473. defines.push("#define UV2");
  6474. }
  6475. }
  6476. // Bones
  6477. if (mesh.useBones) {
  6478. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  6479. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  6480. defines.push("#define BONES");
  6481. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  6482. }
  6483. // Instances
  6484. if (useInstances) {
  6485. defines.push("#define INSTANCES");
  6486. attribs.push("world0");
  6487. attribs.push("world1");
  6488. attribs.push("world2");
  6489. attribs.push("world3");
  6490. }
  6491. // Get correct effect
  6492. var join = defines.join("\n");
  6493. if (this._cachedDefines !== join) {
  6494. this._cachedDefines = join;
  6495. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  6496. }
  6497. return this._effect.isReady();
  6498. };
  6499. ShadowGenerator.prototype.getShadowMap = function () {
  6500. return this._shadowMap;
  6501. };
  6502. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  6503. if (this._shadowMap2) {
  6504. return this._shadowMap2;
  6505. }
  6506. return this._shadowMap;
  6507. };
  6508. ShadowGenerator.prototype.getLight = function () {
  6509. return this._light;
  6510. };
  6511. // Methods
  6512. ShadowGenerator.prototype.getTransformMatrix = function () {
  6513. var scene = this._scene;
  6514. if (this._currentRenderID === scene.getRenderId()) {
  6515. return this._transformMatrix;
  6516. }
  6517. this._currentRenderID = scene.getRenderId();
  6518. var lightPosition = this._light.position;
  6519. var lightDirection = this._light.direction;
  6520. if (this._light.computeTransformedPosition()) {
  6521. lightPosition = this._light.transformedPosition;
  6522. }
  6523. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  6524. this._cachedPosition = lightPosition.clone();
  6525. this._cachedDirection = lightDirection.clone();
  6526. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  6527. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  6528. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6529. }
  6530. return this._transformMatrix;
  6531. };
  6532. ShadowGenerator.prototype.getDarkness = function () {
  6533. return this._darkness;
  6534. };
  6535. ShadowGenerator.prototype.setDarkness = function (darkness) {
  6536. if (darkness >= 1.0)
  6537. this._darkness = 1.0;
  6538. else if (darkness <= 0.0)
  6539. this._darkness = 0.0;
  6540. else
  6541. this._darkness = darkness;
  6542. };
  6543. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  6544. this._transparencyShadow = hasShadow;
  6545. };
  6546. ShadowGenerator.prototype._packHalf = function (depth) {
  6547. var scale = depth * 255.0;
  6548. var fract = scale - Math.floor(scale);
  6549. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  6550. };
  6551. ShadowGenerator.prototype.dispose = function () {
  6552. this._shadowMap.dispose();
  6553. if (this._shadowMap2) {
  6554. this._shadowMap2.dispose();
  6555. }
  6556. if (this._downSamplePostprocess) {
  6557. this._downSamplePostprocess.dispose();
  6558. }
  6559. if (this._boxBlurPostprocess) {
  6560. this._boxBlurPostprocess.dispose();
  6561. }
  6562. };
  6563. ShadowGenerator._FILTER_NONE = 0;
  6564. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  6565. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  6566. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  6567. return ShadowGenerator;
  6568. })();
  6569. BABYLON.ShadowGenerator = ShadowGenerator;
  6570. })(BABYLON || (BABYLON = {}));
  6571. //# sourceMappingURL=babylon.shadowGenerator.js.map
  6572. var BABYLON;
  6573. (function (BABYLON) {
  6574. var HemisphericLight = (function (_super) {
  6575. __extends(HemisphericLight, _super);
  6576. function HemisphericLight(name, direction, scene) {
  6577. _super.call(this, name, scene);
  6578. this.direction = direction;
  6579. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  6580. }
  6581. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  6582. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  6583. return this.direction;
  6584. };
  6585. HemisphericLight.prototype.getShadowGenerator = function () {
  6586. return null;
  6587. };
  6588. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  6589. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6590. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  6591. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  6592. };
  6593. HemisphericLight.prototype._getWorldMatrix = function () {
  6594. if (!this._worldMatrix) {
  6595. this._worldMatrix = BABYLON.Matrix.Identity();
  6596. }
  6597. return this._worldMatrix;
  6598. };
  6599. return HemisphericLight;
  6600. })(BABYLON.Light);
  6601. BABYLON.HemisphericLight = HemisphericLight;
  6602. })(BABYLON || (BABYLON = {}));
  6603. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  6604. (function (BABYLON) {
  6605. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  6606. if (boxMin.x > sphereCenter.x + sphereRadius)
  6607. return false;
  6608. if (sphereCenter.x - sphereRadius > boxMax.x)
  6609. return false;
  6610. if (boxMin.y > sphereCenter.y + sphereRadius)
  6611. return false;
  6612. if (sphereCenter.y - sphereRadius > boxMax.y)
  6613. return false;
  6614. if (boxMin.z > sphereCenter.z + sphereRadius)
  6615. return false;
  6616. if (sphereCenter.z - sphereRadius > boxMax.z)
  6617. return false;
  6618. return true;
  6619. };
  6620. var getLowestRoot = function (a, b, c, maxR) {
  6621. var determinant = b * b - 4.0 * a * c;
  6622. var result = { root: 0, found: false };
  6623. if (determinant < 0)
  6624. return result;
  6625. var sqrtD = Math.sqrt(determinant);
  6626. var r1 = (-b - sqrtD) / (2.0 * a);
  6627. var r2 = (-b + sqrtD) / (2.0 * a);
  6628. if (r1 > r2) {
  6629. var temp = r2;
  6630. r2 = r1;
  6631. r1 = temp;
  6632. }
  6633. if (r1 > 0 && r1 < maxR) {
  6634. result.root = r1;
  6635. result.found = true;
  6636. return result;
  6637. }
  6638. if (r2 > 0 && r2 < maxR) {
  6639. result.root = r2;
  6640. result.found = true;
  6641. return result;
  6642. }
  6643. return result;
  6644. };
  6645. var Collider = (function () {
  6646. function Collider() {
  6647. this.radius = new BABYLON.Vector3(1, 1, 1);
  6648. this.retry = 0;
  6649. this.basePointWorld = BABYLON.Vector3.Zero();
  6650. this.velocityWorld = BABYLON.Vector3.Zero();
  6651. this.normalizedVelocity = BABYLON.Vector3.Zero();
  6652. this._collisionPoint = BABYLON.Vector3.Zero();
  6653. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  6654. this._tempVector = BABYLON.Vector3.Zero();
  6655. this._tempVector2 = BABYLON.Vector3.Zero();
  6656. this._tempVector3 = BABYLON.Vector3.Zero();
  6657. this._tempVector4 = BABYLON.Vector3.Zero();
  6658. this._edge = BABYLON.Vector3.Zero();
  6659. this._baseToVertex = BABYLON.Vector3.Zero();
  6660. this._destinationPoint = BABYLON.Vector3.Zero();
  6661. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  6662. this._displacementVector = BABYLON.Vector3.Zero();
  6663. }
  6664. // Methods
  6665. Collider.prototype._initialize = function (source, dir, e) {
  6666. this.velocity = dir;
  6667. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  6668. this.basePoint = source;
  6669. source.multiplyToRef(this.radius, this.basePointWorld);
  6670. dir.multiplyToRef(this.radius, this.velocityWorld);
  6671. this.velocityWorldLength = this.velocityWorld.length();
  6672. this.epsilon = e;
  6673. this.collisionFound = false;
  6674. };
  6675. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  6676. pa.subtractToRef(point, this._tempVector);
  6677. pb.subtractToRef(point, this._tempVector2);
  6678. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  6679. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6680. if (d < 0)
  6681. return false;
  6682. pc.subtractToRef(point, this._tempVector3);
  6683. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  6684. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6685. if (d < 0)
  6686. return false;
  6687. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  6688. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6689. return d >= 0;
  6690. };
  6691. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  6692. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  6693. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  6694. if (distance > this.velocityWorldLength + max + sphereRadius) {
  6695. return false;
  6696. }
  6697. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  6698. return false;
  6699. return true;
  6700. };
  6701. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  6702. var t0;
  6703. var embeddedInPlane = false;
  6704. if (!subMesh._trianglePlanes) {
  6705. subMesh._trianglePlanes = [];
  6706. }
  6707. if (!subMesh._trianglePlanes[faceIndex]) {
  6708. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  6709. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  6710. }
  6711. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  6712. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  6713. return;
  6714. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  6715. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  6716. if (normalDotVelocity == 0) {
  6717. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  6718. return;
  6719. embeddedInPlane = true;
  6720. t0 = 0;
  6721. }
  6722. else {
  6723. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6724. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6725. if (t0 > t1) {
  6726. var temp = t1;
  6727. t1 = t0;
  6728. t0 = temp;
  6729. }
  6730. if (t0 > 1.0 || t1 < 0.0)
  6731. return;
  6732. if (t0 < 0)
  6733. t0 = 0;
  6734. if (t0 > 1.0)
  6735. t0 = 1.0;
  6736. }
  6737. this._collisionPoint.copyFromFloats(0, 0, 0);
  6738. var found = false;
  6739. var t = 1.0;
  6740. if (!embeddedInPlane) {
  6741. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  6742. this.velocity.scaleToRef(t0, this._tempVector);
  6743. this._planeIntersectionPoint.addInPlace(this._tempVector);
  6744. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  6745. found = true;
  6746. t = t0;
  6747. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  6748. }
  6749. }
  6750. if (!found) {
  6751. var velocitySquaredLength = this.velocity.lengthSquared();
  6752. var a = velocitySquaredLength;
  6753. this.basePoint.subtractToRef(p1, this._tempVector);
  6754. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6755. var c = this._tempVector.lengthSquared() - 1.0;
  6756. var lowestRoot = getLowestRoot(a, b, c, t);
  6757. if (lowestRoot.found) {
  6758. t = lowestRoot.root;
  6759. found = true;
  6760. this._collisionPoint.copyFrom(p1);
  6761. }
  6762. this.basePoint.subtractToRef(p2, this._tempVector);
  6763. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6764. c = this._tempVector.lengthSquared() - 1.0;
  6765. lowestRoot = getLowestRoot(a, b, c, t);
  6766. if (lowestRoot.found) {
  6767. t = lowestRoot.root;
  6768. found = true;
  6769. this._collisionPoint.copyFrom(p2);
  6770. }
  6771. this.basePoint.subtractToRef(p3, this._tempVector);
  6772. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6773. c = this._tempVector.lengthSquared() - 1.0;
  6774. lowestRoot = getLowestRoot(a, b, c, t);
  6775. if (lowestRoot.found) {
  6776. t = lowestRoot.root;
  6777. found = true;
  6778. this._collisionPoint.copyFrom(p3);
  6779. }
  6780. p2.subtractToRef(p1, this._edge);
  6781. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6782. var edgeSquaredLength = this._edge.lengthSquared();
  6783. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6784. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6785. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6786. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6787. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6788. lowestRoot = getLowestRoot(a, b, c, t);
  6789. if (lowestRoot.found) {
  6790. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6791. if (f >= 0.0 && f <= 1.0) {
  6792. t = lowestRoot.root;
  6793. found = true;
  6794. this._edge.scaleInPlace(f);
  6795. p1.addToRef(this._edge, this._collisionPoint);
  6796. }
  6797. }
  6798. p3.subtractToRef(p2, this._edge);
  6799. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6800. edgeSquaredLength = this._edge.lengthSquared();
  6801. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6802. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6803. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6804. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6805. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6806. lowestRoot = getLowestRoot(a, b, c, t);
  6807. if (lowestRoot.found) {
  6808. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6809. if (f >= 0.0 && f <= 1.0) {
  6810. t = lowestRoot.root;
  6811. found = true;
  6812. this._edge.scaleInPlace(f);
  6813. p2.addToRef(this._edge, this._collisionPoint);
  6814. }
  6815. }
  6816. p1.subtractToRef(p3, this._edge);
  6817. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6818. edgeSquaredLength = this._edge.lengthSquared();
  6819. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6820. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6821. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6822. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6823. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6824. lowestRoot = getLowestRoot(a, b, c, t);
  6825. if (lowestRoot.found) {
  6826. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6827. if (f >= 0.0 && f <= 1.0) {
  6828. t = lowestRoot.root;
  6829. found = true;
  6830. this._edge.scaleInPlace(f);
  6831. p3.addToRef(this._edge, this._collisionPoint);
  6832. }
  6833. }
  6834. }
  6835. if (found) {
  6836. var distToCollision = t * this.velocity.length();
  6837. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6838. if (!this.intersectionPoint) {
  6839. this.intersectionPoint = this._collisionPoint.clone();
  6840. }
  6841. else {
  6842. this.intersectionPoint.copyFrom(this._collisionPoint);
  6843. }
  6844. this.nearestDistance = distToCollision;
  6845. this.collisionFound = true;
  6846. this.collidedMesh = subMesh.getMesh();
  6847. }
  6848. }
  6849. };
  6850. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6851. for (var i = indexStart; i < indexEnd; i += 3) {
  6852. var p1 = pts[indices[i] - decal];
  6853. var p2 = pts[indices[i + 1] - decal];
  6854. var p3 = pts[indices[i + 2] - decal];
  6855. this._testTriangle(i, subMesh, p3, p2, p1);
  6856. }
  6857. };
  6858. Collider.prototype._getResponse = function (pos, vel) {
  6859. pos.addToRef(vel, this._destinationPoint);
  6860. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6861. this.basePoint.addToRef(vel, pos);
  6862. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6863. this._slidePlaneNormal.normalize();
  6864. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6865. pos.addInPlace(this._displacementVector);
  6866. this.intersectionPoint.addInPlace(this._displacementVector);
  6867. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6868. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6869. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6870. };
  6871. return Collider;
  6872. })();
  6873. BABYLON.Collider = Collider;
  6874. })(BABYLON || (BABYLON = {}));
  6875. //# sourceMappingURL=babylon.collider.js.map
  6876. var BABYLON;
  6877. (function (BABYLON) {
  6878. var Camera = (function (_super) {
  6879. __extends(Camera, _super);
  6880. function Camera(name, position, scene) {
  6881. _super.call(this, name, scene);
  6882. this.position = position;
  6883. // Members
  6884. this.upVector = BABYLON.Vector3.Up();
  6885. this.orthoLeft = null;
  6886. this.orthoRight = null;
  6887. this.orthoBottom = null;
  6888. this.orthoTop = null;
  6889. this.fov = 0.8;
  6890. this.minZ = 1.0;
  6891. this.maxZ = 10000.0;
  6892. this.inertia = 0.9;
  6893. this.mode = Camera.PERSPECTIVE_CAMERA;
  6894. this.isIntermediate = false;
  6895. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6896. this.subCameras = [];
  6897. this.layerMask = 0xFFFFFFFF;
  6898. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  6899. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6900. this._projectionMatrix = new BABYLON.Matrix();
  6901. this._postProcesses = new Array();
  6902. this._postProcessesTakenIndices = [];
  6903. this._activeMeshes = new BABYLON.SmartArray(256);
  6904. this._globalPosition = BABYLON.Vector3.Zero();
  6905. scene.addCamera(this);
  6906. if (!scene.activeCamera) {
  6907. scene.activeCamera = this;
  6908. }
  6909. }
  6910. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  6911. get: function () {
  6912. return Camera._PERSPECTIVE_CAMERA;
  6913. },
  6914. enumerable: true,
  6915. configurable: true
  6916. });
  6917. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  6918. get: function () {
  6919. return Camera._ORTHOGRAPHIC_CAMERA;
  6920. },
  6921. enumerable: true,
  6922. configurable: true
  6923. });
  6924. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  6925. get: function () {
  6926. return Camera._FOVMODE_VERTICAL_FIXED;
  6927. },
  6928. enumerable: true,
  6929. configurable: true
  6930. });
  6931. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  6932. get: function () {
  6933. return Camera._FOVMODE_HORIZONTAL_FIXED;
  6934. },
  6935. enumerable: true,
  6936. configurable: true
  6937. });
  6938. Object.defineProperty(Camera.prototype, "globalPosition", {
  6939. get: function () {
  6940. return this._globalPosition;
  6941. },
  6942. enumerable: true,
  6943. configurable: true
  6944. });
  6945. Camera.prototype.getActiveMeshes = function () {
  6946. return this._activeMeshes;
  6947. };
  6948. Camera.prototype.isActiveMesh = function (mesh) {
  6949. return (this._activeMeshes.indexOf(mesh) !== -1);
  6950. };
  6951. //Cache
  6952. Camera.prototype._initCache = function () {
  6953. _super.prototype._initCache.call(this);
  6954. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6955. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6956. this._cache.mode = undefined;
  6957. this._cache.minZ = undefined;
  6958. this._cache.maxZ = undefined;
  6959. this._cache.fov = undefined;
  6960. this._cache.aspectRatio = undefined;
  6961. this._cache.orthoLeft = undefined;
  6962. this._cache.orthoRight = undefined;
  6963. this._cache.orthoBottom = undefined;
  6964. this._cache.orthoTop = undefined;
  6965. this._cache.renderWidth = undefined;
  6966. this._cache.renderHeight = undefined;
  6967. };
  6968. Camera.prototype._updateCache = function (ignoreParentClass) {
  6969. if (!ignoreParentClass) {
  6970. _super.prototype._updateCache.call(this);
  6971. }
  6972. var engine = this.getEngine();
  6973. this._cache.position.copyFrom(this.position);
  6974. this._cache.upVector.copyFrom(this.upVector);
  6975. this._cache.mode = this.mode;
  6976. this._cache.minZ = this.minZ;
  6977. this._cache.maxZ = this.maxZ;
  6978. this._cache.fov = this.fov;
  6979. this._cache.aspectRatio = engine.getAspectRatio(this);
  6980. this._cache.orthoLeft = this.orthoLeft;
  6981. this._cache.orthoRight = this.orthoRight;
  6982. this._cache.orthoBottom = this.orthoBottom;
  6983. this._cache.orthoTop = this.orthoTop;
  6984. this._cache.renderWidth = engine.getRenderWidth();
  6985. this._cache.renderHeight = engine.getRenderHeight();
  6986. };
  6987. Camera.prototype._updateFromScene = function () {
  6988. this.updateCache();
  6989. this._update();
  6990. };
  6991. // Synchronized
  6992. Camera.prototype._isSynchronized = function () {
  6993. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6994. };
  6995. Camera.prototype._isSynchronizedViewMatrix = function () {
  6996. if (!_super.prototype._isSynchronized.call(this))
  6997. return false;
  6998. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6999. };
  7000. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  7001. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  7002. if (!check) {
  7003. return false;
  7004. }
  7005. var engine = this.getEngine();
  7006. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  7007. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  7008. }
  7009. else {
  7010. 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();
  7011. }
  7012. return check;
  7013. };
  7014. // Controls
  7015. Camera.prototype.attachControl = function (element) {
  7016. };
  7017. Camera.prototype.detachControl = function (element) {
  7018. };
  7019. Camera.prototype._update = function () {
  7020. };
  7021. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  7022. if (insertAt === void 0) { insertAt = null; }
  7023. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  7024. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  7025. return 0;
  7026. }
  7027. if (insertAt == null || insertAt < 0) {
  7028. this._postProcesses.push(postProcess);
  7029. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  7030. return this._postProcesses.length - 1;
  7031. }
  7032. var add = 0;
  7033. if (this._postProcesses[insertAt]) {
  7034. var start = this._postProcesses.length - 1;
  7035. for (var i = start; i >= insertAt + 1; --i) {
  7036. this._postProcesses[i + 1] = this._postProcesses[i];
  7037. }
  7038. add = 1;
  7039. }
  7040. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  7041. if (this._postProcessesTakenIndices[i] < insertAt) {
  7042. continue;
  7043. }
  7044. start = this._postProcessesTakenIndices.length - 1;
  7045. for (var j = start; j >= i; --j) {
  7046. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  7047. }
  7048. this._postProcessesTakenIndices[i] = insertAt;
  7049. break;
  7050. }
  7051. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  7052. this._postProcessesTakenIndices.push(insertAt);
  7053. }
  7054. var result = insertAt + add;
  7055. this._postProcesses[result] = postProcess;
  7056. return result;
  7057. };
  7058. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  7059. if (atIndices === void 0) { atIndices = null; }
  7060. var result = [];
  7061. if (!atIndices) {
  7062. var length = this._postProcesses.length;
  7063. for (var i = 0; i < length; i++) {
  7064. if (this._postProcesses[i] !== postProcess) {
  7065. continue;
  7066. }
  7067. delete this._postProcesses[i];
  7068. var index = this._postProcessesTakenIndices.indexOf(i);
  7069. this._postProcessesTakenIndices.splice(index, 1);
  7070. }
  7071. }
  7072. else {
  7073. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  7074. for (i = 0; i < atIndices.length; i++) {
  7075. var foundPostProcess = this._postProcesses[atIndices[i]];
  7076. if (foundPostProcess !== postProcess) {
  7077. result.push(i);
  7078. continue;
  7079. }
  7080. delete this._postProcesses[atIndices[i]];
  7081. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  7082. this._postProcessesTakenIndices.splice(index, 1);
  7083. }
  7084. }
  7085. return result;
  7086. };
  7087. Camera.prototype.getWorldMatrix = function () {
  7088. if (!this._worldMatrix) {
  7089. this._worldMatrix = BABYLON.Matrix.Identity();
  7090. }
  7091. var viewMatrix = this.getViewMatrix();
  7092. viewMatrix.invertToRef(this._worldMatrix);
  7093. return this._worldMatrix;
  7094. };
  7095. Camera.prototype._getViewMatrix = function () {
  7096. return BABYLON.Matrix.Identity();
  7097. };
  7098. Camera.prototype.getViewMatrix = function () {
  7099. this._computedViewMatrix = this._computeViewMatrix();
  7100. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  7101. this._globalPosition.copyFrom(this.position);
  7102. return this._computedViewMatrix;
  7103. }
  7104. if (!this._worldMatrix) {
  7105. this._worldMatrix = BABYLON.Matrix.Identity();
  7106. }
  7107. this._computedViewMatrix.invertToRef(this._worldMatrix);
  7108. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  7109. this._computedViewMatrix.invert();
  7110. this._currentRenderId = this.getScene().getRenderId();
  7111. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  7112. return this._computedViewMatrix;
  7113. };
  7114. Camera.prototype._computeViewMatrix = function (force) {
  7115. if (!force && this._isSynchronizedViewMatrix()) {
  7116. return this._computedViewMatrix;
  7117. }
  7118. this._computedViewMatrix = this._getViewMatrix();
  7119. if (!this.parent || !this.parent.getWorldMatrix) {
  7120. this._currentRenderId = this.getScene().getRenderId();
  7121. }
  7122. return this._computedViewMatrix;
  7123. };
  7124. Camera.prototype.getProjectionMatrix = function (force) {
  7125. if (!force && this._isSynchronizedProjectionMatrix()) {
  7126. return this._projectionMatrix;
  7127. }
  7128. var engine = this.getEngine();
  7129. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  7130. if (this.minZ <= 0) {
  7131. this.minZ = 0.1;
  7132. }
  7133. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  7134. return this._projectionMatrix;
  7135. }
  7136. var halfWidth = engine.getRenderWidth() / 2.0;
  7137. var halfHeight = engine.getRenderHeight() / 2.0;
  7138. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  7139. return this._projectionMatrix;
  7140. };
  7141. Camera.prototype.dispose = function () {
  7142. // Remove from scene
  7143. this.getScene().removeCamera(this);
  7144. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  7145. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  7146. }
  7147. };
  7148. // Statics
  7149. Camera._PERSPECTIVE_CAMERA = 0;
  7150. Camera._ORTHOGRAPHIC_CAMERA = 1;
  7151. Camera._FOVMODE_VERTICAL_FIXED = 0;
  7152. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  7153. return Camera;
  7154. })(BABYLON.Node);
  7155. BABYLON.Camera = Camera;
  7156. })(BABYLON || (BABYLON = {}));
  7157. //# sourceMappingURL=babylon.camera.js.map
  7158. var BABYLON;
  7159. (function (BABYLON) {
  7160. var TargetCamera = (function (_super) {
  7161. __extends(TargetCamera, _super);
  7162. function TargetCamera(name, position, scene) {
  7163. _super.call(this, name, position, scene);
  7164. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7165. this.cameraRotation = new BABYLON.Vector2(0, 0);
  7166. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7167. this.speed = 2.0;
  7168. this.noRotationConstraint = false;
  7169. this.lockedTarget = null;
  7170. this._currentTarget = BABYLON.Vector3.Zero();
  7171. this._viewMatrix = BABYLON.Matrix.Zero();
  7172. this._camMatrix = BABYLON.Matrix.Zero();
  7173. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  7174. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  7175. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  7176. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  7177. this._lookAtTemp = BABYLON.Matrix.Zero();
  7178. this._tempMatrix = BABYLON.Matrix.Zero();
  7179. }
  7180. TargetCamera.prototype._getLockedTargetPosition = function () {
  7181. if (!this.lockedTarget) {
  7182. return null;
  7183. }
  7184. return this.lockedTarget.position || this.lockedTarget;
  7185. };
  7186. // Cache
  7187. TargetCamera.prototype._initCache = function () {
  7188. _super.prototype._initCache.call(this);
  7189. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7190. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7191. };
  7192. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  7193. if (!ignoreParentClass) {
  7194. _super.prototype._updateCache.call(this);
  7195. }
  7196. var lockedTargetPosition = this._getLockedTargetPosition();
  7197. if (!lockedTargetPosition) {
  7198. this._cache.lockedTarget = null;
  7199. }
  7200. else {
  7201. if (!this._cache.lockedTarget) {
  7202. this._cache.lockedTarget = lockedTargetPosition.clone();
  7203. }
  7204. else {
  7205. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  7206. }
  7207. }
  7208. this._cache.rotation.copyFrom(this.rotation);
  7209. };
  7210. // Synchronized
  7211. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  7212. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  7213. return false;
  7214. }
  7215. var lockedTargetPosition = this._getLockedTargetPosition();
  7216. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  7217. };
  7218. // Methods
  7219. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  7220. var engine = this.getEngine();
  7221. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  7222. };
  7223. // Target
  7224. TargetCamera.prototype.setTarget = function (target) {
  7225. this.upVector.normalize();
  7226. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  7227. this._camMatrix.invert();
  7228. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  7229. var vDir = target.subtract(this.position);
  7230. if (vDir.x >= 0.0) {
  7231. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  7232. }
  7233. else {
  7234. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  7235. }
  7236. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  7237. if (isNaN(this.rotation.x)) {
  7238. this.rotation.x = 0;
  7239. }
  7240. if (isNaN(this.rotation.y)) {
  7241. this.rotation.y = 0;
  7242. }
  7243. if (isNaN(this.rotation.z)) {
  7244. this.rotation.z = 0;
  7245. }
  7246. };
  7247. TargetCamera.prototype.getTarget = function () {
  7248. return this._currentTarget;
  7249. };
  7250. TargetCamera.prototype._decideIfNeedsToMove = function () {
  7251. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7252. };
  7253. TargetCamera.prototype._updatePosition = function () {
  7254. this.position.addInPlace(this.cameraDirection);
  7255. };
  7256. TargetCamera.prototype._update = function () {
  7257. var needToMove = this._decideIfNeedsToMove();
  7258. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  7259. // Move
  7260. if (needToMove) {
  7261. this._updatePosition();
  7262. }
  7263. // Rotate
  7264. if (needToRotate) {
  7265. this.rotation.x += this.cameraRotation.x;
  7266. this.rotation.y += this.cameraRotation.y;
  7267. if (!this.noRotationConstraint) {
  7268. var limit = (Math.PI / 2) * 0.95;
  7269. if (this.rotation.x > limit)
  7270. this.rotation.x = limit;
  7271. if (this.rotation.x < -limit)
  7272. this.rotation.x = -limit;
  7273. }
  7274. }
  7275. // Inertia
  7276. if (needToMove) {
  7277. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  7278. this.cameraDirection.x = 0;
  7279. }
  7280. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  7281. this.cameraDirection.y = 0;
  7282. }
  7283. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  7284. this.cameraDirection.z = 0;
  7285. }
  7286. this.cameraDirection.scaleInPlace(this.inertia);
  7287. }
  7288. if (needToRotate) {
  7289. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  7290. this.cameraRotation.x = 0;
  7291. }
  7292. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  7293. this.cameraRotation.y = 0;
  7294. }
  7295. this.cameraRotation.scaleInPlace(this.inertia);
  7296. }
  7297. };
  7298. TargetCamera.prototype._getViewMatrix = function () {
  7299. if (!this.lockedTarget) {
  7300. // Compute
  7301. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  7302. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  7303. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  7304. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  7305. this._lookAtTemp.invert();
  7306. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  7307. }
  7308. else {
  7309. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  7310. }
  7311. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  7312. // Computing target and final matrix
  7313. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  7314. }
  7315. else {
  7316. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  7317. }
  7318. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  7319. return this._viewMatrix;
  7320. };
  7321. return TargetCamera;
  7322. })(BABYLON.Camera);
  7323. BABYLON.TargetCamera = TargetCamera;
  7324. })(BABYLON || (BABYLON = {}));
  7325. //# sourceMappingURL=babylon.targetCamera.js.map
  7326. var BABYLON;
  7327. (function (BABYLON) {
  7328. var FollowCamera = (function (_super) {
  7329. __extends(FollowCamera, _super);
  7330. function FollowCamera(name, position, scene) {
  7331. _super.call(this, name, position, scene);
  7332. this.radius = 12;
  7333. this.rotationOffset = 0;
  7334. this.heightOffset = 4;
  7335. this.cameraAcceleration = 0.05;
  7336. this.maxCameraSpeed = 20;
  7337. }
  7338. FollowCamera.prototype.getRadians = function (degrees) {
  7339. return degrees * Math.PI / 180;
  7340. };
  7341. FollowCamera.prototype.follow = function (cameraTarget) {
  7342. if (!cameraTarget)
  7343. return;
  7344. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  7345. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  7346. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  7347. var dx = targetX - this.position.x;
  7348. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  7349. var dz = (targetZ) - this.position.z;
  7350. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  7351. var vy = dy * this.cameraAcceleration;
  7352. var vz = dz * this.cameraAcceleration * 2;
  7353. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  7354. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7355. }
  7356. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  7357. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7358. }
  7359. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  7360. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7361. }
  7362. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  7363. this.setTarget(cameraTarget.position);
  7364. };
  7365. FollowCamera.prototype._update = function () {
  7366. _super.prototype._update.call(this);
  7367. this.follow(this.target);
  7368. };
  7369. return FollowCamera;
  7370. })(BABYLON.TargetCamera);
  7371. BABYLON.FollowCamera = FollowCamera;
  7372. })(BABYLON || (BABYLON = {}));
  7373. //# sourceMappingURL=babylon.followCamera.js.map
  7374. var BABYLON;
  7375. (function (BABYLON) {
  7376. var FreeCamera = (function (_super) {
  7377. __extends(FreeCamera, _super);
  7378. function FreeCamera(name, position, scene) {
  7379. _super.call(this, name, position, scene);
  7380. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7381. this.keysUp = [38];
  7382. this.keysDown = [40];
  7383. this.keysLeft = [37];
  7384. this.keysRight = [39];
  7385. this.checkCollisions = false;
  7386. this.applyGravity = false;
  7387. this.angularSensibility = 2000.0;
  7388. this._keys = [];
  7389. this._collider = new BABYLON.Collider();
  7390. this._needMoveForGravity = true;
  7391. this._oldPosition = BABYLON.Vector3.Zero();
  7392. this._diffPosition = BABYLON.Vector3.Zero();
  7393. this._newPosition = BABYLON.Vector3.Zero();
  7394. }
  7395. // Controls
  7396. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  7397. var _this = this;
  7398. var previousPosition;
  7399. var engine = this.getEngine();
  7400. if (this._attachedElement) {
  7401. return;
  7402. }
  7403. this._attachedElement = element;
  7404. if (this._onMouseDown === undefined) {
  7405. this._onMouseDown = function (evt) {
  7406. previousPosition = {
  7407. x: evt.clientX,
  7408. y: evt.clientY
  7409. };
  7410. if (!noPreventDefault) {
  7411. evt.preventDefault();
  7412. }
  7413. };
  7414. this._onMouseUp = function (evt) {
  7415. previousPosition = null;
  7416. if (!noPreventDefault) {
  7417. evt.preventDefault();
  7418. }
  7419. };
  7420. this._onMouseOut = function (evt) {
  7421. previousPosition = null;
  7422. _this._keys = [];
  7423. if (!noPreventDefault) {
  7424. evt.preventDefault();
  7425. }
  7426. };
  7427. this._onMouseMove = function (evt) {
  7428. if (!previousPosition && !engine.isPointerLock) {
  7429. return;
  7430. }
  7431. var offsetX;
  7432. var offsetY;
  7433. if (!engine.isPointerLock) {
  7434. offsetX = evt.clientX - previousPosition.x;
  7435. offsetY = evt.clientY - previousPosition.y;
  7436. }
  7437. else {
  7438. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7439. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7440. }
  7441. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  7442. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  7443. previousPosition = {
  7444. x: evt.clientX,
  7445. y: evt.clientY
  7446. };
  7447. if (!noPreventDefault) {
  7448. evt.preventDefault();
  7449. }
  7450. };
  7451. this._onKeyDown = function (evt) {
  7452. 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) {
  7453. var index = _this._keys.indexOf(evt.keyCode);
  7454. if (index === -1) {
  7455. _this._keys.push(evt.keyCode);
  7456. }
  7457. if (!noPreventDefault) {
  7458. evt.preventDefault();
  7459. }
  7460. }
  7461. };
  7462. this._onKeyUp = function (evt) {
  7463. 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) {
  7464. var index = _this._keys.indexOf(evt.keyCode);
  7465. if (index >= 0) {
  7466. _this._keys.splice(index, 1);
  7467. }
  7468. if (!noPreventDefault) {
  7469. evt.preventDefault();
  7470. }
  7471. }
  7472. };
  7473. this._onLostFocus = function () {
  7474. _this._keys = [];
  7475. };
  7476. this._reset = function () {
  7477. _this._keys = [];
  7478. previousPosition = null;
  7479. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7480. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  7481. };
  7482. }
  7483. element.addEventListener("mousedown", this._onMouseDown, false);
  7484. element.addEventListener("mouseup", this._onMouseUp, false);
  7485. element.addEventListener("mouseout", this._onMouseOut, false);
  7486. element.addEventListener("mousemove", this._onMouseMove, false);
  7487. BABYLON.Tools.RegisterTopRootEvents([
  7488. { name: "keydown", handler: this._onKeyDown },
  7489. { name: "keyup", handler: this._onKeyUp },
  7490. { name: "blur", handler: this._onLostFocus }
  7491. ]);
  7492. };
  7493. FreeCamera.prototype.detachControl = function (element) {
  7494. if (this._attachedElement != element) {
  7495. return;
  7496. }
  7497. element.removeEventListener("mousedown", this._onMouseDown);
  7498. element.removeEventListener("mouseup", this._onMouseUp);
  7499. element.removeEventListener("mouseout", this._onMouseOut);
  7500. element.removeEventListener("mousemove", this._onMouseMove);
  7501. BABYLON.Tools.UnregisterTopRootEvents([
  7502. { name: "keydown", handler: this._onKeyDown },
  7503. { name: "keyup", handler: this._onKeyUp },
  7504. { name: "blur", handler: this._onLostFocus }
  7505. ]);
  7506. this._attachedElement = null;
  7507. if (this._reset) {
  7508. this._reset();
  7509. }
  7510. };
  7511. FreeCamera.prototype._collideWithWorld = function (velocity) {
  7512. var globalPosition;
  7513. if (this.parent) {
  7514. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  7515. }
  7516. else {
  7517. globalPosition = this.position;
  7518. }
  7519. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  7520. this._collider.radius = this.ellipsoid;
  7521. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  7522. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  7523. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  7524. this.position.addInPlace(this._diffPosition);
  7525. if (this.onCollide) {
  7526. this.onCollide(this._collider.collidedMesh);
  7527. }
  7528. }
  7529. };
  7530. FreeCamera.prototype._checkInputs = function () {
  7531. if (!this._localDirection) {
  7532. this._localDirection = BABYLON.Vector3.Zero();
  7533. this._transformedDirection = BABYLON.Vector3.Zero();
  7534. }
  7535. for (var index = 0; index < this._keys.length; index++) {
  7536. var keyCode = this._keys[index];
  7537. var speed = this._computeLocalCameraSpeed();
  7538. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7539. this._localDirection.copyFromFloats(-speed, 0, 0);
  7540. }
  7541. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7542. this._localDirection.copyFromFloats(0, 0, speed);
  7543. }
  7544. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7545. this._localDirection.copyFromFloats(speed, 0, 0);
  7546. }
  7547. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7548. this._localDirection.copyFromFloats(0, 0, -speed);
  7549. }
  7550. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  7551. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  7552. this.cameraDirection.addInPlace(this._transformedDirection);
  7553. }
  7554. };
  7555. FreeCamera.prototype._decideIfNeedsToMove = function () {
  7556. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7557. };
  7558. FreeCamera.prototype._updatePosition = function () {
  7559. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  7560. this._collideWithWorld(this.cameraDirection);
  7561. if (this.applyGravity) {
  7562. var oldPosition = this.position;
  7563. this._collideWithWorld(this.getScene().gravity);
  7564. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  7565. }
  7566. }
  7567. else {
  7568. this.position.addInPlace(this.cameraDirection);
  7569. }
  7570. };
  7571. FreeCamera.prototype._update = function () {
  7572. this._checkInputs();
  7573. _super.prototype._update.call(this);
  7574. };
  7575. return FreeCamera;
  7576. })(BABYLON.TargetCamera);
  7577. BABYLON.FreeCamera = FreeCamera;
  7578. })(BABYLON || (BABYLON = {}));
  7579. //# sourceMappingURL=babylon.freeCamera.js.map
  7580. var BABYLON;
  7581. (function (BABYLON) {
  7582. // We're mainly based on the logic defined into the FreeCamera code
  7583. var TouchCamera = (function (_super) {
  7584. __extends(TouchCamera, _super);
  7585. function TouchCamera(name, position, scene) {
  7586. _super.call(this, name, position, scene);
  7587. this._offsetX = null;
  7588. this._offsetY = null;
  7589. this._pointerCount = 0;
  7590. this._pointerPressed = [];
  7591. this.angularSensibility = 200000.0;
  7592. this.moveSensibility = 500.0;
  7593. }
  7594. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7595. var _this = this;
  7596. var previousPosition;
  7597. if (this._attachedCanvas) {
  7598. return;
  7599. }
  7600. this._attachedCanvas = canvas;
  7601. if (this._onPointerDown === undefined) {
  7602. this._onPointerDown = function (evt) {
  7603. if (!noPreventDefault) {
  7604. evt.preventDefault();
  7605. }
  7606. _this._pointerPressed.push(evt.pointerId);
  7607. if (_this._pointerPressed.length !== 1) {
  7608. return;
  7609. }
  7610. previousPosition = {
  7611. x: evt.clientX,
  7612. y: evt.clientY
  7613. };
  7614. };
  7615. this._onPointerUp = function (evt) {
  7616. if (!noPreventDefault) {
  7617. evt.preventDefault();
  7618. }
  7619. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7620. if (index === -1) {
  7621. return;
  7622. }
  7623. _this._pointerPressed.splice(index, 1);
  7624. if (index != 0) {
  7625. return;
  7626. }
  7627. previousPosition = null;
  7628. _this._offsetX = null;
  7629. _this._offsetY = null;
  7630. };
  7631. this._onPointerMove = function (evt) {
  7632. if (!noPreventDefault) {
  7633. evt.preventDefault();
  7634. }
  7635. if (!previousPosition) {
  7636. return;
  7637. }
  7638. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7639. if (index != 0) {
  7640. return;
  7641. }
  7642. _this._offsetX = evt.clientX - previousPosition.x;
  7643. _this._offsetY = -(evt.clientY - previousPosition.y);
  7644. };
  7645. this._onLostFocus = function () {
  7646. _this._offsetX = null;
  7647. _this._offsetY = null;
  7648. };
  7649. }
  7650. canvas.addEventListener("pointerdown", this._onPointerDown);
  7651. canvas.addEventListener("pointerup", this._onPointerUp);
  7652. canvas.addEventListener("pointerout", this._onPointerUp);
  7653. canvas.addEventListener("pointermove", this._onPointerMove);
  7654. BABYLON.Tools.RegisterTopRootEvents([
  7655. { name: "blur", handler: this._onLostFocus }
  7656. ]);
  7657. };
  7658. TouchCamera.prototype.detachControl = function (canvas) {
  7659. if (this._attachedCanvas != canvas) {
  7660. return;
  7661. }
  7662. canvas.removeEventListener("pointerdown", this._onPointerDown);
  7663. canvas.removeEventListener("pointerup", this._onPointerUp);
  7664. canvas.removeEventListener("pointerout", this._onPointerUp);
  7665. canvas.removeEventListener("pointermove", this._onPointerMove);
  7666. BABYLON.Tools.UnregisterTopRootEvents([
  7667. { name: "blur", handler: this._onLostFocus }
  7668. ]);
  7669. this._attachedCanvas = null;
  7670. };
  7671. TouchCamera.prototype._checkInputs = function () {
  7672. if (!this._offsetX) {
  7673. return;
  7674. }
  7675. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  7676. if (this._pointerPressed.length > 1) {
  7677. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  7678. }
  7679. else {
  7680. var speed = this._computeLocalCameraSpeed();
  7681. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7682. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7683. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7684. }
  7685. };
  7686. return TouchCamera;
  7687. })(BABYLON.FreeCamera);
  7688. BABYLON.TouchCamera = TouchCamera;
  7689. })(BABYLON || (BABYLON = {}));
  7690. //# sourceMappingURL=babylon.touchCamera.js.map
  7691. var BABYLON;
  7692. (function (BABYLON) {
  7693. // We're mainly based on the logic defined into the FreeCamera code
  7694. var DeviceOrientationCamera = (function (_super) {
  7695. __extends(DeviceOrientationCamera, _super);
  7696. function DeviceOrientationCamera(name, position, scene) {
  7697. var _this = this;
  7698. _super.call(this, name, position, scene);
  7699. this._offsetX = null;
  7700. this._offsetY = null;
  7701. this._orientationGamma = 0;
  7702. this._orientationBeta = 0;
  7703. this._initialOrientationGamma = 0;
  7704. this._initialOrientationBeta = 0;
  7705. this.angularSensibility = 10000.0;
  7706. this.moveSensibility = 50.0;
  7707. window.addEventListener("resize", function () {
  7708. _this._initialOrientationGamma = null;
  7709. }, false);
  7710. }
  7711. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7712. var _this = this;
  7713. if (this._attachedCanvas) {
  7714. return;
  7715. }
  7716. this._attachedCanvas = canvas;
  7717. if (!this._orientationChanged) {
  7718. this._orientationChanged = function (evt) {
  7719. if (!_this._initialOrientationGamma) {
  7720. _this._initialOrientationGamma = evt.gamma;
  7721. _this._initialOrientationBeta = evt.beta;
  7722. }
  7723. _this._orientationGamma = evt.gamma;
  7724. _this._orientationBeta = evt.beta;
  7725. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  7726. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  7727. };
  7728. }
  7729. window.addEventListener("deviceorientation", this._orientationChanged);
  7730. };
  7731. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  7732. if (this._attachedCanvas != canvas) {
  7733. return;
  7734. }
  7735. window.removeEventListener("deviceorientation", this._orientationChanged);
  7736. this._attachedCanvas = null;
  7737. this._orientationGamma = 0;
  7738. this._orientationBeta = 0;
  7739. this._initialOrientationGamma = 0;
  7740. this._initialOrientationBeta = 0;
  7741. };
  7742. DeviceOrientationCamera.prototype._checkInputs = function () {
  7743. if (!this._offsetX) {
  7744. return;
  7745. }
  7746. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  7747. var speed = this._computeLocalCameraSpeed();
  7748. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7749. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7750. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7751. };
  7752. return DeviceOrientationCamera;
  7753. })(BABYLON.FreeCamera);
  7754. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  7755. })(BABYLON || (BABYLON = {}));
  7756. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  7757. var BABYLON;
  7758. (function (BABYLON) {
  7759. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7760. var ArcRotateCamera = (function (_super) {
  7761. __extends(ArcRotateCamera, _super);
  7762. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  7763. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  7764. this.alpha = alpha;
  7765. this.beta = beta;
  7766. this.radius = radius;
  7767. this.target = target;
  7768. this.inertialAlphaOffset = 0;
  7769. this.inertialBetaOffset = 0;
  7770. this.inertialRadiusOffset = 0;
  7771. this.lowerAlphaLimit = null;
  7772. this.upperAlphaLimit = null;
  7773. this.lowerBetaLimit = 0.01;
  7774. this.upperBetaLimit = Math.PI;
  7775. this.lowerRadiusLimit = null;
  7776. this.upperRadiusLimit = null;
  7777. this.angularSensibility = 1000.0;
  7778. this.wheelPrecision = 3.0;
  7779. this.pinchPrecision = 2.0;
  7780. this.keysUp = [38];
  7781. this.keysDown = [40];
  7782. this.keysLeft = [37];
  7783. this.keysRight = [39];
  7784. this.zoomOnFactor = 1;
  7785. this.targetScreenOffset = BABYLON.Vector2.Zero();
  7786. this._keys = [];
  7787. this._viewMatrix = new BABYLON.Matrix();
  7788. this.checkCollisions = false;
  7789. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  7790. this._collider = new BABYLON.Collider();
  7791. this._previousPosition = BABYLON.Vector3.Zero();
  7792. this._collisionVelocity = BABYLON.Vector3.Zero();
  7793. this._newPosition = BABYLON.Vector3.Zero();
  7794. if (!this.target) {
  7795. this.target = BABYLON.Vector3.Zero();
  7796. }
  7797. this.getViewMatrix();
  7798. }
  7799. ArcRotateCamera.prototype._getTargetPosition = function () {
  7800. return this.target.position || this.target;
  7801. };
  7802. // Cache
  7803. ArcRotateCamera.prototype._initCache = function () {
  7804. _super.prototype._initCache.call(this);
  7805. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7806. this._cache.alpha = undefined;
  7807. this._cache.beta = undefined;
  7808. this._cache.radius = undefined;
  7809. this._cache.targetScreenOffset = undefined;
  7810. };
  7811. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  7812. if (!ignoreParentClass) {
  7813. _super.prototype._updateCache.call(this);
  7814. }
  7815. this._cache.target.copyFrom(this._getTargetPosition());
  7816. this._cache.alpha = this.alpha;
  7817. this._cache.beta = this.beta;
  7818. this._cache.radius = this.radius;
  7819. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7820. };
  7821. // Synchronized
  7822. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7823. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7824. return false;
  7825. 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);
  7826. };
  7827. // Methods
  7828. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7829. var _this = this;
  7830. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  7831. var previousPinchDistance = 0;
  7832. var pointers = new BABYLON.SmartCollection();
  7833. if (this._attachedElement) {
  7834. return;
  7835. }
  7836. this._attachedElement = element;
  7837. var engine = this.getEngine();
  7838. if (this._onPointerDown === undefined) {
  7839. this._onPointerDown = function (evt) {
  7840. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  7841. cacheSoloPointer = pointers.item(evt.pointerId);
  7842. if (!noPreventDefault) {
  7843. evt.preventDefault();
  7844. }
  7845. };
  7846. this._onPointerUp = function (evt) {
  7847. cacheSoloPointer = null;
  7848. previousPinchDistance = 0;
  7849. pointers.remove(evt.pointerId);
  7850. if (!noPreventDefault) {
  7851. evt.preventDefault();
  7852. }
  7853. };
  7854. this._onPointerMove = function (evt) {
  7855. if (!noPreventDefault) {
  7856. evt.preventDefault();
  7857. }
  7858. switch (pointers.count) {
  7859. case 1:
  7860. //var offsetX = evt.clientX - pointers.item(evt.pointerId).x;
  7861. //var offsetY = evt.clientY - pointers.item(evt.pointerId).y;
  7862. var offsetX = evt.clientX - cacheSoloPointer.x;
  7863. var offsetY = evt.clientY - cacheSoloPointer.y;
  7864. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7865. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7866. //pointers.item(evt.pointerId).x = evt.clientX;
  7867. //pointers.item(evt.pointerId).y = evt.clientY;
  7868. cacheSoloPointer.x = evt.clientX;
  7869. cacheSoloPointer.y = evt.clientY;
  7870. break;
  7871. case 2:
  7872. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  7873. pointers.item(evt.pointerId).x = evt.clientX;
  7874. pointers.item(evt.pointerId).y = evt.clientY;
  7875. var direction = 1;
  7876. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  7877. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  7878. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  7879. if (previousPinchDistance === 0) {
  7880. previousPinchDistance = pinchSquaredDistance;
  7881. return;
  7882. }
  7883. if (pinchSquaredDistance !== previousPinchDistance) {
  7884. if (pinchSquaredDistance > previousPinchDistance) {
  7885. direction = -1;
  7886. }
  7887. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * _this.angularSensibility);
  7888. previousPinchDistance = pinchSquaredDistance;
  7889. }
  7890. break;
  7891. default:
  7892. if (pointers.item(evt.pointerId)) {
  7893. pointers.item(evt.pointerId).x = evt.clientX;
  7894. pointers.item(evt.pointerId).y = evt.clientY;
  7895. }
  7896. }
  7897. };
  7898. this._onMouseMove = function (evt) {
  7899. if (!engine.isPointerLock) {
  7900. return;
  7901. }
  7902. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7903. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7904. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7905. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7906. if (!noPreventDefault) {
  7907. evt.preventDefault();
  7908. }
  7909. };
  7910. this._wheel = function (event) {
  7911. var delta = 0;
  7912. if (event.wheelDelta) {
  7913. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7914. }
  7915. else if (event.detail) {
  7916. delta = -event.detail / _this.wheelPrecision;
  7917. }
  7918. if (delta)
  7919. _this.inertialRadiusOffset += delta;
  7920. if (event.preventDefault) {
  7921. if (!noPreventDefault) {
  7922. event.preventDefault();
  7923. }
  7924. }
  7925. };
  7926. this._onKeyDown = function (evt) {
  7927. 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) {
  7928. var index = _this._keys.indexOf(evt.keyCode);
  7929. if (index === -1) {
  7930. _this._keys.push(evt.keyCode);
  7931. }
  7932. if (evt.preventDefault) {
  7933. if (!noPreventDefault) {
  7934. evt.preventDefault();
  7935. }
  7936. }
  7937. }
  7938. };
  7939. this._onKeyUp = function (evt) {
  7940. 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) {
  7941. var index = _this._keys.indexOf(evt.keyCode);
  7942. if (index >= 0) {
  7943. _this._keys.splice(index, 1);
  7944. }
  7945. if (evt.preventDefault) {
  7946. if (!noPreventDefault) {
  7947. evt.preventDefault();
  7948. }
  7949. }
  7950. }
  7951. };
  7952. this._onLostFocus = function () {
  7953. _this._keys = [];
  7954. pointers.empty();
  7955. previousPinchDistance = 0;
  7956. cacheSoloPointer = null;
  7957. };
  7958. this._onGestureStart = function (e) {
  7959. if (window.MSGesture === undefined) {
  7960. return;
  7961. }
  7962. if (!_this._MSGestureHandler) {
  7963. _this._MSGestureHandler = new MSGesture();
  7964. _this._MSGestureHandler.target = element;
  7965. }
  7966. _this._MSGestureHandler.addPointer(e.pointerId);
  7967. };
  7968. this._onGesture = function (e) {
  7969. _this.radius *= e.scale;
  7970. if (e.preventDefault) {
  7971. if (!noPreventDefault) {
  7972. e.stopPropagation();
  7973. e.preventDefault();
  7974. }
  7975. }
  7976. };
  7977. this._reset = function () {
  7978. _this._keys = [];
  7979. _this.inertialAlphaOffset = 0;
  7980. _this.inertialBetaOffset = 0;
  7981. _this.inertialRadiusOffset = 0;
  7982. pointers.empty();
  7983. previousPinchDistance = 0;
  7984. cacheSoloPointer = null;
  7985. };
  7986. }
  7987. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7988. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7989. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7990. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7991. element.addEventListener("mousemove", this._onMouseMove, false);
  7992. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7993. element.addEventListener("MSGestureChange", this._onGesture, false);
  7994. element.addEventListener('mousewheel', this._wheel, false);
  7995. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7996. BABYLON.Tools.RegisterTopRootEvents([
  7997. { name: "keydown", handler: this._onKeyDown },
  7998. { name: "keyup", handler: this._onKeyUp },
  7999. { name: "blur", handler: this._onLostFocus }
  8000. ]);
  8001. };
  8002. ArcRotateCamera.prototype.detachControl = function (element) {
  8003. if (this._attachedElement !== element) {
  8004. return;
  8005. }
  8006. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  8007. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  8008. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  8009. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  8010. element.removeEventListener("mousemove", this._onMouseMove);
  8011. element.removeEventListener("MSPointerDown", this._onGestureStart);
  8012. element.removeEventListener("MSGestureChange", this._onGesture);
  8013. element.removeEventListener('mousewheel', this._wheel);
  8014. element.removeEventListener('DOMMouseScroll', this._wheel);
  8015. BABYLON.Tools.UnregisterTopRootEvents([
  8016. { name: "keydown", handler: this._onKeyDown },
  8017. { name: "keyup", handler: this._onKeyUp },
  8018. { name: "blur", handler: this._onLostFocus }
  8019. ]);
  8020. this._MSGestureHandler = null;
  8021. this._attachedElement = null;
  8022. if (this._reset) {
  8023. this._reset();
  8024. }
  8025. };
  8026. ArcRotateCamera.prototype._update = function () {
  8027. for (var index = 0; index < this._keys.length; index++) {
  8028. var keyCode = this._keys[index];
  8029. if (this.keysLeft.indexOf(keyCode) !== -1) {
  8030. this.inertialAlphaOffset -= 0.01;
  8031. }
  8032. else if (this.keysUp.indexOf(keyCode) !== -1) {
  8033. this.inertialBetaOffset -= 0.01;
  8034. }
  8035. else if (this.keysRight.indexOf(keyCode) !== -1) {
  8036. this.inertialAlphaOffset += 0.01;
  8037. }
  8038. else if (this.keysDown.indexOf(keyCode) !== -1) {
  8039. this.inertialBetaOffset += 0.01;
  8040. }
  8041. }
  8042. // Inertia
  8043. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  8044. this.alpha += this.inertialAlphaOffset;
  8045. this.beta += this.inertialBetaOffset;
  8046. this.radius -= this.inertialRadiusOffset;
  8047. this.inertialAlphaOffset *= this.inertia;
  8048. this.inertialBetaOffset *= this.inertia;
  8049. this.inertialRadiusOffset *= this.inertia;
  8050. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  8051. this.inertialAlphaOffset = 0;
  8052. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  8053. this.inertialBetaOffset = 0;
  8054. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  8055. this.inertialRadiusOffset = 0;
  8056. }
  8057. // Limits
  8058. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  8059. this.alpha = this.lowerAlphaLimit;
  8060. }
  8061. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  8062. this.alpha = this.upperAlphaLimit;
  8063. }
  8064. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  8065. this.beta = this.lowerBetaLimit;
  8066. }
  8067. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  8068. this.beta = this.upperBetaLimit;
  8069. }
  8070. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  8071. this.radius = this.lowerRadiusLimit;
  8072. }
  8073. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  8074. this.radius = this.upperRadiusLimit;
  8075. }
  8076. };
  8077. ArcRotateCamera.prototype.setPosition = function (position) {
  8078. var radiusv3 = position.subtract(this._getTargetPosition());
  8079. this.radius = radiusv3.length();
  8080. // Alpha
  8081. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  8082. if (radiusv3.z < 0) {
  8083. this.alpha = 2 * Math.PI - this.alpha;
  8084. }
  8085. // Beta
  8086. this.beta = Math.acos(radiusv3.y / this.radius);
  8087. };
  8088. ArcRotateCamera.prototype._getViewMatrix = function () {
  8089. // Compute
  8090. var cosa = Math.cos(this.alpha);
  8091. var sina = Math.sin(this.alpha);
  8092. var cosb = Math.cos(this.beta);
  8093. var sinb = Math.sin(this.beta);
  8094. var target = this._getTargetPosition();
  8095. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  8096. if (this.checkCollisions) {
  8097. this._collider.radius = this.collisionRadius;
  8098. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  8099. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  8100. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  8101. this.position.copyFrom(this._previousPosition);
  8102. this.alpha = this._previousAlpha;
  8103. this.beta = this._previousBeta;
  8104. this.radius = this._previousRadius;
  8105. if (this.onCollide) {
  8106. this.onCollide(this._collider.collidedMesh);
  8107. }
  8108. }
  8109. }
  8110. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  8111. this._previousAlpha = this.alpha;
  8112. this._previousBeta = this.beta;
  8113. this._previousRadius = this.radius;
  8114. this._previousPosition.copyFrom(this.position);
  8115. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  8116. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  8117. return this._viewMatrix;
  8118. };
  8119. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  8120. meshes = meshes || this.getScene().meshes;
  8121. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  8122. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  8123. this.radius = distance * this.zoomOnFactor;
  8124. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  8125. };
  8126. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  8127. var meshesOrMinMaxVector;
  8128. var distance;
  8129. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  8130. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  8131. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  8132. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  8133. }
  8134. else {
  8135. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  8136. distance = meshesOrMinMaxVectorAndDistance.distance;
  8137. }
  8138. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  8139. this.maxZ = distance * 2;
  8140. };
  8141. return ArcRotateCamera;
  8142. })(BABYLON.Camera);
  8143. BABYLON.ArcRotateCamera = ArcRotateCamera;
  8144. })(BABYLON || (BABYLON = {}));
  8145. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  8146. (function (BABYLON) {
  8147. /**
  8148. * Represents a scene to be rendered by the engine.
  8149. * @see http://doc.babylonjs.com/page.php?p=21911
  8150. */
  8151. var Scene = (function () {
  8152. /**
  8153. * @constructor
  8154. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  8155. */
  8156. function Scene(engine) {
  8157. // Members
  8158. this.autoClear = true;
  8159. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  8160. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  8161. this.forceWireframe = false;
  8162. this.forcePointsCloud = false;
  8163. this.forceShowBoundingBoxes = false;
  8164. this.animationsEnabled = true;
  8165. 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
  8166. // Fog
  8167. /**
  8168. * is fog enabled on this scene.
  8169. * @type {boolean}
  8170. */
  8171. this.fogEnabled = true;
  8172. this.fogMode = Scene.FOGMODE_NONE;
  8173. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  8174. this.fogDensity = 0.1;
  8175. this.fogStart = 0;
  8176. this.fogEnd = 1000.0;
  8177. // Lights
  8178. /**
  8179. * is shadow enabled on this scene.
  8180. * @type {boolean}
  8181. */
  8182. this.shadowsEnabled = true;
  8183. /**
  8184. * is light enabled on this scene.
  8185. * @type {boolean}
  8186. */
  8187. this.lightsEnabled = true;
  8188. /**
  8189. * All of the lights added to this scene.
  8190. * @see BABYLON.Light
  8191. * @type {BABYLON.Light[]}
  8192. */
  8193. this.lights = new Array();
  8194. // Cameras
  8195. /**
  8196. * All of the cameras added to this scene.
  8197. * @see BABYLON.Camera
  8198. * @type {BABYLON.Camera[]}
  8199. */
  8200. this.cameras = new Array();
  8201. this.activeCameras = new Array();
  8202. // Meshes
  8203. /**
  8204. * All of the (abstract) meshes added to this scene.
  8205. * @see BABYLON.AbstractMesh
  8206. * @type {BABYLON.AbstractMesh[]}
  8207. */
  8208. this.meshes = new Array();
  8209. // Geometries
  8210. this._geometries = new Array();
  8211. this.materials = new Array();
  8212. this.multiMaterials = new Array();
  8213. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  8214. // Textures
  8215. this.texturesEnabled = true;
  8216. this.textures = new Array();
  8217. // Particles
  8218. this.particlesEnabled = true;
  8219. this.particleSystems = new Array();
  8220. // Sprites
  8221. this.spritesEnabled = true;
  8222. this.spriteManagers = new Array();
  8223. // Layers
  8224. this.layers = new Array();
  8225. // Skeletons
  8226. this.skeletonsEnabled = true;
  8227. this.skeletons = new Array();
  8228. // Lens flares
  8229. this.lensFlaresEnabled = true;
  8230. this.lensFlareSystems = new Array();
  8231. // Collisions
  8232. this.collisionsEnabled = true;
  8233. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  8234. // Postprocesses
  8235. this.postProcessesEnabled = true;
  8236. // Customs render targets
  8237. this.renderTargetsEnabled = true;
  8238. this.dumpNextRenderTargets = false;
  8239. this.customRenderTargets = new Array();
  8240. // Imported meshes
  8241. this.importedMeshesFiles = new Array();
  8242. this._actionManagers = new Array();
  8243. this._meshesForIntersections = new BABYLON.SmartArray(256);
  8244. // Procedural textures
  8245. this.proceduralTexturesEnabled = true;
  8246. this._proceduralTextures = new Array();
  8247. this.soundTracks = new Array();
  8248. this._audioEnabled = true;
  8249. this._headphone = false;
  8250. this._totalVertices = 0;
  8251. this._activeVertices = 0;
  8252. this._activeParticles = 0;
  8253. this._lastFrameDuration = 0;
  8254. this._evaluateActiveMeshesDuration = 0;
  8255. this._renderTargetsDuration = 0;
  8256. this._particlesDuration = 0;
  8257. this._renderDuration = 0;
  8258. this._spritesDuration = 0;
  8259. this._animationRatio = 0;
  8260. this._renderId = 0;
  8261. this._executeWhenReadyTimeoutId = -1;
  8262. this._toBeDisposed = new BABYLON.SmartArray(256);
  8263. this._onReadyCallbacks = new Array();
  8264. this._pendingData = []; //ANY
  8265. this._onBeforeRenderCallbacks = new Array();
  8266. this._onAfterRenderCallbacks = new Array();
  8267. this._activeMeshes = new BABYLON.SmartArray(256);
  8268. this._processedMaterials = new BABYLON.SmartArray(256);
  8269. this._renderTargets = new BABYLON.SmartArray(256);
  8270. this._activeParticleSystems = new BABYLON.SmartArray(256);
  8271. this._activeSkeletons = new BABYLON.SmartArray(32);
  8272. this._activeBones = 0;
  8273. this._activeAnimatables = new Array();
  8274. this._transformMatrix = BABYLON.Matrix.Zero();
  8275. this._scaledPosition = BABYLON.Vector3.Zero();
  8276. this._scaledVelocity = BABYLON.Vector3.Zero();
  8277. this._uniqueIdCounter = 0;
  8278. this._engine = engine;
  8279. engine.scenes.push(this);
  8280. this._renderingManager = new BABYLON.RenderingManager(this);
  8281. this.postProcessManager = new BABYLON.PostProcessManager(this);
  8282. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  8283. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  8284. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  8285. this.attachControl();
  8286. this._debugLayer = new BABYLON.DebugLayer(this);
  8287. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  8288. //simplification queue
  8289. this.simplificationQueue = new BABYLON.SimplificationQueue();
  8290. }
  8291. Object.defineProperty(Scene, "FOGMODE_NONE", {
  8292. get: function () {
  8293. return Scene._FOGMODE_NONE;
  8294. },
  8295. enumerable: true,
  8296. configurable: true
  8297. });
  8298. Object.defineProperty(Scene, "FOGMODE_EXP", {
  8299. get: function () {
  8300. return Scene._FOGMODE_EXP;
  8301. },
  8302. enumerable: true,
  8303. configurable: true
  8304. });
  8305. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  8306. get: function () {
  8307. return Scene._FOGMODE_EXP2;
  8308. },
  8309. enumerable: true,
  8310. configurable: true
  8311. });
  8312. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  8313. get: function () {
  8314. return Scene._FOGMODE_LINEAR;
  8315. },
  8316. enumerable: true,
  8317. configurable: true
  8318. });
  8319. Object.defineProperty(Scene.prototype, "debugLayer", {
  8320. // Properties
  8321. get: function () {
  8322. return this._debugLayer;
  8323. },
  8324. enumerable: true,
  8325. configurable: true
  8326. });
  8327. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  8328. /**
  8329. * The mesh that is currently under the pointer.
  8330. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  8331. */
  8332. get: function () {
  8333. return this._meshUnderPointer;
  8334. },
  8335. enumerable: true,
  8336. configurable: true
  8337. });
  8338. Object.defineProperty(Scene.prototype, "pointerX", {
  8339. /**
  8340. * Current on-screen X position of the pointer
  8341. * @return {number} X position of the pointer
  8342. */
  8343. get: function () {
  8344. return this._pointerX;
  8345. },
  8346. enumerable: true,
  8347. configurable: true
  8348. });
  8349. Object.defineProperty(Scene.prototype, "pointerY", {
  8350. /**
  8351. * Current on-screen Y position of the pointer
  8352. * @return {number} Y position of the pointer
  8353. */
  8354. get: function () {
  8355. return this._pointerY;
  8356. },
  8357. enumerable: true,
  8358. configurable: true
  8359. });
  8360. Scene.prototype.getCachedMaterial = function () {
  8361. return this._cachedMaterial;
  8362. };
  8363. Scene.prototype.getBoundingBoxRenderer = function () {
  8364. return this._boundingBoxRenderer;
  8365. };
  8366. Scene.prototype.getOutlineRenderer = function () {
  8367. return this._outlineRenderer;
  8368. };
  8369. Scene.prototype.getEngine = function () {
  8370. return this._engine;
  8371. };
  8372. Scene.prototype.getTotalVertices = function () {
  8373. return this._totalVertices;
  8374. };
  8375. Scene.prototype.getActiveVertices = function () {
  8376. return this._activeVertices;
  8377. };
  8378. Scene.prototype.getActiveParticles = function () {
  8379. return this._activeParticles;
  8380. };
  8381. Scene.prototype.getActiveBones = function () {
  8382. return this._activeBones;
  8383. };
  8384. // Stats
  8385. Scene.prototype.getLastFrameDuration = function () {
  8386. return this._lastFrameDuration;
  8387. };
  8388. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  8389. return this._evaluateActiveMeshesDuration;
  8390. };
  8391. Scene.prototype.getActiveMeshes = function () {
  8392. return this._activeMeshes;
  8393. };
  8394. Scene.prototype.getRenderTargetsDuration = function () {
  8395. return this._renderTargetsDuration;
  8396. };
  8397. Scene.prototype.getRenderDuration = function () {
  8398. return this._renderDuration;
  8399. };
  8400. Scene.prototype.getParticlesDuration = function () {
  8401. return this._particlesDuration;
  8402. };
  8403. Scene.prototype.getSpritesDuration = function () {
  8404. return this._spritesDuration;
  8405. };
  8406. Scene.prototype.getAnimationRatio = function () {
  8407. return this._animationRatio;
  8408. };
  8409. Scene.prototype.getRenderId = function () {
  8410. return this._renderId;
  8411. };
  8412. Scene.prototype.incrementRenderId = function () {
  8413. this._renderId++;
  8414. };
  8415. Scene.prototype._updatePointerPosition = function (evt) {
  8416. var canvasRect = this._engine.getRenderingCanvasClientRect();
  8417. this._pointerX = evt.clientX - canvasRect.left;
  8418. this._pointerY = evt.clientY - canvasRect.top;
  8419. if (this.cameraToUseForPointers) {
  8420. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  8421. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  8422. }
  8423. };
  8424. // Pointers handling
  8425. Scene.prototype.attachControl = function () {
  8426. var _this = this;
  8427. this._onPointerMove = function (evt) {
  8428. var canvas = _this._engine.getRenderingCanvas();
  8429. _this._updatePointerPosition(evt);
  8430. 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);
  8431. if (pickResult.hit) {
  8432. _this._meshUnderPointer = pickResult.pickedMesh;
  8433. _this.setPointerOverMesh(pickResult.pickedMesh);
  8434. canvas.style.cursor = "pointer";
  8435. }
  8436. else {
  8437. _this.setPointerOverMesh(null);
  8438. canvas.style.cursor = "";
  8439. _this._meshUnderPointer = null;
  8440. }
  8441. };
  8442. this._onPointerDown = function (evt) {
  8443. var predicate = null;
  8444. if (!_this.onPointerDown) {
  8445. predicate = function (mesh) {
  8446. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  8447. };
  8448. }
  8449. _this._updatePointerPosition(evt);
  8450. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  8451. if (pickResult.hit) {
  8452. if (pickResult.pickedMesh.actionManager) {
  8453. switch (evt.button) {
  8454. case 0:
  8455. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8456. break;
  8457. case 1:
  8458. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8459. break;
  8460. case 2:
  8461. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8462. break;
  8463. }
  8464. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8465. }
  8466. }
  8467. if (_this.onPointerDown) {
  8468. _this.onPointerDown(evt, pickResult);
  8469. }
  8470. };
  8471. this._onKeyDown = function (evt) {
  8472. if (_this.actionManager) {
  8473. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8474. }
  8475. };
  8476. this._onKeyUp = function (evt) {
  8477. if (_this.actionManager) {
  8478. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8479. }
  8480. };
  8481. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8482. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  8483. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  8484. BABYLON.Tools.RegisterTopRootEvents([
  8485. { name: "keydown", handler: this._onKeyDown },
  8486. { name: "keyup", handler: this._onKeyUp }
  8487. ]);
  8488. };
  8489. Scene.prototype.detachControl = function () {
  8490. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8491. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  8492. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  8493. BABYLON.Tools.UnregisterTopRootEvents([
  8494. { name: "keydown", handler: this._onKeyDown },
  8495. { name: "keyup", handler: this._onKeyUp }
  8496. ]);
  8497. };
  8498. // Ready
  8499. Scene.prototype.isReady = function () {
  8500. if (this._pendingData.length > 0) {
  8501. return false;
  8502. }
  8503. for (var index = 0; index < this._geometries.length; index++) {
  8504. var geometry = this._geometries[index];
  8505. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8506. return false;
  8507. }
  8508. }
  8509. for (index = 0; index < this.meshes.length; index++) {
  8510. var mesh = this.meshes[index];
  8511. if (!mesh.isReady()) {
  8512. return false;
  8513. }
  8514. var mat = mesh.material;
  8515. if (mat) {
  8516. if (!mat.isReady(mesh)) {
  8517. return false;
  8518. }
  8519. }
  8520. }
  8521. return true;
  8522. };
  8523. Scene.prototype.resetCachedMaterial = function () {
  8524. this._cachedMaterial = null;
  8525. };
  8526. Scene.prototype.registerBeforeRender = function (func) {
  8527. this._onBeforeRenderCallbacks.push(func);
  8528. };
  8529. Scene.prototype.unregisterBeforeRender = function (func) {
  8530. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8531. if (index > -1) {
  8532. this._onBeforeRenderCallbacks.splice(index, 1);
  8533. }
  8534. };
  8535. Scene.prototype.registerAfterRender = function (func) {
  8536. this._onAfterRenderCallbacks.push(func);
  8537. };
  8538. Scene.prototype.unregisterAfterRender = function (func) {
  8539. var index = this._onAfterRenderCallbacks.indexOf(func);
  8540. if (index > -1) {
  8541. this._onAfterRenderCallbacks.splice(index, 1);
  8542. }
  8543. };
  8544. Scene.prototype._addPendingData = function (data) {
  8545. this._pendingData.push(data);
  8546. };
  8547. Scene.prototype._removePendingData = function (data) {
  8548. var index = this._pendingData.indexOf(data);
  8549. if (index !== -1) {
  8550. this._pendingData.splice(index, 1);
  8551. }
  8552. };
  8553. Scene.prototype.getWaitingItemsCount = function () {
  8554. return this._pendingData.length;
  8555. };
  8556. /**
  8557. * Registers a function to be executed when the scene is ready.
  8558. * @param {Function} func - the function to be executed.
  8559. */
  8560. Scene.prototype.executeWhenReady = function (func) {
  8561. var _this = this;
  8562. this._onReadyCallbacks.push(func);
  8563. if (this._executeWhenReadyTimeoutId !== -1) {
  8564. return;
  8565. }
  8566. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8567. _this._checkIsReady();
  8568. }, 150);
  8569. };
  8570. Scene.prototype._checkIsReady = function () {
  8571. var _this = this;
  8572. if (this.isReady()) {
  8573. this._onReadyCallbacks.forEach(function (func) {
  8574. func();
  8575. });
  8576. this._onReadyCallbacks = [];
  8577. this._executeWhenReadyTimeoutId = -1;
  8578. return;
  8579. }
  8580. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8581. _this._checkIsReady();
  8582. }, 150);
  8583. };
  8584. // Animations
  8585. /**
  8586. * Will start the animation sequence of a given target
  8587. * @param target - the target
  8588. * @param {number} from - from which frame should animation start
  8589. * @param {number} to - till which frame should animation run.
  8590. * @param {boolean} [loop] - should the animation loop
  8591. * @param {number} [speedRatio] - the speed in which to run the animation
  8592. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  8593. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  8594. * @return {BABYLON.Animatable} the animatable object created for this animation
  8595. * @see BABYLON.Animatable
  8596. * @see http://doc.babylonjs.com/page.php?p=22081
  8597. */
  8598. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  8599. if (speedRatio === undefined) {
  8600. speedRatio = 1.0;
  8601. }
  8602. this.stopAnimation(target);
  8603. if (!animatable) {
  8604. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  8605. }
  8606. // Local animations
  8607. if (target.animations) {
  8608. animatable.appendAnimations(target, target.animations);
  8609. }
  8610. // Children animations
  8611. if (target.getAnimatables) {
  8612. var animatables = target.getAnimatables();
  8613. for (var index = 0; index < animatables.length; index++) {
  8614. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  8615. }
  8616. }
  8617. return animatable;
  8618. };
  8619. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  8620. if (speedRatio === undefined) {
  8621. speedRatio = 1.0;
  8622. }
  8623. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  8624. return animatable;
  8625. };
  8626. Scene.prototype.getAnimatableByTarget = function (target) {
  8627. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8628. if (this._activeAnimatables[index].target === target) {
  8629. return this._activeAnimatables[index];
  8630. }
  8631. }
  8632. return null;
  8633. };
  8634. /**
  8635. * Will stop the animation of the given target
  8636. * @param target - the target
  8637. * @see beginAnimation
  8638. */
  8639. Scene.prototype.stopAnimation = function (target) {
  8640. var animatable = this.getAnimatableByTarget(target);
  8641. if (animatable) {
  8642. animatable.stop();
  8643. }
  8644. };
  8645. Scene.prototype._animate = function () {
  8646. if (!this.animationsEnabled) {
  8647. return;
  8648. }
  8649. if (!this._animationStartDate) {
  8650. this._animationStartDate = BABYLON.Tools.Now;
  8651. }
  8652. // Getting time
  8653. var now = BABYLON.Tools.Now;
  8654. var delay = now - this._animationStartDate;
  8655. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8656. this._activeAnimatables[index]._animate(delay);
  8657. }
  8658. };
  8659. // Matrix
  8660. Scene.prototype.getViewMatrix = function () {
  8661. return this._viewMatrix;
  8662. };
  8663. Scene.prototype.getProjectionMatrix = function () {
  8664. return this._projectionMatrix;
  8665. };
  8666. Scene.prototype.getTransformMatrix = function () {
  8667. return this._transformMatrix;
  8668. };
  8669. Scene.prototype.setTransformMatrix = function (view, projection) {
  8670. this._viewMatrix = view;
  8671. this._projectionMatrix = projection;
  8672. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8673. };
  8674. // Methods
  8675. Scene.prototype.addMesh = function (newMesh) {
  8676. newMesh.uniqueId = this._uniqueIdCounter++;
  8677. var position = this.meshes.push(newMesh);
  8678. if (this.onNewMeshAdded) {
  8679. this.onNewMeshAdded(newMesh, position, this);
  8680. }
  8681. };
  8682. Scene.prototype.removeMesh = function (toRemove) {
  8683. var index = this.meshes.indexOf(toRemove);
  8684. if (index !== -1) {
  8685. // Remove from the scene if mesh found
  8686. this.meshes.splice(index, 1);
  8687. }
  8688. if (this.onMeshRemoved) {
  8689. this.onMeshRemoved(toRemove);
  8690. }
  8691. return index;
  8692. };
  8693. Scene.prototype.removeLight = function (toRemove) {
  8694. var index = this.lights.indexOf(toRemove);
  8695. if (index !== -1) {
  8696. // Remove from the scene if mesh found
  8697. this.lights.splice(index, 1);
  8698. }
  8699. if (this.onLightRemoved) {
  8700. this.onLightRemoved(toRemove);
  8701. }
  8702. return index;
  8703. };
  8704. Scene.prototype.removeCamera = function (toRemove) {
  8705. var index = this.cameras.indexOf(toRemove);
  8706. if (index !== -1) {
  8707. // Remove from the scene if mesh found
  8708. this.cameras.splice(index, 1);
  8709. }
  8710. if (this.onCameraRemoved) {
  8711. this.onCameraRemoved(toRemove);
  8712. }
  8713. return index;
  8714. };
  8715. Scene.prototype.addLight = function (newLight) {
  8716. newLight.uniqueId = this._uniqueIdCounter++;
  8717. var position = this.lights.push(newLight);
  8718. if (this.onNewLightAdded) {
  8719. this.onNewLightAdded(newLight, position, this);
  8720. }
  8721. };
  8722. Scene.prototype.addCamera = function (newCamera) {
  8723. newCamera.uniqueId = this._uniqueIdCounter++;
  8724. var position = this.cameras.push(newCamera);
  8725. if (this.onNewCameraAdded) {
  8726. this.onNewCameraAdded(newCamera, position, this);
  8727. }
  8728. };
  8729. /**
  8730. * sets the active camera of the scene using its ID
  8731. * @param {string} id - the camera's ID
  8732. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8733. * @see activeCamera
  8734. */
  8735. Scene.prototype.setActiveCameraByID = function (id) {
  8736. var camera = this.getCameraByID(id);
  8737. if (camera) {
  8738. this.activeCamera = camera;
  8739. return camera;
  8740. }
  8741. return null;
  8742. };
  8743. /**
  8744. * sets the active camera of the scene using its name
  8745. * @param {string} name - the camera's name
  8746. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8747. * @see activeCamera
  8748. */
  8749. Scene.prototype.setActiveCameraByName = function (name) {
  8750. var camera = this.getCameraByName(name);
  8751. if (camera) {
  8752. this.activeCamera = camera;
  8753. return camera;
  8754. }
  8755. return null;
  8756. };
  8757. /**
  8758. * get a material using its id
  8759. * @param {string} the material's ID
  8760. * @return {BABYLON.Material|null} the material or null if none found.
  8761. */
  8762. Scene.prototype.getMaterialByID = function (id) {
  8763. for (var index = 0; index < this.materials.length; index++) {
  8764. if (this.materials[index].id === id) {
  8765. return this.materials[index];
  8766. }
  8767. }
  8768. return null;
  8769. };
  8770. /**
  8771. * get a material using its name
  8772. * @param {string} the material's name
  8773. * @return {BABYLON.Material|null} the material or null if none found.
  8774. */
  8775. Scene.prototype.getMaterialByName = function (name) {
  8776. for (var index = 0; index < this.materials.length; index++) {
  8777. if (this.materials[index].name === name) {
  8778. return this.materials[index];
  8779. }
  8780. }
  8781. return null;
  8782. };
  8783. Scene.prototype.getCameraByID = function (id) {
  8784. for (var index = 0; index < this.cameras.length; index++) {
  8785. if (this.cameras[index].id === id) {
  8786. return this.cameras[index];
  8787. }
  8788. }
  8789. return null;
  8790. };
  8791. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  8792. for (var index = 0; index < this.cameras.length; index++) {
  8793. if (this.cameras[index].uniqueId === uniqueId) {
  8794. return this.cameras[index];
  8795. }
  8796. }
  8797. return null;
  8798. };
  8799. /**
  8800. * get a camera using its name
  8801. * @param {string} the camera's name
  8802. * @return {BABYLON.Camera|null} the camera or null if none found.
  8803. */
  8804. Scene.prototype.getCameraByName = function (name) {
  8805. for (var index = 0; index < this.cameras.length; index++) {
  8806. if (this.cameras[index].name === name) {
  8807. return this.cameras[index];
  8808. }
  8809. }
  8810. return null;
  8811. };
  8812. /**
  8813. * get a light node using its name
  8814. * @param {string} the light's name
  8815. * @return {BABYLON.Light|null} the light or null if none found.
  8816. */
  8817. Scene.prototype.getLightByName = function (name) {
  8818. for (var index = 0; index < this.lights.length; index++) {
  8819. if (this.lights[index].name === name) {
  8820. return this.lights[index];
  8821. }
  8822. }
  8823. return null;
  8824. };
  8825. /**
  8826. * get a light node using its ID
  8827. * @param {string} the light's id
  8828. * @return {BABYLON.Light|null} the light or null if none found.
  8829. */
  8830. Scene.prototype.getLightByID = function (id) {
  8831. for (var index = 0; index < this.lights.length; index++) {
  8832. if (this.lights[index].id === id) {
  8833. return this.lights[index];
  8834. }
  8835. }
  8836. return null;
  8837. };
  8838. /**
  8839. * get a light node using its scene-generated unique ID
  8840. * @param {number} the light's unique id
  8841. * @return {BABYLON.Light|null} the light or null if none found.
  8842. */
  8843. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  8844. for (var index = 0; index < this.lights.length; index++) {
  8845. if (this.lights[index].uniqueId === uniqueId) {
  8846. return this.lights[index];
  8847. }
  8848. }
  8849. return null;
  8850. };
  8851. /**
  8852. * get a geometry using its ID
  8853. * @param {string} the geometry's id
  8854. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  8855. */
  8856. Scene.prototype.getGeometryByID = function (id) {
  8857. for (var index = 0; index < this._geometries.length; index++) {
  8858. if (this._geometries[index].id === id) {
  8859. return this._geometries[index];
  8860. }
  8861. }
  8862. return null;
  8863. };
  8864. /**
  8865. * add a new geometry to this scene.
  8866. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  8867. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  8868. * @return {boolean} was the geometry added or not
  8869. */
  8870. Scene.prototype.pushGeometry = function (geometry, force) {
  8871. if (!force && this.getGeometryByID(geometry.id)) {
  8872. return false;
  8873. }
  8874. this._geometries.push(geometry);
  8875. if (this.onGeometryAdded) {
  8876. this.onGeometryAdded(geometry);
  8877. }
  8878. return true;
  8879. };
  8880. /**
  8881. * Removes an existing geometry
  8882. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  8883. * @return {boolean} was the geometry removed or not
  8884. */
  8885. Scene.prototype.removeGeometry = function (geometry) {
  8886. var index = this._geometries.indexOf(geometry);
  8887. if (index > -1) {
  8888. this._geometries.splice(index, 1);
  8889. if (this.onGeometryRemoved) {
  8890. this.onGeometryRemoved(geometry);
  8891. }
  8892. return true;
  8893. }
  8894. return false;
  8895. };
  8896. Scene.prototype.getGeometries = function () {
  8897. return this._geometries;
  8898. };
  8899. /**
  8900. * Get the first added mesh found of a given ID
  8901. * @param {string} id - the id to search for
  8902. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8903. */
  8904. Scene.prototype.getMeshByID = function (id) {
  8905. for (var index = 0; index < this.meshes.length; index++) {
  8906. if (this.meshes[index].id === id) {
  8907. return this.meshes[index];
  8908. }
  8909. }
  8910. return null;
  8911. };
  8912. /**
  8913. * Get a mesh with its auto-generated unique id
  8914. * @param {number} uniqueId - the unique id to search for
  8915. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8916. */
  8917. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  8918. for (var index = 0; index < this.meshes.length; index++) {
  8919. if (this.meshes[index].uniqueId === uniqueId) {
  8920. return this.meshes[index];
  8921. }
  8922. }
  8923. return null;
  8924. };
  8925. /**
  8926. * Get a the last added mesh found of a given ID
  8927. * @param {string} id - the id to search for
  8928. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8929. */
  8930. Scene.prototype.getLastMeshByID = function (id) {
  8931. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8932. if (this.meshes[index].id === id) {
  8933. return this.meshes[index];
  8934. }
  8935. }
  8936. return null;
  8937. };
  8938. /**
  8939. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  8940. * @param {string} id - the id to search for
  8941. * @return {BABYLON.Node|null} the node found or null if not found at all.
  8942. */
  8943. Scene.prototype.getLastEntryByID = function (id) {
  8944. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8945. if (this.meshes[index].id === id) {
  8946. return this.meshes[index];
  8947. }
  8948. }
  8949. for (index = this.cameras.length - 1; index >= 0; index--) {
  8950. if (this.cameras[index].id === id) {
  8951. return this.cameras[index];
  8952. }
  8953. }
  8954. for (index = this.lights.length - 1; index >= 0; index--) {
  8955. if (this.lights[index].id === id) {
  8956. return this.lights[index];
  8957. }
  8958. }
  8959. return null;
  8960. };
  8961. Scene.prototype.getNodeByName = function (name) {
  8962. var mesh = this.getMeshByName(name);
  8963. if (mesh) {
  8964. return mesh;
  8965. }
  8966. var light = this.getLightByName(name);
  8967. if (light) {
  8968. return light;
  8969. }
  8970. return this.getCameraByName(name);
  8971. };
  8972. Scene.prototype.getMeshByName = function (name) {
  8973. for (var index = 0; index < this.meshes.length; index++) {
  8974. if (this.meshes[index].name === name) {
  8975. return this.meshes[index];
  8976. }
  8977. }
  8978. return null;
  8979. };
  8980. Scene.prototype.getSoundByName = function (name) {
  8981. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  8982. if (this.mainSoundTrack.soundCollection[index].name === name) {
  8983. return this.mainSoundTrack.soundCollection[index];
  8984. }
  8985. }
  8986. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  8987. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  8988. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  8989. return this.soundTracks[sdIndex].soundCollection[index];
  8990. }
  8991. }
  8992. }
  8993. return null;
  8994. };
  8995. Scene.prototype.getLastSkeletonByID = function (id) {
  8996. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  8997. if (this.skeletons[index].id === id) {
  8998. return this.skeletons[index];
  8999. }
  9000. }
  9001. return null;
  9002. };
  9003. Scene.prototype.getSkeletonById = function (id) {
  9004. for (var index = 0; index < this.skeletons.length; index++) {
  9005. if (this.skeletons[index].id === id) {
  9006. return this.skeletons[index];
  9007. }
  9008. }
  9009. return null;
  9010. };
  9011. Scene.prototype.getSkeletonByName = function (name) {
  9012. for (var index = 0; index < this.skeletons.length; index++) {
  9013. if (this.skeletons[index].name === name) {
  9014. return this.skeletons[index];
  9015. }
  9016. }
  9017. return null;
  9018. };
  9019. Scene.prototype.isActiveMesh = function (mesh) {
  9020. return (this._activeMeshes.indexOf(mesh) !== -1);
  9021. };
  9022. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  9023. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  9024. var material = subMesh.getMaterial();
  9025. if (mesh.showSubMeshesBoundingBox) {
  9026. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  9027. }
  9028. if (material) {
  9029. // Render targets
  9030. if (material.getRenderTargetTextures) {
  9031. if (this._processedMaterials.indexOf(material) === -1) {
  9032. this._processedMaterials.push(material);
  9033. this._renderTargets.concat(material.getRenderTargetTextures());
  9034. }
  9035. }
  9036. // Dispatch
  9037. this._activeVertices += subMesh.indexCount;
  9038. this._renderingManager.dispatch(subMesh);
  9039. }
  9040. }
  9041. };
  9042. Scene.prototype._evaluateActiveMeshes = function () {
  9043. this.activeCamera._activeMeshes.reset();
  9044. this._activeMeshes.reset();
  9045. this._renderingManager.reset();
  9046. this._processedMaterials.reset();
  9047. this._activeParticleSystems.reset();
  9048. this._activeSkeletons.reset();
  9049. this._boundingBoxRenderer.reset();
  9050. if (!this._frustumPlanes) {
  9051. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  9052. }
  9053. else {
  9054. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  9055. }
  9056. // Meshes
  9057. var meshes;
  9058. var len;
  9059. if (this._selectionOctree) {
  9060. var selection = this._selectionOctree.select(this._frustumPlanes);
  9061. meshes = selection.data;
  9062. len = selection.length;
  9063. }
  9064. else {
  9065. len = this.meshes.length;
  9066. meshes = this.meshes;
  9067. }
  9068. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  9069. var mesh = meshes[meshIndex];
  9070. if (mesh.isBlocked) {
  9071. continue;
  9072. }
  9073. this._totalVertices += mesh.getTotalVertices();
  9074. if (!mesh.isReady()) {
  9075. continue;
  9076. }
  9077. mesh.computeWorldMatrix();
  9078. // Intersections
  9079. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  9080. this._meshesForIntersections.pushNoDuplicate(mesh);
  9081. }
  9082. // Switch to current LOD
  9083. var meshLOD = mesh.getLOD(this.activeCamera);
  9084. if (!meshLOD) {
  9085. continue;
  9086. }
  9087. mesh._preActivate();
  9088. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  9089. this._activeMeshes.push(mesh);
  9090. this.activeCamera._activeMeshes.push(mesh);
  9091. mesh._activate(this._renderId);
  9092. this._activeMesh(meshLOD);
  9093. }
  9094. }
  9095. // Particle systems
  9096. var beforeParticlesDate = BABYLON.Tools.Now;
  9097. if (this.particlesEnabled) {
  9098. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  9099. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  9100. var particleSystem = this.particleSystems[particleIndex];
  9101. if (!particleSystem.isStarted()) {
  9102. continue;
  9103. }
  9104. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  9105. this._activeParticleSystems.push(particleSystem);
  9106. particleSystem.animate();
  9107. }
  9108. }
  9109. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  9110. }
  9111. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  9112. };
  9113. Scene.prototype._activeMesh = function (mesh) {
  9114. if (mesh.skeleton && this.skeletonsEnabled) {
  9115. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  9116. }
  9117. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  9118. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  9119. }
  9120. if (mesh && mesh.subMeshes) {
  9121. // Submeshes Octrees
  9122. var len;
  9123. var subMeshes;
  9124. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  9125. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  9126. len = intersections.length;
  9127. subMeshes = intersections.data;
  9128. }
  9129. else {
  9130. subMeshes = mesh.subMeshes;
  9131. len = subMeshes.length;
  9132. }
  9133. for (var subIndex = 0; subIndex < len; subIndex++) {
  9134. var subMesh = subMeshes[subIndex];
  9135. this._evaluateSubMesh(subMesh, mesh);
  9136. }
  9137. }
  9138. };
  9139. Scene.prototype.updateTransformMatrix = function (force) {
  9140. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  9141. };
  9142. Scene.prototype._renderForCamera = function (camera) {
  9143. var engine = this._engine;
  9144. this.activeCamera = camera;
  9145. if (!this.activeCamera)
  9146. throw new Error("Active camera not set");
  9147. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  9148. // Viewport
  9149. engine.setViewport(this.activeCamera.viewport);
  9150. // Camera
  9151. this._renderId++;
  9152. this.updateTransformMatrix();
  9153. if (this.beforeCameraRender) {
  9154. this.beforeCameraRender(this.activeCamera);
  9155. }
  9156. // Meshes
  9157. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  9158. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  9159. this._evaluateActiveMeshes();
  9160. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  9161. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  9162. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  9163. var skeleton = this._activeSkeletons.data[skeletonIndex];
  9164. skeleton.prepare();
  9165. }
  9166. // Render targets
  9167. var beforeRenderTargetDate = BABYLON.Tools.Now;
  9168. if (this.renderTargetsEnabled) {
  9169. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  9170. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  9171. var renderTarget = this._renderTargets.data[renderIndex];
  9172. if (renderTarget._shouldRender()) {
  9173. this._renderId++;
  9174. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  9175. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  9176. }
  9177. }
  9178. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  9179. this._renderId++;
  9180. }
  9181. if (this._renderTargets.length > 0) {
  9182. engine.restoreDefaultFramebuffer();
  9183. }
  9184. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  9185. // Prepare Frame
  9186. this.postProcessManager._prepareFrame();
  9187. var beforeRenderDate = BABYLON.Tools.Now;
  9188. // Backgrounds
  9189. if (this.layers.length) {
  9190. engine.setDepthBuffer(false);
  9191. var layerIndex;
  9192. var layer;
  9193. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  9194. layer = this.layers[layerIndex];
  9195. if (layer.isBackground) {
  9196. layer.render();
  9197. }
  9198. }
  9199. engine.setDepthBuffer(true);
  9200. }
  9201. // Render
  9202. BABYLON.Tools.StartPerformanceCounter("Main render");
  9203. this._renderingManager.render(null, null, true, true);
  9204. BABYLON.Tools.EndPerformanceCounter("Main render");
  9205. // Bounding boxes
  9206. this._boundingBoxRenderer.render();
  9207. // Lens flares
  9208. if (this.lensFlaresEnabled) {
  9209. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  9210. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  9211. this.lensFlareSystems[lensFlareSystemIndex].render();
  9212. }
  9213. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  9214. }
  9215. // Foregrounds
  9216. if (this.layers.length) {
  9217. engine.setDepthBuffer(false);
  9218. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  9219. layer = this.layers[layerIndex];
  9220. if (!layer.isBackground) {
  9221. layer.render();
  9222. }
  9223. }
  9224. engine.setDepthBuffer(true);
  9225. }
  9226. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  9227. // Finalize frame
  9228. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  9229. // Update camera
  9230. this.activeCamera._updateFromScene();
  9231. // Reset some special arrays
  9232. this._renderTargets.reset();
  9233. if (this.afterCameraRender) {
  9234. this.afterCameraRender(this.activeCamera);
  9235. }
  9236. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  9237. };
  9238. Scene.prototype._processSubCameras = function (camera) {
  9239. if (camera.subCameras.length === 0) {
  9240. this._renderForCamera(camera);
  9241. return;
  9242. }
  9243. for (var index = 0; index < camera.subCameras.length; index++) {
  9244. this._renderForCamera(camera.subCameras[index]);
  9245. }
  9246. this.activeCamera = camera;
  9247. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  9248. // Update camera
  9249. this.activeCamera._updateFromScene();
  9250. };
  9251. Scene.prototype._checkIntersections = function () {
  9252. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  9253. var sourceMesh = this._meshesForIntersections.data[index];
  9254. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  9255. var action = sourceMesh.actionManager.actions[actionIndex];
  9256. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9257. var parameters = action.getTriggerParameter();
  9258. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  9259. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  9260. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  9261. if (areIntersecting && currentIntersectionInProgress === -1) {
  9262. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  9263. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  9264. sourceMesh._intersectionsInProgress.push(otherMesh);
  9265. }
  9266. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9267. sourceMesh._intersectionsInProgress.push(otherMesh);
  9268. }
  9269. }
  9270. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9271. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  9272. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  9273. if (indexOfOther > -1) {
  9274. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  9275. }
  9276. }
  9277. }
  9278. }
  9279. }
  9280. };
  9281. Scene.prototype.render = function () {
  9282. var startDate = BABYLON.Tools.Now;
  9283. this._particlesDuration = 0;
  9284. this._spritesDuration = 0;
  9285. this._activeParticles = 0;
  9286. this._renderDuration = 0;
  9287. this._renderTargetsDuration = 0;
  9288. this._evaluateActiveMeshesDuration = 0;
  9289. this._totalVertices = 0;
  9290. this._activeVertices = 0;
  9291. this._activeBones = 0;
  9292. this.getEngine().resetDrawCalls();
  9293. this._meshesForIntersections.reset();
  9294. this.resetCachedMaterial();
  9295. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  9296. // Actions
  9297. if (this.actionManager) {
  9298. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  9299. }
  9300. //Simplification Queue
  9301. if (!this.simplificationQueue.running) {
  9302. this.simplificationQueue.executeNext();
  9303. }
  9304. // Before render
  9305. if (this.beforeRender) {
  9306. this.beforeRender();
  9307. }
  9308. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  9309. this._onBeforeRenderCallbacks[callbackIndex]();
  9310. }
  9311. // Animations
  9312. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  9313. this._animationRatio = deltaTime * (60.0 / 1000.0);
  9314. this._animate();
  9315. // Physics
  9316. if (this._physicsEngine) {
  9317. BABYLON.Tools.StartPerformanceCounter("Physics");
  9318. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  9319. BABYLON.Tools.EndPerformanceCounter("Physics");
  9320. }
  9321. // Customs render targets
  9322. var beforeRenderTargetDate = BABYLON.Tools.Now;
  9323. var engine = this.getEngine();
  9324. var currentActiveCamera = this.activeCamera;
  9325. if (this.renderTargetsEnabled) {
  9326. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  9327. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  9328. var renderTarget = this.customRenderTargets[customIndex];
  9329. if (renderTarget._shouldRender()) {
  9330. this._renderId++;
  9331. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  9332. if (!this.activeCamera)
  9333. throw new Error("Active camera not set");
  9334. // Viewport
  9335. engine.setViewport(this.activeCamera.viewport);
  9336. // Camera
  9337. this.updateTransformMatrix();
  9338. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  9339. }
  9340. }
  9341. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  9342. this._renderId++;
  9343. }
  9344. if (this.customRenderTargets.length > 0) {
  9345. engine.restoreDefaultFramebuffer();
  9346. }
  9347. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  9348. this.activeCamera = currentActiveCamera;
  9349. // Procedural textures
  9350. if (this.proceduralTexturesEnabled) {
  9351. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  9352. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  9353. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  9354. if (proceduralTexture._shouldRender()) {
  9355. proceduralTexture.render();
  9356. }
  9357. }
  9358. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  9359. }
  9360. // Clear
  9361. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  9362. // Shadows
  9363. if (this.shadowsEnabled) {
  9364. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  9365. var light = this.lights[lightIndex];
  9366. var shadowGenerator = light.getShadowGenerator();
  9367. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  9368. this._renderTargets.push(shadowGenerator.getShadowMap());
  9369. }
  9370. }
  9371. }
  9372. // Depth renderer
  9373. if (this._depthRenderer) {
  9374. this._renderTargets.push(this._depthRenderer.getDepthMap());
  9375. }
  9376. // RenderPipeline
  9377. this.postProcessRenderPipelineManager.update();
  9378. // Multi-cameras?
  9379. if (this.activeCameras.length > 0) {
  9380. var currentRenderId = this._renderId;
  9381. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  9382. this._renderId = currentRenderId;
  9383. this._processSubCameras(this.activeCameras[cameraIndex]);
  9384. }
  9385. }
  9386. else {
  9387. if (!this.activeCamera) {
  9388. throw new Error("No camera defined");
  9389. }
  9390. this._processSubCameras(this.activeCamera);
  9391. }
  9392. // Intersection checks
  9393. this._checkIntersections();
  9394. // Update the audio listener attached to the camera
  9395. this._updateAudioParameters();
  9396. // After render
  9397. if (this.afterRender) {
  9398. this.afterRender();
  9399. }
  9400. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  9401. this._onAfterRenderCallbacks[callbackIndex]();
  9402. }
  9403. for (var index = 0; index < this._toBeDisposed.length; index++) {
  9404. this._toBeDisposed.data[index].dispose();
  9405. this._toBeDisposed[index] = null;
  9406. }
  9407. this._toBeDisposed.reset();
  9408. if (this.dumpNextRenderTargets) {
  9409. this.dumpNextRenderTargets = false;
  9410. }
  9411. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  9412. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  9413. };
  9414. Scene.prototype._updateAudioParameters = function () {
  9415. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  9416. return;
  9417. }
  9418. var listeningCamera;
  9419. var audioEngine = BABYLON.Engine.audioEngine;
  9420. if (this.activeCameras.length > 0) {
  9421. listeningCamera = this.activeCameras[0];
  9422. }
  9423. else {
  9424. listeningCamera = this.activeCamera;
  9425. }
  9426. if (listeningCamera && audioEngine.canUseWebAudio) {
  9427. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  9428. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  9429. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  9430. cameraDirection.normalize();
  9431. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  9432. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9433. var sound = this.mainSoundTrack.soundCollection[i];
  9434. if (sound.useCustomAttenuation) {
  9435. sound.updateDistanceFromListener();
  9436. }
  9437. }
  9438. for (i = 0; i < this.soundTracks.length; i++) {
  9439. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9440. sound = this.soundTracks[i].soundCollection[j];
  9441. if (sound.useCustomAttenuation) {
  9442. sound.updateDistanceFromListener();
  9443. }
  9444. }
  9445. }
  9446. }
  9447. };
  9448. Object.defineProperty(Scene.prototype, "audioEnabled", {
  9449. // Audio
  9450. get: function () {
  9451. return this._audioEnabled;
  9452. },
  9453. set: function (value) {
  9454. this._audioEnabled = value;
  9455. if (this._audioEnabled) {
  9456. this._enableAudio();
  9457. }
  9458. else {
  9459. this._disableAudio();
  9460. }
  9461. },
  9462. enumerable: true,
  9463. configurable: true
  9464. });
  9465. Scene.prototype._disableAudio = function () {
  9466. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9467. this.mainSoundTrack.soundCollection[i].pause();
  9468. }
  9469. for (i = 0; i < this.soundTracks.length; i++) {
  9470. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9471. this.soundTracks[i].soundCollection[j].pause();
  9472. }
  9473. }
  9474. };
  9475. Scene.prototype._enableAudio = function () {
  9476. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9477. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  9478. this.mainSoundTrack.soundCollection[i].play();
  9479. }
  9480. }
  9481. for (i = 0; i < this.soundTracks.length; i++) {
  9482. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9483. if (this.soundTracks[i].soundCollection[j].isPaused) {
  9484. this.soundTracks[i].soundCollection[j].play();
  9485. }
  9486. }
  9487. }
  9488. };
  9489. Object.defineProperty(Scene.prototype, "headphone", {
  9490. get: function () {
  9491. return this._headphone;
  9492. },
  9493. set: function (value) {
  9494. this._headphone = value;
  9495. if (this._headphone) {
  9496. this._switchAudioModeForHeadphones();
  9497. }
  9498. else {
  9499. this._switchAudioModeForNormalSpeakers();
  9500. }
  9501. },
  9502. enumerable: true,
  9503. configurable: true
  9504. });
  9505. Scene.prototype._switchAudioModeForHeadphones = function () {
  9506. this.mainSoundTrack.switchPanningModelToHRTF();
  9507. for (var i = 0; i < this.soundTracks.length; i++) {
  9508. this.soundTracks[i].switchPanningModelToHRTF();
  9509. }
  9510. };
  9511. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  9512. this.mainSoundTrack.switchPanningModelToEqualPower();
  9513. for (var i = 0; i < this.soundTracks.length; i++) {
  9514. this.soundTracks[i].switchPanningModelToEqualPower();
  9515. }
  9516. };
  9517. Scene.prototype.enableDepthRenderer = function () {
  9518. if (this._depthRenderer) {
  9519. return this._depthRenderer;
  9520. }
  9521. this._depthRenderer = new BABYLON.DepthRenderer(this);
  9522. return this._depthRenderer;
  9523. };
  9524. Scene.prototype.disableDepthRenderer = function () {
  9525. if (!this._depthRenderer) {
  9526. return;
  9527. }
  9528. this._depthRenderer.dispose();
  9529. this._depthRenderer = null;
  9530. };
  9531. Scene.prototype.dispose = function () {
  9532. this.beforeRender = null;
  9533. this.afterRender = null;
  9534. this.skeletons = [];
  9535. this._boundingBoxRenderer.dispose();
  9536. if (this._depthRenderer) {
  9537. this._depthRenderer.dispose();
  9538. }
  9539. // Debug layer
  9540. this.debugLayer.hide();
  9541. // Events
  9542. if (this.onDispose) {
  9543. this.onDispose();
  9544. }
  9545. this._onBeforeRenderCallbacks = [];
  9546. this._onAfterRenderCallbacks = [];
  9547. this.detachControl();
  9548. // Release sounds & sounds tracks
  9549. this.disposeSounds();
  9550. // Detach cameras
  9551. var canvas = this._engine.getRenderingCanvas();
  9552. var index;
  9553. for (index = 0; index < this.cameras.length; index++) {
  9554. this.cameras[index].detachControl(canvas);
  9555. }
  9556. while (this.lights.length) {
  9557. this.lights[0].dispose();
  9558. }
  9559. while (this.meshes.length) {
  9560. this.meshes[0].dispose(true);
  9561. }
  9562. while (this.cameras.length) {
  9563. this.cameras[0].dispose();
  9564. }
  9565. while (this.materials.length) {
  9566. this.materials[0].dispose();
  9567. }
  9568. while (this.particleSystems.length) {
  9569. this.particleSystems[0].dispose();
  9570. }
  9571. while (this.spriteManagers.length) {
  9572. this.spriteManagers[0].dispose();
  9573. }
  9574. while (this.layers.length) {
  9575. this.layers[0].dispose();
  9576. }
  9577. while (this.textures.length) {
  9578. this.textures[0].dispose();
  9579. }
  9580. // Post-processes
  9581. this.postProcessManager.dispose();
  9582. // Physics
  9583. if (this._physicsEngine) {
  9584. this.disablePhysicsEngine();
  9585. }
  9586. // Remove from engine
  9587. index = this._engine.scenes.indexOf(this);
  9588. if (index > -1) {
  9589. this._engine.scenes.splice(index, 1);
  9590. }
  9591. this._engine.wipeCaches();
  9592. };
  9593. // Release sounds & sounds tracks
  9594. Scene.prototype.disposeSounds = function () {
  9595. this.mainSoundTrack.dispose();
  9596. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  9597. this.soundTracks[scIndex].dispose();
  9598. }
  9599. };
  9600. // Collisions
  9601. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9602. if (excludedMesh === void 0) { excludedMesh = null; }
  9603. position.divideToRef(collider.radius, this._scaledPosition);
  9604. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9605. collider.retry = 0;
  9606. collider.initialVelocity = this._scaledVelocity;
  9607. collider.initialPosition = this._scaledPosition;
  9608. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  9609. finalPosition.multiplyInPlace(collider.radius);
  9610. };
  9611. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9612. if (excludedMesh === void 0) { excludedMesh = null; }
  9613. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9614. if (collider.retry >= maximumRetry) {
  9615. finalPosition.copyFrom(position);
  9616. return;
  9617. }
  9618. collider._initialize(position, velocity, closeDistance);
  9619. for (var index = 0; index < this.meshes.length; index++) {
  9620. var mesh = this.meshes[index];
  9621. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9622. mesh._checkCollision(collider);
  9623. }
  9624. }
  9625. if (!collider.collisionFound) {
  9626. position.addToRef(velocity, finalPosition);
  9627. return;
  9628. }
  9629. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9630. collider._getResponse(position, velocity);
  9631. }
  9632. if (velocity.length() <= closeDistance) {
  9633. finalPosition.copyFrom(position);
  9634. return;
  9635. }
  9636. collider.retry++;
  9637. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9638. };
  9639. // Octrees
  9640. Scene.prototype.getWorldExtends = function () {
  9641. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9642. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9643. for (var index = 0; index < this.meshes.length; index++) {
  9644. var mesh = this.meshes[index];
  9645. mesh.computeWorldMatrix(true);
  9646. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  9647. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  9648. BABYLON.Tools.CheckExtends(minBox, min, max);
  9649. BABYLON.Tools.CheckExtends(maxBox, min, max);
  9650. }
  9651. return {
  9652. min: min,
  9653. max: max
  9654. };
  9655. };
  9656. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  9657. if (maxCapacity === void 0) { maxCapacity = 64; }
  9658. if (maxDepth === void 0) { maxDepth = 2; }
  9659. if (!this._selectionOctree) {
  9660. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  9661. }
  9662. var worldExtends = this.getWorldExtends();
  9663. // Update octree
  9664. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  9665. return this._selectionOctree;
  9666. };
  9667. // Picking
  9668. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  9669. var engine = this._engine;
  9670. if (!camera) {
  9671. if (!this.activeCamera)
  9672. throw new Error("Active camera not set");
  9673. camera = this.activeCamera;
  9674. }
  9675. var cameraViewport = camera.viewport;
  9676. var viewport = cameraViewport.toGlobal(engine);
  9677. // Moving coordinates to local viewport world
  9678. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  9679. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  9680. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9681. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9682. };
  9683. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  9684. var pickingInfo = null;
  9685. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  9686. var mesh = this.meshes[meshIndex];
  9687. if (predicate) {
  9688. if (!predicate(mesh)) {
  9689. continue;
  9690. }
  9691. }
  9692. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  9693. continue;
  9694. }
  9695. var world = mesh.getWorldMatrix();
  9696. var ray = rayFunction(world);
  9697. var result = mesh.intersects(ray, fastCheck);
  9698. if (!result || !result.hit)
  9699. continue;
  9700. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  9701. continue;
  9702. pickingInfo = result;
  9703. if (fastCheck) {
  9704. break;
  9705. }
  9706. }
  9707. return pickingInfo || new BABYLON.PickingInfo();
  9708. };
  9709. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  9710. var _this = this;
  9711. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  9712. /// <param name="x">X position on screen</param>
  9713. /// <param name="y">Y position on screen</param>
  9714. /// <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>
  9715. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  9716. /// <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>
  9717. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  9718. };
  9719. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  9720. var _this = this;
  9721. return this._internalPick(function (world) {
  9722. if (!_this._pickWithRayInverseMatrix) {
  9723. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  9724. }
  9725. world.invertToRef(_this._pickWithRayInverseMatrix);
  9726. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  9727. }, predicate, fastCheck);
  9728. };
  9729. Scene.prototype.setPointerOverMesh = function (mesh) {
  9730. if (this._pointerOverMesh === mesh) {
  9731. return;
  9732. }
  9733. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9734. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9735. }
  9736. this._pointerOverMesh = mesh;
  9737. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9738. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9739. }
  9740. };
  9741. Scene.prototype.getPointerOverMesh = function () {
  9742. return this._pointerOverMesh;
  9743. };
  9744. // Physics
  9745. Scene.prototype.getPhysicsEngine = function () {
  9746. return this._physicsEngine;
  9747. };
  9748. Scene.prototype.enablePhysics = function (gravity, plugin) {
  9749. if (this._physicsEngine) {
  9750. return true;
  9751. }
  9752. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  9753. if (!this._physicsEngine.isSupported()) {
  9754. this._physicsEngine = null;
  9755. return false;
  9756. }
  9757. this._physicsEngine._initialize(gravity);
  9758. return true;
  9759. };
  9760. Scene.prototype.disablePhysicsEngine = function () {
  9761. if (!this._physicsEngine) {
  9762. return;
  9763. }
  9764. this._physicsEngine.dispose();
  9765. this._physicsEngine = undefined;
  9766. };
  9767. Scene.prototype.isPhysicsEnabled = function () {
  9768. return this._physicsEngine !== undefined;
  9769. };
  9770. Scene.prototype.setGravity = function (gravity) {
  9771. if (!this._physicsEngine) {
  9772. return;
  9773. }
  9774. this._physicsEngine._setGravity(gravity);
  9775. };
  9776. Scene.prototype.createCompoundImpostor = function (parts, options) {
  9777. if (parts.parts) {
  9778. options = parts;
  9779. parts = parts.parts;
  9780. }
  9781. if (!this._physicsEngine) {
  9782. return null;
  9783. }
  9784. for (var index = 0; index < parts.length; index++) {
  9785. var mesh = parts[index].mesh;
  9786. mesh._physicImpostor = parts[index].impostor;
  9787. mesh._physicsMass = options.mass / parts.length;
  9788. mesh._physicsFriction = options.friction;
  9789. mesh._physicRestitution = options.restitution;
  9790. }
  9791. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  9792. };
  9793. Scene.prototype.deleteCompoundImpostor = function (compound) {
  9794. for (var index = 0; index < compound.parts.length; index++) {
  9795. var mesh = compound.parts[index].mesh;
  9796. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9797. this._physicsEngine._unregisterMesh(mesh);
  9798. }
  9799. };
  9800. // Misc.
  9801. Scene.prototype.createDefaultCameraOrLight = function () {
  9802. // Light
  9803. if (this.lights.length === 0) {
  9804. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  9805. }
  9806. // Camera
  9807. if (!this.activeCamera) {
  9808. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  9809. // Compute position
  9810. var worldExtends = this.getWorldExtends();
  9811. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  9812. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  9813. camera.setTarget(worldCenter);
  9814. this.activeCamera = camera;
  9815. }
  9816. };
  9817. // Tags
  9818. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  9819. if (tagsQuery === undefined) {
  9820. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  9821. return list;
  9822. }
  9823. var listByTags = [];
  9824. forEach = forEach || (function (item) {
  9825. return;
  9826. });
  9827. for (var i in list) {
  9828. var item = list[i];
  9829. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  9830. listByTags.push(item);
  9831. forEach(item);
  9832. }
  9833. }
  9834. return listByTags;
  9835. };
  9836. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  9837. return this._getByTags(this.meshes, tagsQuery, forEach);
  9838. };
  9839. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  9840. return this._getByTags(this.cameras, tagsQuery, forEach);
  9841. };
  9842. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  9843. return this._getByTags(this.lights, tagsQuery, forEach);
  9844. };
  9845. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  9846. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  9847. };
  9848. // Statics
  9849. Scene._FOGMODE_NONE = 0;
  9850. Scene._FOGMODE_EXP = 1;
  9851. Scene._FOGMODE_EXP2 = 2;
  9852. Scene._FOGMODE_LINEAR = 3;
  9853. Scene.MinDeltaTime = 1.0;
  9854. Scene.MaxDeltaTime = 1000.0;
  9855. return Scene;
  9856. })();
  9857. BABYLON.Scene = Scene;
  9858. })(BABYLON || (BABYLON = {}));
  9859. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  9860. (function (BABYLON) {
  9861. var VertexBuffer = (function () {
  9862. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  9863. if (engine instanceof BABYLON.Mesh) {
  9864. this._engine = engine.getScene().getEngine();
  9865. }
  9866. else {
  9867. this._engine = engine;
  9868. }
  9869. this._updatable = updatable;
  9870. this._data = data;
  9871. if (!postponeInternalCreation) {
  9872. this.create();
  9873. }
  9874. this._kind = kind;
  9875. if (stride) {
  9876. this._strideSize = stride;
  9877. return;
  9878. }
  9879. switch (kind) {
  9880. case VertexBuffer.PositionKind:
  9881. this._strideSize = 3;
  9882. break;
  9883. case VertexBuffer.NormalKind:
  9884. this._strideSize = 3;
  9885. break;
  9886. case VertexBuffer.UVKind:
  9887. this._strideSize = 2;
  9888. break;
  9889. case VertexBuffer.UV2Kind:
  9890. this._strideSize = 2;
  9891. break;
  9892. case VertexBuffer.ColorKind:
  9893. this._strideSize = 4;
  9894. break;
  9895. case VertexBuffer.MatricesIndicesKind:
  9896. this._strideSize = 4;
  9897. break;
  9898. case VertexBuffer.MatricesWeightsKind:
  9899. this._strideSize = 4;
  9900. break;
  9901. }
  9902. }
  9903. // Properties
  9904. VertexBuffer.prototype.isUpdatable = function () {
  9905. return this._updatable;
  9906. };
  9907. VertexBuffer.prototype.getData = function () {
  9908. return this._data;
  9909. };
  9910. VertexBuffer.prototype.getBuffer = function () {
  9911. return this._buffer;
  9912. };
  9913. VertexBuffer.prototype.getStrideSize = function () {
  9914. return this._strideSize;
  9915. };
  9916. // Methods
  9917. VertexBuffer.prototype.create = function (data) {
  9918. if (!data && this._buffer) {
  9919. return; // nothing to do
  9920. }
  9921. data = data || this._data;
  9922. if (!this._buffer) {
  9923. if (this._updatable) {
  9924. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  9925. }
  9926. else {
  9927. this._buffer = this._engine.createVertexBuffer(data);
  9928. }
  9929. }
  9930. if (this._updatable) {
  9931. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  9932. this._data = data;
  9933. }
  9934. };
  9935. VertexBuffer.prototype.update = function (data) {
  9936. this.create(data);
  9937. };
  9938. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  9939. if (!this._buffer) {
  9940. return;
  9941. }
  9942. if (this._updatable) {
  9943. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  9944. this._data = null;
  9945. }
  9946. };
  9947. VertexBuffer.prototype.dispose = function () {
  9948. if (!this._buffer) {
  9949. return;
  9950. }
  9951. if (this._engine._releaseBuffer(this._buffer)) {
  9952. this._buffer = null;
  9953. }
  9954. };
  9955. Object.defineProperty(VertexBuffer, "PositionKind", {
  9956. get: function () {
  9957. return VertexBuffer._PositionKind;
  9958. },
  9959. enumerable: true,
  9960. configurable: true
  9961. });
  9962. Object.defineProperty(VertexBuffer, "NormalKind", {
  9963. get: function () {
  9964. return VertexBuffer._NormalKind;
  9965. },
  9966. enumerable: true,
  9967. configurable: true
  9968. });
  9969. Object.defineProperty(VertexBuffer, "UVKind", {
  9970. get: function () {
  9971. return VertexBuffer._UVKind;
  9972. },
  9973. enumerable: true,
  9974. configurable: true
  9975. });
  9976. Object.defineProperty(VertexBuffer, "UV2Kind", {
  9977. get: function () {
  9978. return VertexBuffer._UV2Kind;
  9979. },
  9980. enumerable: true,
  9981. configurable: true
  9982. });
  9983. Object.defineProperty(VertexBuffer, "ColorKind", {
  9984. get: function () {
  9985. return VertexBuffer._ColorKind;
  9986. },
  9987. enumerable: true,
  9988. configurable: true
  9989. });
  9990. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  9991. get: function () {
  9992. return VertexBuffer._MatricesIndicesKind;
  9993. },
  9994. enumerable: true,
  9995. configurable: true
  9996. });
  9997. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  9998. get: function () {
  9999. return VertexBuffer._MatricesWeightsKind;
  10000. },
  10001. enumerable: true,
  10002. configurable: true
  10003. });
  10004. // Enums
  10005. VertexBuffer._PositionKind = "position";
  10006. VertexBuffer._NormalKind = "normal";
  10007. VertexBuffer._UVKind = "uv";
  10008. VertexBuffer._UV2Kind = "uv2";
  10009. VertexBuffer._ColorKind = "color";
  10010. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  10011. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  10012. return VertexBuffer;
  10013. })();
  10014. BABYLON.VertexBuffer = VertexBuffer;
  10015. })(BABYLON || (BABYLON = {}));
  10016. //# sourceMappingURL=babylon.vertexBuffer.js.map
  10017. var BABYLON;
  10018. (function (BABYLON) {
  10019. var AbstractMesh = (function (_super) {
  10020. __extends(AbstractMesh, _super);
  10021. function AbstractMesh(name, scene) {
  10022. _super.call(this, name, scene);
  10023. // Properties
  10024. this.definedFacingForward = true; // orientation for POV movement & rotation
  10025. this.position = new BABYLON.Vector3(0, 0, 0);
  10026. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10027. this.scaling = new BABYLON.Vector3(1, 1, 1);
  10028. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10029. this.visibility = 1.0;
  10030. this.alphaIndex = Number.MAX_VALUE;
  10031. this.infiniteDistance = false;
  10032. this.isVisible = true;
  10033. this.isPickable = true;
  10034. this.showBoundingBox = false;
  10035. this.showSubMeshesBoundingBox = false;
  10036. this.onDispose = null;
  10037. this.checkCollisions = false;
  10038. this.isBlocker = false;
  10039. this.renderingGroupId = 0;
  10040. this.receiveShadows = false;
  10041. this.renderOutline = false;
  10042. this.outlineColor = BABYLON.Color3.Red();
  10043. this.outlineWidth = 0.02;
  10044. this.renderOverlay = false;
  10045. this.overlayColor = BABYLON.Color3.Red();
  10046. this.overlayAlpha = 0.5;
  10047. this.hasVertexAlpha = false;
  10048. this.useVertexColors = true;
  10049. this.applyFog = true;
  10050. this.useOctreeForRenderingSelection = true;
  10051. this.useOctreeForPicking = true;
  10052. this.useOctreeForCollisions = true;
  10053. this.layerMask = 0x0FFFFFFF;
  10054. // Physics
  10055. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  10056. // Collisions
  10057. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10058. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10059. this._collider = new BABYLON.Collider();
  10060. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10061. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10062. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10063. // Cache
  10064. this._localScaling = BABYLON.Matrix.Zero();
  10065. this._localRotation = BABYLON.Matrix.Zero();
  10066. this._localTranslation = BABYLON.Matrix.Zero();
  10067. this._localBillboard = BABYLON.Matrix.Zero();
  10068. this._localPivotScaling = BABYLON.Matrix.Zero();
  10069. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  10070. this._localWorld = BABYLON.Matrix.Zero();
  10071. this._worldMatrix = BABYLON.Matrix.Zero();
  10072. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  10073. this._absolutePosition = BABYLON.Vector3.Zero();
  10074. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10075. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10076. this._isDirty = false;
  10077. this._pivotMatrix = BABYLON.Matrix.Identity();
  10078. this._isDisposed = false;
  10079. this._renderId = 0;
  10080. this._intersectionsInProgress = new Array();
  10081. this._onAfterWorldMatrixUpdate = new Array();
  10082. scene.addMesh(this);
  10083. }
  10084. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10085. get: function () {
  10086. return AbstractMesh._BILLBOARDMODE_NONE;
  10087. },
  10088. enumerable: true,
  10089. configurable: true
  10090. });
  10091. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10092. get: function () {
  10093. return AbstractMesh._BILLBOARDMODE_X;
  10094. },
  10095. enumerable: true,
  10096. configurable: true
  10097. });
  10098. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10099. get: function () {
  10100. return AbstractMesh._BILLBOARDMODE_Y;
  10101. },
  10102. enumerable: true,
  10103. configurable: true
  10104. });
  10105. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10106. get: function () {
  10107. return AbstractMesh._BILLBOARDMODE_Z;
  10108. },
  10109. enumerable: true,
  10110. configurable: true
  10111. });
  10112. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10113. get: function () {
  10114. return AbstractMesh._BILLBOARDMODE_ALL;
  10115. },
  10116. enumerable: true,
  10117. configurable: true
  10118. });
  10119. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  10120. // Methods
  10121. get: function () {
  10122. return false;
  10123. },
  10124. enumerable: true,
  10125. configurable: true
  10126. });
  10127. AbstractMesh.prototype.getLOD = function (camera) {
  10128. return this;
  10129. };
  10130. AbstractMesh.prototype.getTotalVertices = function () {
  10131. return 0;
  10132. };
  10133. AbstractMesh.prototype.getIndices = function () {
  10134. return null;
  10135. };
  10136. AbstractMesh.prototype.getVerticesData = function (kind) {
  10137. return null;
  10138. };
  10139. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10140. return false;
  10141. };
  10142. AbstractMesh.prototype.getBoundingInfo = function () {
  10143. if (this._masterMesh) {
  10144. return this._masterMesh.getBoundingInfo();
  10145. }
  10146. if (!this._boundingInfo) {
  10147. this._updateBoundingInfo();
  10148. }
  10149. return this._boundingInfo;
  10150. };
  10151. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10152. get: function () {
  10153. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10154. },
  10155. enumerable: true,
  10156. configurable: true
  10157. });
  10158. AbstractMesh.prototype._preActivate = function () {
  10159. };
  10160. AbstractMesh.prototype._activate = function (renderId) {
  10161. this._renderId = renderId;
  10162. };
  10163. AbstractMesh.prototype.getWorldMatrix = function () {
  10164. if (this._masterMesh) {
  10165. return this._masterMesh.getWorldMatrix();
  10166. }
  10167. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10168. this.computeWorldMatrix();
  10169. }
  10170. return this._worldMatrix;
  10171. };
  10172. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10173. get: function () {
  10174. return this._worldMatrix;
  10175. },
  10176. enumerable: true,
  10177. configurable: true
  10178. });
  10179. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10180. get: function () {
  10181. return this._absolutePosition;
  10182. },
  10183. enumerable: true,
  10184. configurable: true
  10185. });
  10186. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10187. if (!this.rotationQuaternion) {
  10188. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10189. this.rotation = BABYLON.Vector3.Zero();
  10190. }
  10191. if (!space || space === 0 /* LOCAL */) {
  10192. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  10193. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  10194. }
  10195. else {
  10196. if (this.parent) {
  10197. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10198. invertParentWorldMatrix.invert();
  10199. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10200. }
  10201. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  10202. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  10203. }
  10204. };
  10205. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10206. var displacementVector = axis.scale(distance);
  10207. if (!space || space === 0 /* LOCAL */) {
  10208. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10209. this.setPositionWithLocalVector(tempV3);
  10210. }
  10211. else {
  10212. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10213. }
  10214. };
  10215. AbstractMesh.prototype.getAbsolutePosition = function () {
  10216. this.computeWorldMatrix();
  10217. return this._absolutePosition;
  10218. };
  10219. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10220. if (!absolutePosition) {
  10221. return;
  10222. }
  10223. var absolutePositionX;
  10224. var absolutePositionY;
  10225. var absolutePositionZ;
  10226. if (absolutePosition.x === undefined) {
  10227. if (arguments.length < 3) {
  10228. return;
  10229. }
  10230. absolutePositionX = arguments[0];
  10231. absolutePositionY = arguments[1];
  10232. absolutePositionZ = arguments[2];
  10233. }
  10234. else {
  10235. absolutePositionX = absolutePosition.x;
  10236. absolutePositionY = absolutePosition.y;
  10237. absolutePositionZ = absolutePosition.z;
  10238. }
  10239. if (this.parent) {
  10240. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10241. invertParentWorldMatrix.invert();
  10242. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10243. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10244. }
  10245. else {
  10246. this.position.x = absolutePositionX;
  10247. this.position.y = absolutePositionY;
  10248. this.position.z = absolutePositionZ;
  10249. }
  10250. };
  10251. // ================================== Point of View Movement =================================
  10252. /**
  10253. * Perform relative position change from the point of view of behind the front of the mesh.
  10254. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10255. * Supports definition of mesh facing forward or backward.
  10256. * @param {number} amountRight
  10257. * @param {number} amountUp
  10258. * @param {number} amountForward
  10259. */
  10260. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10261. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10262. };
  10263. /**
  10264. * Calculate relative position change from the point of view of behind the front of the mesh.
  10265. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10266. * Supports definition of mesh facing forward or backward.
  10267. * @param {number} amountRight
  10268. * @param {number} amountUp
  10269. * @param {number} amountForward
  10270. */
  10271. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10272. var rotMatrix = new BABYLON.Matrix();
  10273. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10274. rotQuaternion.toRotationMatrix(rotMatrix);
  10275. var translationDelta = BABYLON.Vector3.Zero();
  10276. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10277. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10278. return translationDelta;
  10279. };
  10280. // ================================== Point of View Rotation =================================
  10281. /**
  10282. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10283. * Supports definition of mesh facing forward or backward.
  10284. * @param {number} flipBack
  10285. * @param {number} twirlClockwise
  10286. * @param {number} tiltRight
  10287. */
  10288. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10289. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10290. };
  10291. /**
  10292. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10293. * Supports definition of mesh facing forward or backward.
  10294. * @param {number} flipBack
  10295. * @param {number} twirlClockwise
  10296. * @param {number} tiltRight
  10297. */
  10298. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10299. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10300. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10301. };
  10302. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10303. this._pivotMatrix = matrix;
  10304. this._cache.pivotMatrixUpdated = true;
  10305. };
  10306. AbstractMesh.prototype.getPivotMatrix = function () {
  10307. return this._pivotMatrix;
  10308. };
  10309. AbstractMesh.prototype._isSynchronized = function () {
  10310. if (this._isDirty) {
  10311. return false;
  10312. }
  10313. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10314. return false;
  10315. if (this._cache.pivotMatrixUpdated) {
  10316. return false;
  10317. }
  10318. if (this.infiniteDistance) {
  10319. return false;
  10320. }
  10321. if (!this._cache.position.equals(this.position))
  10322. return false;
  10323. if (this.rotationQuaternion) {
  10324. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10325. return false;
  10326. }
  10327. else {
  10328. if (!this._cache.rotation.equals(this.rotation))
  10329. return false;
  10330. }
  10331. if (!this._cache.scaling.equals(this.scaling))
  10332. return false;
  10333. return true;
  10334. };
  10335. AbstractMesh.prototype._initCache = function () {
  10336. _super.prototype._initCache.call(this);
  10337. this._cache.localMatrixUpdated = false;
  10338. this._cache.position = BABYLON.Vector3.Zero();
  10339. this._cache.scaling = BABYLON.Vector3.Zero();
  10340. this._cache.rotation = BABYLON.Vector3.Zero();
  10341. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10342. };
  10343. AbstractMesh.prototype.markAsDirty = function (property) {
  10344. if (property === "rotation") {
  10345. this.rotationQuaternion = null;
  10346. }
  10347. this._currentRenderId = Number.MAX_VALUE;
  10348. this._isDirty = true;
  10349. };
  10350. AbstractMesh.prototype._updateBoundingInfo = function () {
  10351. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10352. this._boundingInfo._update(this.worldMatrixFromCache);
  10353. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10354. };
  10355. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10356. if (!this.subMeshes) {
  10357. return;
  10358. }
  10359. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10360. var subMesh = this.subMeshes[subIndex];
  10361. subMesh.updateBoundingInfo(matrix);
  10362. }
  10363. };
  10364. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10365. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10366. return this._worldMatrix;
  10367. }
  10368. this._cache.position.copyFrom(this.position);
  10369. this._cache.scaling.copyFrom(this.scaling);
  10370. this._cache.pivotMatrixUpdated = false;
  10371. this._currentRenderId = this.getScene().getRenderId();
  10372. this._isDirty = false;
  10373. // Scaling
  10374. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  10375. // Rotation
  10376. if (this.rotationQuaternion) {
  10377. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  10378. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10379. }
  10380. else {
  10381. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  10382. this._cache.rotation.copyFrom(this.rotation);
  10383. }
  10384. // Translation
  10385. if (this.infiniteDistance && !this.parent) {
  10386. var camera = this.getScene().activeCamera;
  10387. var cameraWorldMatrix = camera.getWorldMatrix();
  10388. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10389. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  10390. }
  10391. else {
  10392. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  10393. }
  10394. // Composing transformations
  10395. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  10396. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  10397. // Billboarding
  10398. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10399. var localPosition = this.position.clone();
  10400. var zero = this.getScene().activeCamera.position.clone();
  10401. if (this.parent && this.parent.position) {
  10402. localPosition.addInPlace(this.parent.position);
  10403. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  10404. }
  10405. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  10406. zero = this.getScene().activeCamera.position;
  10407. }
  10408. else {
  10409. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10410. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  10411. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10412. zero.y = localPosition.y + 0.001;
  10413. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10414. zero.z = localPosition.z + 0.001;
  10415. }
  10416. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  10417. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  10418. this._localBillboard.invert();
  10419. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  10420. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  10421. }
  10422. // Local world
  10423. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  10424. // Parent
  10425. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10426. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10427. }
  10428. else {
  10429. this._worldMatrix.copyFrom(this._localWorld);
  10430. }
  10431. // Bounding info
  10432. this._updateBoundingInfo();
  10433. // Absolute position
  10434. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10435. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  10436. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  10437. }
  10438. return this._worldMatrix;
  10439. };
  10440. /**
  10441. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10442. * @param func: callback function to add
  10443. */
  10444. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10445. this._onAfterWorldMatrixUpdate.push(func);
  10446. };
  10447. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10448. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  10449. if (index > -1) {
  10450. this._onAfterWorldMatrixUpdate.splice(index, 1);
  10451. }
  10452. };
  10453. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10454. this.computeWorldMatrix();
  10455. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10456. };
  10457. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10458. this.computeWorldMatrix();
  10459. var invLocalWorldMatrix = this._localWorld.clone();
  10460. invLocalWorldMatrix.invert();
  10461. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10462. };
  10463. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10464. this.computeWorldMatrix();
  10465. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10466. };
  10467. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  10468. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10469. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10470. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10471. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10472. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10473. /// <returns>Mesh oriented towards targetMesh</returns>
  10474. yawCor = yawCor || 0; // default to zero if undefined
  10475. pitchCor = pitchCor || 0;
  10476. rollCor = rollCor || 0;
  10477. var dv = targetPoint.subtract(this.position);
  10478. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10479. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10480. var pitch = Math.atan2(dv.y, len);
  10481. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  10482. };
  10483. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10484. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  10485. return false;
  10486. }
  10487. return true;
  10488. };
  10489. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  10490. if (!camera) {
  10491. camera = this.getScene().activeCamera;
  10492. }
  10493. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  10494. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  10495. return false;
  10496. }
  10497. return true;
  10498. };
  10499. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10500. if (!this._boundingInfo || !mesh._boundingInfo) {
  10501. return false;
  10502. }
  10503. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10504. };
  10505. AbstractMesh.prototype.intersectsPoint = function (point) {
  10506. if (!this._boundingInfo) {
  10507. return false;
  10508. }
  10509. return this._boundingInfo.intersectsPoint(point);
  10510. };
  10511. // Physics
  10512. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10513. var physicsEngine = this.getScene().getPhysicsEngine();
  10514. if (!physicsEngine) {
  10515. return;
  10516. }
  10517. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  10518. if (impostor.impostor) {
  10519. // Old API
  10520. options = impostor;
  10521. impostor = impostor.impostor;
  10522. }
  10523. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  10524. physicsEngine._unregisterMesh(this);
  10525. return;
  10526. }
  10527. if (!options) {
  10528. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  10529. }
  10530. else {
  10531. if (!options.mass && options.mass !== 0)
  10532. options.mass = 0;
  10533. if (!options.friction && options.friction !== 0)
  10534. options.friction = 0.2;
  10535. if (!options.restitution && options.restitution !== 0)
  10536. options.restitution = 0.2;
  10537. }
  10538. this._physicImpostor = impostor;
  10539. this._physicsMass = options.mass;
  10540. this._physicsFriction = options.friction;
  10541. this._physicRestitution = options.restitution;
  10542. return physicsEngine._registerMesh(this, impostor, options);
  10543. };
  10544. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10545. if (!this._physicImpostor) {
  10546. return BABYLON.PhysicsEngine.NoImpostor;
  10547. }
  10548. return this._physicImpostor;
  10549. };
  10550. AbstractMesh.prototype.getPhysicsMass = function () {
  10551. if (!this._physicsMass) {
  10552. return 0;
  10553. }
  10554. return this._physicsMass;
  10555. };
  10556. AbstractMesh.prototype.getPhysicsFriction = function () {
  10557. if (!this._physicsFriction) {
  10558. return 0;
  10559. }
  10560. return this._physicsFriction;
  10561. };
  10562. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10563. if (!this._physicRestitution) {
  10564. return 0;
  10565. }
  10566. return this._physicRestitution;
  10567. };
  10568. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10569. if (!camera) {
  10570. camera = this.getScene().activeCamera;
  10571. }
  10572. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10573. };
  10574. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10575. if (!camera) {
  10576. camera = this.getScene().activeCamera;
  10577. }
  10578. return this.absolutePosition.subtract(camera.position).length();
  10579. };
  10580. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10581. if (!this._physicImpostor) {
  10582. return;
  10583. }
  10584. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  10585. };
  10586. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10587. if (!this._physicImpostor) {
  10588. return;
  10589. }
  10590. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  10591. };
  10592. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10593. if (!this._physicImpostor) {
  10594. return;
  10595. }
  10596. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  10597. };
  10598. // Collisions
  10599. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10600. var globalPosition = this.getAbsolutePosition();
  10601. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10602. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10603. this._collider.radius = this.ellipsoid;
  10604. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  10605. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  10606. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10607. this.position.addInPlace(this._diffPositionForCollisions);
  10608. }
  10609. };
  10610. // Submeshes octree
  10611. /**
  10612. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10613. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10614. */
  10615. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10616. if (maxCapacity === void 0) { maxCapacity = 64; }
  10617. if (maxDepth === void 0) { maxDepth = 2; }
  10618. if (!this._submeshesOctree) {
  10619. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10620. }
  10621. this.computeWorldMatrix(true);
  10622. // Update octree
  10623. var bbox = this.getBoundingInfo().boundingBox;
  10624. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10625. return this._submeshesOctree;
  10626. };
  10627. // Collisions
  10628. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10629. this._generatePointsArray();
  10630. // Transformation
  10631. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10632. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10633. subMesh._lastColliderWorldVertices = [];
  10634. subMesh._trianglePlanes = [];
  10635. var start = subMesh.verticesStart;
  10636. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10637. for (var i = start; i < end; i++) {
  10638. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10639. }
  10640. }
  10641. // Collide
  10642. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  10643. };
  10644. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10645. var subMeshes;
  10646. var len;
  10647. // Octrees
  10648. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10649. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10650. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10651. len = intersections.length;
  10652. subMeshes = intersections.data;
  10653. }
  10654. else {
  10655. subMeshes = this.subMeshes;
  10656. len = subMeshes.length;
  10657. }
  10658. for (var index = 0; index < len; index++) {
  10659. var subMesh = subMeshes[index];
  10660. // Bounding test
  10661. if (len > 1 && !subMesh._checkCollision(collider))
  10662. continue;
  10663. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10664. }
  10665. };
  10666. AbstractMesh.prototype._checkCollision = function (collider) {
  10667. // Bounding box test
  10668. if (!this._boundingInfo._checkCollision(collider))
  10669. return;
  10670. // Transformation matrix
  10671. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10672. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10673. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10674. };
  10675. // Picking
  10676. AbstractMesh.prototype._generatePointsArray = function () {
  10677. return false;
  10678. };
  10679. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10680. var pickingInfo = new BABYLON.PickingInfo();
  10681. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10682. return pickingInfo;
  10683. }
  10684. if (!this._generatePointsArray()) {
  10685. return pickingInfo;
  10686. }
  10687. var intersectInfo = null;
  10688. // Octrees
  10689. var subMeshes;
  10690. var len;
  10691. if (this._submeshesOctree && this.useOctreeForPicking) {
  10692. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10693. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10694. len = intersections.length;
  10695. subMeshes = intersections.data;
  10696. }
  10697. else {
  10698. subMeshes = this.subMeshes;
  10699. len = subMeshes.length;
  10700. }
  10701. for (var index = 0; index < len; index++) {
  10702. var subMesh = subMeshes[index];
  10703. // Bounding test
  10704. if (len > 1 && !subMesh.canIntersects(ray))
  10705. continue;
  10706. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10707. if (currentIntersectInfo) {
  10708. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10709. intersectInfo = currentIntersectInfo;
  10710. intersectInfo.subMeshId = index;
  10711. if (fastCheck) {
  10712. break;
  10713. }
  10714. }
  10715. }
  10716. }
  10717. if (intersectInfo) {
  10718. // Get picked point
  10719. var world = this.getWorldMatrix();
  10720. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10721. var direction = ray.direction.clone();
  10722. direction = direction.scale(intersectInfo.distance);
  10723. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10724. var pickedPoint = worldOrigin.add(worldDirection);
  10725. // Return result
  10726. pickingInfo.hit = true;
  10727. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10728. pickingInfo.pickedPoint = pickedPoint;
  10729. pickingInfo.pickedMesh = this;
  10730. pickingInfo.bu = intersectInfo.bu;
  10731. pickingInfo.bv = intersectInfo.bv;
  10732. pickingInfo.faceId = intersectInfo.faceId;
  10733. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10734. return pickingInfo;
  10735. }
  10736. return pickingInfo;
  10737. };
  10738. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10739. return null;
  10740. };
  10741. AbstractMesh.prototype.releaseSubMeshes = function () {
  10742. if (this.subMeshes) {
  10743. while (this.subMeshes.length) {
  10744. this.subMeshes[0].dispose();
  10745. }
  10746. }
  10747. else {
  10748. this.subMeshes = new Array();
  10749. }
  10750. };
  10751. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10752. var index;
  10753. // Physics
  10754. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  10755. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  10756. }
  10757. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10758. var other = this._intersectionsInProgress[index];
  10759. var pos = other._intersectionsInProgress.indexOf(this);
  10760. other._intersectionsInProgress.splice(pos, 1);
  10761. }
  10762. this._intersectionsInProgress = [];
  10763. // SubMeshes
  10764. this.releaseSubMeshes();
  10765. // Remove from scene
  10766. this.getScene().removeMesh(this);
  10767. if (!doNotRecurse) {
  10768. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10769. if (this.getScene().particleSystems[index].emitter === this) {
  10770. this.getScene().particleSystems[index].dispose();
  10771. index--;
  10772. }
  10773. }
  10774. // Children
  10775. var objects = this.getScene().meshes.slice(0);
  10776. for (index = 0; index < objects.length; index++) {
  10777. if (objects[index].parent === this) {
  10778. objects[index].dispose();
  10779. }
  10780. }
  10781. }
  10782. else {
  10783. for (index = 0; index < this.getScene().meshes.length; index++) {
  10784. var obj = this.getScene().meshes[index];
  10785. if (obj.parent === this) {
  10786. obj.parent = null;
  10787. obj.computeWorldMatrix(true);
  10788. }
  10789. }
  10790. }
  10791. this._onAfterWorldMatrixUpdate = [];
  10792. this._isDisposed = true;
  10793. // Callback
  10794. if (this.onDispose) {
  10795. this.onDispose();
  10796. }
  10797. };
  10798. // Statics
  10799. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10800. AbstractMesh._BILLBOARDMODE_X = 1;
  10801. AbstractMesh._BILLBOARDMODE_Y = 2;
  10802. AbstractMesh._BILLBOARDMODE_Z = 4;
  10803. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10804. return AbstractMesh;
  10805. })(BABYLON.Node);
  10806. BABYLON.AbstractMesh = AbstractMesh;
  10807. })(BABYLON || (BABYLON = {}));
  10808. //# sourceMappingURL=babylon.abstractMesh.js.map
  10809. var BABYLON;
  10810. (function (BABYLON) {
  10811. var _InstancesBatch = (function () {
  10812. function _InstancesBatch() {
  10813. this.mustReturn = false;
  10814. this.visibleInstances = new Array();
  10815. this.renderSelf = new Array();
  10816. }
  10817. return _InstancesBatch;
  10818. })();
  10819. BABYLON._InstancesBatch = _InstancesBatch;
  10820. var Mesh = (function (_super) {
  10821. __extends(Mesh, _super);
  10822. /**
  10823. * @constructor
  10824. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  10825. * @param {Scene} scene - The scene to add this mesh to.
  10826. * @param {Node} parent - The parent of this mesh, if it has one
  10827. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  10828. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  10829. * When false, achieved by calling a clone(), also passing False.
  10830. * This will make creation of children, recursive.
  10831. */
  10832. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  10833. if (parent === void 0) { parent = null; }
  10834. _super.call(this, name, scene);
  10835. // Members
  10836. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10837. this.instances = new Array();
  10838. this._LODLevels = new Array();
  10839. this._onBeforeRenderCallbacks = new Array();
  10840. this._onAfterRenderCallbacks = new Array();
  10841. this._visibleInstances = {};
  10842. this._renderIdForInstances = new Array();
  10843. this._batchCache = new _InstancesBatch();
  10844. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  10845. this._sideOrientation = Mesh._DEFAULTSIDE;
  10846. if (source) {
  10847. // Geometry
  10848. if (source._geometry) {
  10849. source._geometry.applyToMesh(this);
  10850. }
  10851. // Deep copy
  10852. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  10853. // Material
  10854. this.material = source.material;
  10855. if (!doNotCloneChildren) {
  10856. for (var index = 0; index < scene.meshes.length; index++) {
  10857. var mesh = scene.meshes[index];
  10858. if (mesh.parent === source) {
  10859. // doNotCloneChildren is always going to be False
  10860. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  10861. }
  10862. }
  10863. }
  10864. for (index = 0; index < scene.particleSystems.length; index++) {
  10865. var system = scene.particleSystems[index];
  10866. if (system.emitter === source) {
  10867. system.clone(system.name, this);
  10868. }
  10869. }
  10870. this.computeWorldMatrix(true);
  10871. }
  10872. // Parent
  10873. if (parent !== null) {
  10874. this.parent = parent;
  10875. }
  10876. }
  10877. Object.defineProperty(Mesh, "FRONTSIDE", {
  10878. get: function () {
  10879. return Mesh._FRONTSIDE;
  10880. },
  10881. enumerable: true,
  10882. configurable: true
  10883. });
  10884. Object.defineProperty(Mesh, "BACKSIDE", {
  10885. get: function () {
  10886. return Mesh._BACKSIDE;
  10887. },
  10888. enumerable: true,
  10889. configurable: true
  10890. });
  10891. Object.defineProperty(Mesh, "DOUBLESIDE", {
  10892. get: function () {
  10893. return Mesh._DOUBLESIDE;
  10894. },
  10895. enumerable: true,
  10896. configurable: true
  10897. });
  10898. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  10899. get: function () {
  10900. return Mesh._DEFAULTSIDE;
  10901. },
  10902. enumerable: true,
  10903. configurable: true
  10904. });
  10905. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  10906. // Methods
  10907. get: function () {
  10908. return this._LODLevels.length > 0;
  10909. },
  10910. enumerable: true,
  10911. configurable: true
  10912. });
  10913. Mesh.prototype._sortLODLevels = function () {
  10914. this._LODLevels.sort(function (a, b) {
  10915. if (a.distance < b.distance) {
  10916. return 1;
  10917. }
  10918. if (a.distance > b.distance) {
  10919. return -1;
  10920. }
  10921. return 0;
  10922. });
  10923. };
  10924. /**
  10925. * Add a mesh as LOD level triggered at the given distance.
  10926. * @param {number} distance - the distance from the center of the object to show this level
  10927. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  10928. * @return {BABYLON.Mesh} this mesh (for chaining)
  10929. */
  10930. Mesh.prototype.addLODLevel = function (distance, mesh) {
  10931. if (mesh && mesh._masterMesh) {
  10932. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  10933. return this;
  10934. }
  10935. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  10936. this._LODLevels.push(level);
  10937. if (mesh) {
  10938. mesh._masterMesh = this;
  10939. }
  10940. this._sortLODLevels();
  10941. return this;
  10942. };
  10943. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  10944. for (var index = 0; index < this._LODLevels.length; index++) {
  10945. var level = this._LODLevels[index];
  10946. if (level.distance === distance) {
  10947. return level.mesh;
  10948. }
  10949. }
  10950. return null;
  10951. };
  10952. /**
  10953. * Remove a mesh from the LOD array
  10954. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  10955. * @return {BABYLON.Mesh} this mesh (for chaining)
  10956. */
  10957. Mesh.prototype.removeLODLevel = function (mesh) {
  10958. for (var index = 0; index < this._LODLevels.length; index++) {
  10959. if (this._LODLevels[index].mesh === mesh) {
  10960. this._LODLevels.splice(index, 1);
  10961. if (mesh) {
  10962. mesh._masterMesh = null;
  10963. }
  10964. }
  10965. }
  10966. this._sortLODLevels();
  10967. return this;
  10968. };
  10969. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  10970. if (!this._LODLevels || this._LODLevels.length === 0) {
  10971. return this;
  10972. }
  10973. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  10974. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  10975. if (this.onLODLevelSelection) {
  10976. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  10977. }
  10978. return this;
  10979. }
  10980. for (var index = 0; index < this._LODLevels.length; index++) {
  10981. var level = this._LODLevels[index];
  10982. if (level.distance < distanceToCamera) {
  10983. if (level.mesh) {
  10984. level.mesh._preActivate();
  10985. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10986. }
  10987. if (this.onLODLevelSelection) {
  10988. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  10989. }
  10990. return level.mesh;
  10991. }
  10992. }
  10993. if (this.onLODLevelSelection) {
  10994. this.onLODLevelSelection(distanceToCamera, this, this);
  10995. }
  10996. return this;
  10997. };
  10998. Object.defineProperty(Mesh.prototype, "geometry", {
  10999. get: function () {
  11000. return this._geometry;
  11001. },
  11002. enumerable: true,
  11003. configurable: true
  11004. });
  11005. Mesh.prototype.getTotalVertices = function () {
  11006. if (!this._geometry) {
  11007. return 0;
  11008. }
  11009. return this._geometry.getTotalVertices();
  11010. };
  11011. Mesh.prototype.getVerticesData = function (kind) {
  11012. if (!this._geometry) {
  11013. return null;
  11014. }
  11015. return this._geometry.getVerticesData(kind);
  11016. };
  11017. Mesh.prototype.getVertexBuffer = function (kind) {
  11018. if (!this._geometry) {
  11019. return undefined;
  11020. }
  11021. return this._geometry.getVertexBuffer(kind);
  11022. };
  11023. Mesh.prototype.isVerticesDataPresent = function (kind) {
  11024. if (!this._geometry) {
  11025. if (this._delayInfo) {
  11026. return this._delayInfo.indexOf(kind) !== -1;
  11027. }
  11028. return false;
  11029. }
  11030. return this._geometry.isVerticesDataPresent(kind);
  11031. };
  11032. Mesh.prototype.getVerticesDataKinds = function () {
  11033. if (!this._geometry) {
  11034. var result = [];
  11035. if (this._delayInfo) {
  11036. for (var kind in this._delayInfo) {
  11037. result.push(kind);
  11038. }
  11039. }
  11040. return result;
  11041. }
  11042. return this._geometry.getVerticesDataKinds();
  11043. };
  11044. Mesh.prototype.getTotalIndices = function () {
  11045. if (!this._geometry) {
  11046. return 0;
  11047. }
  11048. return this._geometry.getTotalIndices();
  11049. };
  11050. Mesh.prototype.getIndices = function () {
  11051. if (!this._geometry) {
  11052. return [];
  11053. }
  11054. return this._geometry.getIndices();
  11055. };
  11056. Object.defineProperty(Mesh.prototype, "isBlocked", {
  11057. get: function () {
  11058. return this._masterMesh !== null && this._masterMesh !== undefined;
  11059. },
  11060. enumerable: true,
  11061. configurable: true
  11062. });
  11063. Mesh.prototype.isReady = function () {
  11064. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11065. return false;
  11066. }
  11067. return _super.prototype.isReady.call(this);
  11068. };
  11069. Mesh.prototype.isDisposed = function () {
  11070. return this._isDisposed;
  11071. };
  11072. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  11073. get: function () {
  11074. return this._sideOrientation;
  11075. },
  11076. set: function (sideO) {
  11077. this._sideOrientation = sideO;
  11078. },
  11079. enumerable: true,
  11080. configurable: true
  11081. });
  11082. // Methods
  11083. Mesh.prototype._preActivate = function () {
  11084. var sceneRenderId = this.getScene().getRenderId();
  11085. if (this._preActivateId === sceneRenderId) {
  11086. return;
  11087. }
  11088. this._preActivateId = sceneRenderId;
  11089. this._visibleInstances = null;
  11090. };
  11091. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  11092. if (!this._visibleInstances) {
  11093. this._visibleInstances = {};
  11094. this._visibleInstances.defaultRenderId = renderId;
  11095. this._visibleInstances.selfDefaultRenderId = this._renderId;
  11096. }
  11097. if (!this._visibleInstances[renderId]) {
  11098. this._visibleInstances[renderId] = new Array();
  11099. }
  11100. this._visibleInstances[renderId].push(instance);
  11101. };
  11102. Mesh.prototype.refreshBoundingInfo = function () {
  11103. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11104. if (data) {
  11105. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  11106. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11107. }
  11108. if (this.subMeshes) {
  11109. for (var index = 0; index < this.subMeshes.length; index++) {
  11110. this.subMeshes[index].refreshBoundingInfo();
  11111. }
  11112. }
  11113. this._updateBoundingInfo();
  11114. };
  11115. Mesh.prototype._createGlobalSubMesh = function () {
  11116. var totalVertices = this.getTotalVertices();
  11117. if (!totalVertices || !this.getIndices()) {
  11118. return null;
  11119. }
  11120. this.releaseSubMeshes();
  11121. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  11122. };
  11123. Mesh.prototype.subdivide = function (count) {
  11124. if (count < 1) {
  11125. return;
  11126. }
  11127. var totalIndices = this.getTotalIndices();
  11128. var subdivisionSize = (totalIndices / count) | 0;
  11129. var offset = 0;
  11130. while (subdivisionSize % 3 !== 0) {
  11131. subdivisionSize++;
  11132. }
  11133. this.releaseSubMeshes();
  11134. for (var index = 0; index < count; index++) {
  11135. if (offset >= totalIndices) {
  11136. break;
  11137. }
  11138. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  11139. offset += subdivisionSize;
  11140. }
  11141. this.synchronizeInstances();
  11142. };
  11143. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  11144. if (kind instanceof Array) {
  11145. var temp = data;
  11146. data = kind;
  11147. kind = temp;
  11148. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  11149. }
  11150. if (!this._geometry) {
  11151. var vertexData = new BABYLON.VertexData();
  11152. vertexData.set(data, kind);
  11153. var scene = this.getScene();
  11154. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  11155. }
  11156. else {
  11157. this._geometry.setVerticesData(kind, data, updatable, stride);
  11158. }
  11159. };
  11160. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  11161. if (!this._geometry) {
  11162. return;
  11163. }
  11164. if (!makeItUnique) {
  11165. this._geometry.updateVerticesData(kind, data, updateExtends);
  11166. }
  11167. else {
  11168. this.makeGeometryUnique();
  11169. this.updateVerticesData(kind, data, updateExtends, false);
  11170. }
  11171. };
  11172. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  11173. if (!this._geometry) {
  11174. return;
  11175. }
  11176. if (!makeItUnique) {
  11177. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  11178. }
  11179. else {
  11180. this.makeGeometryUnique();
  11181. this.updateVerticesDataDirectly(kind, data, offset, false);
  11182. }
  11183. };
  11184. // Mesh positions update function :
  11185. // updates the mesh positions according to the positionFunction returned values.
  11186. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  11187. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  11188. Mesh.prototype.updateMeshPositions = function (positionFunction) {
  11189. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11190. positionFunction(positions);
  11191. var indices = this.getIndices();
  11192. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11193. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  11194. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  11195. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  11196. };
  11197. Mesh.prototype.makeGeometryUnique = function () {
  11198. if (!this._geometry) {
  11199. return;
  11200. }
  11201. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  11202. geometry.applyToMesh(this);
  11203. };
  11204. Mesh.prototype.setIndices = function (indices, totalVertices) {
  11205. if (!this._geometry) {
  11206. var vertexData = new BABYLON.VertexData();
  11207. vertexData.indices = indices;
  11208. var scene = this.getScene();
  11209. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  11210. }
  11211. else {
  11212. this._geometry.setIndices(indices, totalVertices);
  11213. }
  11214. };
  11215. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  11216. var engine = this.getScene().getEngine();
  11217. // Wireframe
  11218. var indexToBind;
  11219. switch (fillMode) {
  11220. case BABYLON.Material.PointFillMode:
  11221. indexToBind = null;
  11222. break;
  11223. case BABYLON.Material.WireFrameFillMode:
  11224. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  11225. break;
  11226. default:
  11227. case BABYLON.Material.TriangleFillMode:
  11228. indexToBind = this._geometry.getIndexBuffer();
  11229. break;
  11230. }
  11231. // VBOs
  11232. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  11233. };
  11234. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  11235. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  11236. return;
  11237. }
  11238. var engine = this.getScene().getEngine();
  11239. switch (fillMode) {
  11240. case BABYLON.Material.PointFillMode:
  11241. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  11242. break;
  11243. case BABYLON.Material.WireFrameFillMode:
  11244. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  11245. break;
  11246. default:
  11247. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  11248. }
  11249. };
  11250. Mesh.prototype.registerBeforeRender = function (func) {
  11251. this._onBeforeRenderCallbacks.push(func);
  11252. };
  11253. Mesh.prototype.unregisterBeforeRender = function (func) {
  11254. var index = this._onBeforeRenderCallbacks.indexOf(func);
  11255. if (index > -1) {
  11256. this._onBeforeRenderCallbacks.splice(index, 1);
  11257. }
  11258. };
  11259. Mesh.prototype.registerAfterRender = function (func) {
  11260. this._onAfterRenderCallbacks.push(func);
  11261. };
  11262. Mesh.prototype.unregisterAfterRender = function (func) {
  11263. var index = this._onAfterRenderCallbacks.indexOf(func);
  11264. if (index > -1) {
  11265. this._onAfterRenderCallbacks.splice(index, 1);
  11266. }
  11267. };
  11268. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  11269. var scene = this.getScene();
  11270. this._batchCache.mustReturn = false;
  11271. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  11272. this._batchCache.visibleInstances[subMeshId] = null;
  11273. if (this._visibleInstances) {
  11274. var currentRenderId = scene.getRenderId();
  11275. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  11276. var selfRenderId = this._renderId;
  11277. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  11278. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  11279. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  11280. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  11281. }
  11282. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  11283. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  11284. this._batchCache.mustReturn = true;
  11285. return this._batchCache;
  11286. }
  11287. if (currentRenderId !== selfRenderId) {
  11288. this._batchCache.renderSelf[subMeshId] = false;
  11289. }
  11290. }
  11291. this._renderIdForInstances[subMeshId] = currentRenderId;
  11292. }
  11293. return this._batchCache;
  11294. };
  11295. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  11296. var visibleInstances = batch.visibleInstances[subMesh._id];
  11297. var matricesCount = visibleInstances.length + 1;
  11298. var bufferSize = matricesCount * 16 * 4;
  11299. while (this._instancesBufferSize < bufferSize) {
  11300. this._instancesBufferSize *= 2;
  11301. }
  11302. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  11303. if (this._worldMatricesInstancesBuffer) {
  11304. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11305. }
  11306. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  11307. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  11308. }
  11309. var offset = 0;
  11310. var instancesCount = 0;
  11311. var world = this.getWorldMatrix();
  11312. if (batch.renderSelf[subMesh._id]) {
  11313. world.copyToArray(this._worldMatricesInstancesArray, offset);
  11314. offset += 16;
  11315. instancesCount++;
  11316. }
  11317. if (visibleInstances) {
  11318. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  11319. var instance = visibleInstances[instanceIndex];
  11320. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  11321. offset += 16;
  11322. instancesCount++;
  11323. }
  11324. }
  11325. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  11326. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  11327. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  11328. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  11329. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  11330. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  11331. this._draw(subMesh, fillMode, instancesCount);
  11332. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  11333. };
  11334. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  11335. var scene = this.getScene();
  11336. var engine = scene.getEngine();
  11337. if (hardwareInstancedRendering) {
  11338. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  11339. }
  11340. else {
  11341. if (batch.renderSelf[subMesh._id]) {
  11342. // Draw
  11343. if (onBeforeDraw) {
  11344. onBeforeDraw(false, this.getWorldMatrix());
  11345. }
  11346. this._draw(subMesh, fillMode);
  11347. }
  11348. if (batch.visibleInstances[subMesh._id]) {
  11349. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  11350. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  11351. // World
  11352. var world = instance.getWorldMatrix();
  11353. if (onBeforeDraw) {
  11354. onBeforeDraw(true, world);
  11355. }
  11356. // Draw
  11357. this._draw(subMesh, fillMode);
  11358. }
  11359. }
  11360. }
  11361. };
  11362. Mesh.prototype.render = function (subMesh) {
  11363. var scene = this.getScene();
  11364. // Managing instances
  11365. var batch = this._getInstancesRenderList(subMesh._id);
  11366. if (batch.mustReturn) {
  11367. return;
  11368. }
  11369. // Checking geometry state
  11370. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  11371. return;
  11372. }
  11373. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  11374. this._onBeforeRenderCallbacks[callbackIndex](this);
  11375. }
  11376. var engine = scene.getEngine();
  11377. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  11378. // Material
  11379. var effectiveMaterial = subMesh.getMaterial();
  11380. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  11381. return;
  11382. }
  11383. // Outline - step 1
  11384. var savedDepthWrite = engine.getDepthWrite();
  11385. if (this.renderOutline) {
  11386. engine.setDepthWrite(false);
  11387. scene.getOutlineRenderer().render(subMesh, batch);
  11388. engine.setDepthWrite(savedDepthWrite);
  11389. }
  11390. effectiveMaterial._preBind();
  11391. var effect = effectiveMaterial.getEffect();
  11392. // Bind
  11393. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  11394. this._bind(subMesh, effect, fillMode);
  11395. var world = this.getWorldMatrix();
  11396. effectiveMaterial.bind(world, this);
  11397. // Draw
  11398. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  11399. if (isInstance) {
  11400. effectiveMaterial.bindOnlyWorldMatrix(world);
  11401. }
  11402. });
  11403. // Unbind
  11404. effectiveMaterial.unbind();
  11405. // Outline - step 2
  11406. if (this.renderOutline && savedDepthWrite) {
  11407. engine.setDepthWrite(true);
  11408. engine.setColorWrite(false);
  11409. scene.getOutlineRenderer().render(subMesh, batch);
  11410. engine.setColorWrite(true);
  11411. }
  11412. // Overlay
  11413. if (this.renderOverlay) {
  11414. var currentMode = engine.getAlphaMode();
  11415. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11416. scene.getOutlineRenderer().render(subMesh, batch, true);
  11417. engine.setAlphaMode(currentMode);
  11418. }
  11419. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  11420. this._onAfterRenderCallbacks[callbackIndex](this);
  11421. }
  11422. };
  11423. Mesh.prototype.getEmittedParticleSystems = function () {
  11424. var results = new Array();
  11425. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  11426. var particleSystem = this.getScene().particleSystems[index];
  11427. if (particleSystem.emitter === this) {
  11428. results.push(particleSystem);
  11429. }
  11430. }
  11431. return results;
  11432. };
  11433. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  11434. var results = new Array();
  11435. var descendants = this.getDescendants();
  11436. descendants.push(this);
  11437. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  11438. var particleSystem = this.getScene().particleSystems[index];
  11439. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  11440. results.push(particleSystem);
  11441. }
  11442. }
  11443. return results;
  11444. };
  11445. Mesh.prototype.getChildren = function () {
  11446. var results = [];
  11447. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11448. var mesh = this.getScene().meshes[index];
  11449. if (mesh.parent === this) {
  11450. results.push(mesh);
  11451. }
  11452. }
  11453. return results;
  11454. };
  11455. Mesh.prototype._checkDelayState = function () {
  11456. var _this = this;
  11457. var that = this;
  11458. var scene = this.getScene();
  11459. if (this._geometry) {
  11460. this._geometry.load(scene);
  11461. }
  11462. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11463. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  11464. scene._addPendingData(that);
  11465. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  11466. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  11467. if (data instanceof ArrayBuffer) {
  11468. _this._delayLoadingFunction(data, _this);
  11469. }
  11470. else {
  11471. _this._delayLoadingFunction(JSON.parse(data), _this);
  11472. }
  11473. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11474. scene._removePendingData(_this);
  11475. }, function () {
  11476. }, scene.database, getBinaryData);
  11477. }
  11478. };
  11479. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  11480. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11481. return false;
  11482. }
  11483. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  11484. return false;
  11485. }
  11486. this._checkDelayState();
  11487. return true;
  11488. };
  11489. Mesh.prototype.setMaterialByID = function (id) {
  11490. var materials = this.getScene().materials;
  11491. for (var index = 0; index < materials.length; index++) {
  11492. if (materials[index].id === id) {
  11493. this.material = materials[index];
  11494. return;
  11495. }
  11496. }
  11497. // Multi
  11498. var multiMaterials = this.getScene().multiMaterials;
  11499. for (index = 0; index < multiMaterials.length; index++) {
  11500. if (multiMaterials[index].id === id) {
  11501. this.material = multiMaterials[index];
  11502. return;
  11503. }
  11504. }
  11505. };
  11506. Mesh.prototype.getAnimatables = function () {
  11507. var results = [];
  11508. if (this.material) {
  11509. results.push(this.material);
  11510. }
  11511. if (this.skeleton) {
  11512. results.push(this.skeleton);
  11513. }
  11514. return results;
  11515. };
  11516. // Geometry
  11517. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  11518. // Position
  11519. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  11520. return;
  11521. }
  11522. this._resetPointsArrayCache();
  11523. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11524. var temp = [];
  11525. for (var index = 0; index < data.length; index += 3) {
  11526. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11527. }
  11528. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  11529. // Normals
  11530. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  11531. return;
  11532. }
  11533. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11534. for (index = 0; index < data.length; index += 3) {
  11535. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11536. }
  11537. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  11538. };
  11539. // Cache
  11540. Mesh.prototype._resetPointsArrayCache = function () {
  11541. this._positions = null;
  11542. };
  11543. Mesh.prototype._generatePointsArray = function () {
  11544. if (this._positions)
  11545. return true;
  11546. this._positions = [];
  11547. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11548. if (!data) {
  11549. return false;
  11550. }
  11551. for (var index = 0; index < data.length; index += 3) {
  11552. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  11553. }
  11554. return true;
  11555. };
  11556. // Clone
  11557. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11558. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  11559. };
  11560. // Dispose
  11561. Mesh.prototype.dispose = function (doNotRecurse) {
  11562. if (this._geometry) {
  11563. this._geometry.releaseForMesh(this, true);
  11564. }
  11565. // Instances
  11566. if (this._worldMatricesInstancesBuffer) {
  11567. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11568. this._worldMatricesInstancesBuffer = null;
  11569. }
  11570. while (this.instances.length) {
  11571. this.instances[0].dispose();
  11572. }
  11573. _super.prototype.dispose.call(this, doNotRecurse);
  11574. };
  11575. // Geometric tools
  11576. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  11577. var _this = this;
  11578. var scene = this.getScene();
  11579. var onload = function (img) {
  11580. // Getting height map data
  11581. var canvas = document.createElement("canvas");
  11582. var context = canvas.getContext("2d");
  11583. var heightMapWidth = img.width;
  11584. var heightMapHeight = img.height;
  11585. canvas.width = heightMapWidth;
  11586. canvas.height = heightMapHeight;
  11587. context.drawImage(img, 0, 0);
  11588. // Create VertexData from map data
  11589. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11590. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11591. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  11592. //execute success callback, if set
  11593. if (onSuccess) {
  11594. onSuccess(_this);
  11595. }
  11596. };
  11597. BABYLON.Tools.LoadImage(url, onload, function () {
  11598. }, scene.database);
  11599. };
  11600. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  11601. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11602. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  11603. return;
  11604. }
  11605. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11606. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11607. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11608. var position = BABYLON.Vector3.Zero();
  11609. var normal = BABYLON.Vector3.Zero();
  11610. var uv = BABYLON.Vector2.Zero();
  11611. for (var index = 0; index < positions.length; index += 3) {
  11612. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  11613. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  11614. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  11615. // Compute height
  11616. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  11617. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  11618. var pos = (u + v * heightMapWidth) * 4;
  11619. var r = buffer[pos] / 255.0;
  11620. var g = buffer[pos + 1] / 255.0;
  11621. var b = buffer[pos + 2] / 255.0;
  11622. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  11623. normal.normalize();
  11624. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  11625. position = position.add(normal);
  11626. position.toArray(positions, index);
  11627. }
  11628. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  11629. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  11630. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  11631. };
  11632. Mesh.prototype.convertToFlatShadedMesh = function () {
  11633. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  11634. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  11635. var kinds = this.getVerticesDataKinds();
  11636. var vbs = [];
  11637. var data = [];
  11638. var newdata = [];
  11639. var updatableNormals = false;
  11640. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11641. var kind = kinds[kindIndex];
  11642. var vertexBuffer = this.getVertexBuffer(kind);
  11643. if (kind === BABYLON.VertexBuffer.NormalKind) {
  11644. updatableNormals = vertexBuffer.isUpdatable();
  11645. kinds.splice(kindIndex, 1);
  11646. kindIndex--;
  11647. continue;
  11648. }
  11649. vbs[kind] = vertexBuffer;
  11650. data[kind] = vbs[kind].getData();
  11651. newdata[kind] = [];
  11652. }
  11653. // Save previous submeshes
  11654. var previousSubmeshes = this.subMeshes.slice(0);
  11655. var indices = this.getIndices();
  11656. var totalIndices = this.getTotalIndices();
  11657. for (var index = 0; index < totalIndices; index++) {
  11658. var vertexIndex = indices[index];
  11659. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11660. kind = kinds[kindIndex];
  11661. var stride = vbs[kind].getStrideSize();
  11662. for (var offset = 0; offset < stride; offset++) {
  11663. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  11664. }
  11665. }
  11666. }
  11667. // Updating faces & normal
  11668. var normals = [];
  11669. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  11670. for (index = 0; index < totalIndices; index += 3) {
  11671. indices[index] = index;
  11672. indices[index + 1] = index + 1;
  11673. indices[index + 2] = index + 2;
  11674. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  11675. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  11676. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  11677. var p1p2 = p1.subtract(p2);
  11678. var p3p2 = p3.subtract(p2);
  11679. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  11680. for (var localIndex = 0; localIndex < 3; localIndex++) {
  11681. normals.push(normal.x);
  11682. normals.push(normal.y);
  11683. normals.push(normal.z);
  11684. }
  11685. }
  11686. this.setIndices(indices);
  11687. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  11688. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11689. kind = kinds[kindIndex];
  11690. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  11691. }
  11692. // Updating submeshes
  11693. this.releaseSubMeshes();
  11694. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  11695. var previousOne = previousSubmeshes[submeshIndex];
  11696. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  11697. }
  11698. this.synchronizeInstances();
  11699. };
  11700. // Instances
  11701. Mesh.prototype.createInstance = function (name) {
  11702. return new BABYLON.InstancedMesh(name, this);
  11703. };
  11704. Mesh.prototype.synchronizeInstances = function () {
  11705. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  11706. var instance = this.instances[instanceIndex];
  11707. instance._syncSubMeshes();
  11708. }
  11709. };
  11710. /**
  11711. * Simplify the mesh according to the given array of settings.
  11712. * Function will return immediately and will simplify async.
  11713. * @param settings a collection of simplification settings.
  11714. * @param parallelProcessing should all levels calculate parallel or one after the other.
  11715. * @param type the type of simplification to run.
  11716. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  11717. */
  11718. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  11719. if (parallelProcessing === void 0) { parallelProcessing = true; }
  11720. if (simplificationType === void 0) { simplificationType = 0 /* QUADRATIC */; }
  11721. this.getScene().simplificationQueue.addTask({
  11722. settings: settings,
  11723. parallelProcessing: parallelProcessing,
  11724. mesh: this,
  11725. simplificationType: simplificationType,
  11726. successCallback: successCallback
  11727. });
  11728. };
  11729. /**
  11730. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  11731. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  11732. * This should be used together with the simplification to avoid disappearing triangles.
  11733. * @param successCallback an optional success callback to be called after the optimization finished.
  11734. */
  11735. Mesh.prototype.optimizeIndices = function (successCallback) {
  11736. var _this = this;
  11737. var indices = this.getIndices();
  11738. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11739. var vectorPositions = [];
  11740. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  11741. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  11742. }
  11743. var dupes = [];
  11744. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  11745. var realPos = vectorPositions.length - 1 - iteration;
  11746. var testedPosition = vectorPositions[realPos];
  11747. for (var j = 0; j < realPos; ++j) {
  11748. var againstPosition = vectorPositions[j];
  11749. if (testedPosition.equals(againstPosition)) {
  11750. dupes[realPos] = j;
  11751. break;
  11752. }
  11753. }
  11754. }, function () {
  11755. for (var i = 0; i < indices.length; ++i) {
  11756. indices[i] = dupes[indices[i]] || indices[i];
  11757. }
  11758. //indices are now reordered
  11759. var originalSubMeshes = _this.subMeshes.slice(0);
  11760. _this.setIndices(indices);
  11761. _this.subMeshes = originalSubMeshes;
  11762. if (successCallback) {
  11763. successCallback(_this);
  11764. }
  11765. });
  11766. };
  11767. // Statics
  11768. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  11769. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11770. if (ribbonInstance === void 0) { ribbonInstance = null; }
  11771. if (ribbonInstance) {
  11772. // positionFunction : ribbon case
  11773. // only pathArray and sideOrientation parameters are taken into account for positions update
  11774. var positionsOfRibbon = function (pathArray, sideOrientation) {
  11775. var positionFunction = function (positions) {
  11776. var minlg = pathArray[0].length;
  11777. var i = 0;
  11778. var ns = (sideOrientation == BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  11779. for (var si = 1; si <= ns; si++) {
  11780. for (var p = 0; p < pathArray.length; p++) {
  11781. var path = pathArray[p];
  11782. var l = path.length;
  11783. minlg = (minlg < l) ? minlg : l;
  11784. var j = 0;
  11785. while (j < minlg) {
  11786. positions[i] = path[j].x;
  11787. positions[i + 1] = path[j].y;
  11788. positions[i + 2] = path[j].z;
  11789. j++;
  11790. i += 3;
  11791. }
  11792. }
  11793. }
  11794. };
  11795. return positionFunction;
  11796. };
  11797. var sideOrientation = ribbonInstance.sideOrientation;
  11798. var positionFunction = positionsOfRibbon(pathArray, sideOrientation);
  11799. ribbonInstance.updateMeshPositions(positionFunction);
  11800. return ribbonInstance;
  11801. }
  11802. else {
  11803. var ribbon = new Mesh(name, scene);
  11804. ribbon.sideOrientation = sideOrientation;
  11805. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  11806. vertexData.applyToMesh(ribbon, updatable);
  11807. return ribbon;
  11808. }
  11809. };
  11810. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  11811. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11812. var box = new Mesh(name, scene);
  11813. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  11814. vertexData.applyToMesh(box, updatable);
  11815. return box;
  11816. };
  11817. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  11818. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11819. var sphere = new Mesh(name, scene);
  11820. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  11821. vertexData.applyToMesh(sphere, updatable);
  11822. return sphere;
  11823. };
  11824. // Cylinder and cone (Code inspired by SharpDX.org)
  11825. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  11826. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11827. // subdivisions is a new parameter, we need to support old signature
  11828. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  11829. if (scene !== undefined) {
  11830. updatable = scene;
  11831. }
  11832. scene = subdivisions;
  11833. subdivisions = 1;
  11834. }
  11835. var cylinder = new Mesh(name, scene);
  11836. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  11837. vertexData.applyToMesh(cylinder, updatable);
  11838. return cylinder;
  11839. };
  11840. // Torus (Code from SharpDX.org)
  11841. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  11842. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11843. var torus = new Mesh(name, scene);
  11844. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  11845. vertexData.applyToMesh(torus, updatable);
  11846. return torus;
  11847. };
  11848. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  11849. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11850. var torusKnot = new Mesh(name, scene);
  11851. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  11852. vertexData.applyToMesh(torusKnot, updatable);
  11853. return torusKnot;
  11854. };
  11855. // Lines
  11856. Mesh.CreateLines = function (name, points, scene, updatable) {
  11857. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  11858. var vertexData = BABYLON.VertexData.CreateLines(points);
  11859. vertexData.applyToMesh(lines, updatable);
  11860. return lines;
  11861. };
  11862. // Extrusion
  11863. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, scene, updatable, sideOrientation) {
  11864. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11865. scale = scale || 1;
  11866. rotation = rotation || 0;
  11867. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, false, scene, updatable, sideOrientation);
  11868. return extruded;
  11869. };
  11870. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, scene, updatable, sideOrientation) {
  11871. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11872. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, true, scene, updatable, sideOrientation);
  11873. return extrudedCustom;
  11874. };
  11875. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, custom, scene, updtbl, side) {
  11876. var path3D = new BABYLON.Path3D(curve);
  11877. var tangents = path3D.getTangents();
  11878. var normals = path3D.getNormals();
  11879. var binormals = path3D.getBinormals();
  11880. var distances = path3D.getDistances();
  11881. var shapePaths = new Array();
  11882. var angle = 0;
  11883. var returnScale = function (i, distance) {
  11884. return scale;
  11885. };
  11886. var returnRotation = function (i, distance) {
  11887. return rotation;
  11888. };
  11889. var rotate = custom ? rotateFunction : returnRotation;
  11890. var scl = custom ? scaleFunction : returnScale;
  11891. for (var i = 0; i < curve.length; i++) {
  11892. var shapePath = new Array();
  11893. var angleStep = rotate(i, distances[i]);
  11894. var scaleRatio = scl(i, distances[i]);
  11895. for (var p = 0; p < shape.length; p++) {
  11896. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  11897. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  11898. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  11899. shapePath.push(rotated);
  11900. }
  11901. shapePaths.push(shapePath);
  11902. angle += angleStep;
  11903. }
  11904. var extrudedGeneric = Mesh.CreateRibbon(name, shapePaths, rbCA, rbCP, 0, scene, updtbl, side);
  11905. return extrudedGeneric;
  11906. };
  11907. // Plane & ground
  11908. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  11909. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11910. var plane = new Mesh(name, scene);
  11911. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  11912. vertexData.applyToMesh(plane, updatable);
  11913. return plane;
  11914. };
  11915. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  11916. var ground = new BABYLON.GroundMesh(name, scene);
  11917. ground._setReady(false);
  11918. ground._subdivisions = subdivisions;
  11919. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  11920. vertexData.applyToMesh(ground, updatable);
  11921. ground._setReady(true);
  11922. return ground;
  11923. };
  11924. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  11925. var tiledGround = new Mesh(name, scene);
  11926. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  11927. vertexData.applyToMesh(tiledGround, updatable);
  11928. return tiledGround;
  11929. };
  11930. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  11931. var ground = new BABYLON.GroundMesh(name, scene);
  11932. ground._subdivisions = subdivisions;
  11933. ground._setReady(false);
  11934. var onload = function (img) {
  11935. // Getting height map data
  11936. var canvas = document.createElement("canvas");
  11937. var context = canvas.getContext("2d");
  11938. var heightMapWidth = img.width;
  11939. var heightMapHeight = img.height;
  11940. canvas.width = heightMapWidth;
  11941. canvas.height = heightMapHeight;
  11942. context.drawImage(img, 0, 0);
  11943. // Create VertexData from map data
  11944. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11945. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11946. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  11947. vertexData.applyToMesh(ground, updatable);
  11948. ground._setReady(true);
  11949. //execute ready callback, if set
  11950. if (onReady) {
  11951. onReady(ground);
  11952. }
  11953. };
  11954. BABYLON.Tools.LoadImage(url, onload, function () {
  11955. }, scene.database);
  11956. return ground;
  11957. };
  11958. Mesh.CreateTube = function (name, path, radius, tesselation, radiusFunction, scene, updatable, sideOrientation) {
  11959. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11960. var path3D = new BABYLON.Path3D(path);
  11961. var tangents = path3D.getTangents();
  11962. var normals = path3D.getNormals();
  11963. var distances = path3D.getDistances();
  11964. var pi2 = Math.PI * 2;
  11965. var step = pi2 / tesselation;
  11966. var returnRadius = function (i, distance) { return radius; };
  11967. var radiusFunctionFinal = radiusFunction || returnRadius;
  11968. var circlePaths = new Array();
  11969. var circlePath;
  11970. var rad;
  11971. var normal;
  11972. var rotated;
  11973. var rotationMatrix;
  11974. for (var i = 0; i < path.length; i++) {
  11975. rad = radiusFunctionFinal(i, distances[i]); // current radius
  11976. circlePath = Array(); // current circle array
  11977. normal = normals[i]; // current normal
  11978. for (var ang = 0; ang < pi2; ang += step) {
  11979. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], ang);
  11980. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  11981. circlePath.push(rotated);
  11982. }
  11983. circlePaths.push(circlePath);
  11984. }
  11985. var tube = Mesh.CreateRibbon(name, circlePaths, false, true, 0, scene, updatable, sideOrientation);
  11986. return tube;
  11987. };
  11988. // Decals
  11989. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  11990. if (angle === void 0) { angle = 0; }
  11991. var indices = sourceMesh.getIndices();
  11992. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11993. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11994. // Getting correct rotation
  11995. if (!normal) {
  11996. var target = new BABYLON.Vector3(0, 0, 1);
  11997. var camera = sourceMesh.getScene().activeCamera;
  11998. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  11999. normal = camera.globalPosition.subtract(cameraWorldTarget);
  12000. }
  12001. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  12002. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  12003. var pitch = Math.atan2(normal.y, len);
  12004. // Matrix
  12005. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  12006. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  12007. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  12008. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  12009. var vertexData = new BABYLON.VertexData();
  12010. vertexData.indices = [];
  12011. vertexData.positions = [];
  12012. vertexData.normals = [];
  12013. vertexData.uvs = [];
  12014. var currentVertexDataIndex = 0;
  12015. var extractDecalVector3 = function (indexId) {
  12016. var vertexId = indices[indexId];
  12017. var result = new BABYLON.PositionNormalVertex();
  12018. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  12019. // Send vector to decal local world
  12020. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  12021. // Get normal
  12022. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  12023. return result;
  12024. };
  12025. // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  12026. var clip = function (vertices, axis) {
  12027. if (vertices.length === 0) {
  12028. return vertices;
  12029. }
  12030. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  12031. var clipVertices = function (v0, v1) {
  12032. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  12033. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  12034. };
  12035. var result = new Array();
  12036. for (var index = 0; index < vertices.length; index += 3) {
  12037. var v1Out;
  12038. var v2Out;
  12039. var v3Out;
  12040. var total = 0;
  12041. var nV1, nV2, nV3, nV4;
  12042. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  12043. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  12044. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  12045. v1Out = d1 > 0;
  12046. v2Out = d2 > 0;
  12047. v3Out = d3 > 0;
  12048. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  12049. switch (total) {
  12050. case 0:
  12051. result.push(vertices[index]);
  12052. result.push(vertices[index + 1]);
  12053. result.push(vertices[index + 2]);
  12054. break;
  12055. case 1:
  12056. if (v1Out) {
  12057. nV1 = vertices[index + 1];
  12058. nV2 = vertices[index + 2];
  12059. nV3 = clipVertices(vertices[index], nV1);
  12060. nV4 = clipVertices(vertices[index], nV2);
  12061. }
  12062. if (v2Out) {
  12063. nV1 = vertices[index];
  12064. nV2 = vertices[index + 2];
  12065. nV3 = clipVertices(vertices[index + 1], nV1);
  12066. nV4 = clipVertices(vertices[index + 1], nV2);
  12067. result.push(nV3);
  12068. result.push(nV2.clone());
  12069. result.push(nV1.clone());
  12070. result.push(nV2.clone());
  12071. result.push(nV3.clone());
  12072. result.push(nV4);
  12073. break;
  12074. }
  12075. if (v3Out) {
  12076. nV1 = vertices[index];
  12077. nV2 = vertices[index + 1];
  12078. nV3 = clipVertices(vertices[index + 2], nV1);
  12079. nV4 = clipVertices(vertices[index + 2], nV2);
  12080. }
  12081. result.push(nV1.clone());
  12082. result.push(nV2.clone());
  12083. result.push(nV3);
  12084. result.push(nV4);
  12085. result.push(nV3.clone());
  12086. result.push(nV2.clone());
  12087. break;
  12088. case 2:
  12089. if (!v1Out) {
  12090. nV1 = vertices[index].clone();
  12091. nV2 = clipVertices(nV1, vertices[index + 1]);
  12092. nV3 = clipVertices(nV1, vertices[index + 2]);
  12093. result.push(nV1);
  12094. result.push(nV2);
  12095. result.push(nV3);
  12096. }
  12097. if (!v2Out) {
  12098. nV1 = vertices[index + 1].clone();
  12099. nV2 = clipVertices(nV1, vertices[index + 2]);
  12100. nV3 = clipVertices(nV1, vertices[index]);
  12101. result.push(nV1);
  12102. result.push(nV2);
  12103. result.push(nV3);
  12104. }
  12105. if (!v3Out) {
  12106. nV1 = vertices[index + 2].clone();
  12107. nV2 = clipVertices(nV1, vertices[index]);
  12108. nV3 = clipVertices(nV1, vertices[index + 1]);
  12109. result.push(nV1);
  12110. result.push(nV2);
  12111. result.push(nV3);
  12112. }
  12113. break;
  12114. case 3:
  12115. break;
  12116. }
  12117. }
  12118. return result;
  12119. };
  12120. for (var index = 0; index < indices.length; index += 3) {
  12121. var faceVertices = new Array();
  12122. faceVertices.push(extractDecalVector3(index));
  12123. faceVertices.push(extractDecalVector3(index + 1));
  12124. faceVertices.push(extractDecalVector3(index + 2));
  12125. // Clip
  12126. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  12127. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  12128. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  12129. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  12130. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  12131. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  12132. if (faceVertices.length === 0) {
  12133. continue;
  12134. }
  12135. // Add UVs and get back to world
  12136. var localRotationMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle);
  12137. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  12138. var vertex = faceVertices[vIndex];
  12139. vertexData.indices.push(currentVertexDataIndex);
  12140. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  12141. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  12142. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  12143. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  12144. currentVertexDataIndex++;
  12145. }
  12146. }
  12147. // Return mesh
  12148. var decal = new Mesh(name, sourceMesh.getScene());
  12149. vertexData.applyToMesh(decal);
  12150. decal.position = position.clone();
  12151. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  12152. return decal;
  12153. };
  12154. // Tools
  12155. Mesh.MinMax = function (meshes) {
  12156. var minVector = null;
  12157. var maxVector = null;
  12158. for (var i in meshes) {
  12159. var mesh = meshes[i];
  12160. var boundingBox = mesh.getBoundingInfo().boundingBox;
  12161. if (!minVector) {
  12162. minVector = boundingBox.minimumWorld;
  12163. maxVector = boundingBox.maximumWorld;
  12164. continue;
  12165. }
  12166. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  12167. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  12168. }
  12169. return {
  12170. min: minVector,
  12171. max: maxVector
  12172. };
  12173. };
  12174. Mesh.Center = function (meshesOrMinMaxVector) {
  12175. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  12176. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  12177. };
  12178. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  12179. if (disposeSource === void 0) { disposeSource = true; }
  12180. var source = meshes[0];
  12181. var material = source.material;
  12182. var scene = source.getScene();
  12183. if (!allow32BitsIndices) {
  12184. var totalVertices = 0;
  12185. for (var index = 0; index < meshes.length; index++) {
  12186. totalVertices += meshes[index].getTotalVertices();
  12187. if (totalVertices > 65536) {
  12188. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  12189. return null;
  12190. }
  12191. }
  12192. }
  12193. // Merge
  12194. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  12195. vertexData.transform(source.getWorldMatrix());
  12196. for (index = 1; index < meshes.length; index++) {
  12197. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  12198. otherVertexData.transform(meshes[index].getWorldMatrix());
  12199. vertexData.merge(otherVertexData);
  12200. }
  12201. var newMesh = new Mesh(source.name + "_merged", scene);
  12202. vertexData.applyToMesh(newMesh);
  12203. // Setting properties
  12204. newMesh.material = material;
  12205. newMesh.checkCollisions = source.checkCollisions;
  12206. // Cleaning
  12207. if (disposeSource) {
  12208. for (index = 0; index < meshes.length; index++) {
  12209. meshes[index].dispose();
  12210. }
  12211. }
  12212. return newMesh;
  12213. };
  12214. // Consts
  12215. Mesh._FRONTSIDE = 0;
  12216. Mesh._BACKSIDE = 1;
  12217. Mesh._DOUBLESIDE = 2;
  12218. Mesh._DEFAULTSIDE = 0;
  12219. return Mesh;
  12220. })(BABYLON.AbstractMesh);
  12221. BABYLON.Mesh = Mesh;
  12222. })(BABYLON || (BABYLON = {}));
  12223. //# sourceMappingURL=babylon.mesh.js.map
  12224. var BABYLON;
  12225. (function (BABYLON) {
  12226. var GroundMesh = (function (_super) {
  12227. __extends(GroundMesh, _super);
  12228. function GroundMesh(name, scene) {
  12229. _super.call(this, name, scene);
  12230. this.generateOctree = false;
  12231. this._worldInverse = new BABYLON.Matrix();
  12232. }
  12233. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  12234. get: function () {
  12235. return this._subdivisions;
  12236. },
  12237. enumerable: true,
  12238. configurable: true
  12239. });
  12240. GroundMesh.prototype.optimize = function (chunksCount) {
  12241. this.subdivide(this._subdivisions);
  12242. this.createOrUpdateSubmeshesOctree(32);
  12243. };
  12244. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  12245. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  12246. this.getWorldMatrix().invertToRef(this._worldInverse);
  12247. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  12248. var pickInfo = this.intersects(ray);
  12249. if (pickInfo.hit) {
  12250. return pickInfo.pickedPoint.y;
  12251. }
  12252. return 0;
  12253. };
  12254. return GroundMesh;
  12255. })(BABYLON.Mesh);
  12256. BABYLON.GroundMesh = GroundMesh;
  12257. })(BABYLON || (BABYLON = {}));
  12258. //# sourceMappingURL=babylon.groundMesh.js.map
  12259. var BABYLON;
  12260. (function (BABYLON) {
  12261. /**
  12262. * Creates an instance based on a source mesh.
  12263. */
  12264. var InstancedMesh = (function (_super) {
  12265. __extends(InstancedMesh, _super);
  12266. function InstancedMesh(name, source) {
  12267. _super.call(this, name, source.getScene());
  12268. source.instances.push(this);
  12269. this._sourceMesh = source;
  12270. this.position.copyFrom(source.position);
  12271. this.rotation.copyFrom(source.rotation);
  12272. this.scaling.copyFrom(source.scaling);
  12273. if (source.rotationQuaternion) {
  12274. this.rotationQuaternion = source.rotationQuaternion.clone();
  12275. }
  12276. this.infiniteDistance = source.infiniteDistance;
  12277. this.setPivotMatrix(source.getPivotMatrix());
  12278. this.refreshBoundingInfo();
  12279. this._syncSubMeshes();
  12280. }
  12281. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  12282. // Methods
  12283. get: function () {
  12284. return this._sourceMesh.receiveShadows;
  12285. },
  12286. enumerable: true,
  12287. configurable: true
  12288. });
  12289. Object.defineProperty(InstancedMesh.prototype, "material", {
  12290. get: function () {
  12291. return this._sourceMesh.material;
  12292. },
  12293. enumerable: true,
  12294. configurable: true
  12295. });
  12296. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  12297. get: function () {
  12298. return this._sourceMesh.visibility;
  12299. },
  12300. enumerable: true,
  12301. configurable: true
  12302. });
  12303. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  12304. get: function () {
  12305. return this._sourceMesh.skeleton;
  12306. },
  12307. enumerable: true,
  12308. configurable: true
  12309. });
  12310. InstancedMesh.prototype.getTotalVertices = function () {
  12311. return this._sourceMesh.getTotalVertices();
  12312. };
  12313. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  12314. get: function () {
  12315. return this._sourceMesh;
  12316. },
  12317. enumerable: true,
  12318. configurable: true
  12319. });
  12320. InstancedMesh.prototype.getVerticesData = function (kind) {
  12321. return this._sourceMesh.getVerticesData(kind);
  12322. };
  12323. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  12324. return this._sourceMesh.isVerticesDataPresent(kind);
  12325. };
  12326. InstancedMesh.prototype.getIndices = function () {
  12327. return this._sourceMesh.getIndices();
  12328. };
  12329. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  12330. get: function () {
  12331. return this._sourceMesh._positions;
  12332. },
  12333. enumerable: true,
  12334. configurable: true
  12335. });
  12336. InstancedMesh.prototype.refreshBoundingInfo = function () {
  12337. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12338. if (data) {
  12339. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  12340. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  12341. }
  12342. this._updateBoundingInfo();
  12343. };
  12344. InstancedMesh.prototype._preActivate = function () {
  12345. if (this._currentLOD) {
  12346. this._currentLOD._preActivate();
  12347. }
  12348. };
  12349. InstancedMesh.prototype._activate = function (renderId) {
  12350. if (this._currentLOD) {
  12351. this._currentLOD._registerInstanceForRenderId(this, renderId);
  12352. }
  12353. };
  12354. InstancedMesh.prototype.getLOD = function (camera) {
  12355. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  12356. if (this._currentLOD === this.sourceMesh) {
  12357. return this;
  12358. }
  12359. return this._currentLOD;
  12360. };
  12361. InstancedMesh.prototype._syncSubMeshes = function () {
  12362. this.releaseSubMeshes();
  12363. if (this._sourceMesh.subMeshes) {
  12364. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  12365. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  12366. }
  12367. }
  12368. };
  12369. InstancedMesh.prototype._generatePointsArray = function () {
  12370. return this._sourceMesh._generatePointsArray();
  12371. };
  12372. // Clone
  12373. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  12374. var result = this._sourceMesh.createInstance(name);
  12375. // Deep copy
  12376. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  12377. // Bounding info
  12378. this.refreshBoundingInfo();
  12379. // Parent
  12380. if (newParent) {
  12381. result.parent = newParent;
  12382. }
  12383. if (!doNotCloneChildren) {
  12384. for (var index = 0; index < this.getScene().meshes.length; index++) {
  12385. var mesh = this.getScene().meshes[index];
  12386. if (mesh.parent === this) {
  12387. mesh.clone(mesh.name, result);
  12388. }
  12389. }
  12390. }
  12391. result.computeWorldMatrix(true);
  12392. return result;
  12393. };
  12394. // Dispoe
  12395. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  12396. // Remove from mesh
  12397. var index = this._sourceMesh.instances.indexOf(this);
  12398. this._sourceMesh.instances.splice(index, 1);
  12399. _super.prototype.dispose.call(this, doNotRecurse);
  12400. };
  12401. return InstancedMesh;
  12402. })(BABYLON.AbstractMesh);
  12403. BABYLON.InstancedMesh = InstancedMesh;
  12404. })(BABYLON || (BABYLON = {}));
  12405. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  12406. (function (BABYLON) {
  12407. var SubMesh = (function () {
  12408. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  12409. if (createBoundingBox === void 0) { createBoundingBox = true; }
  12410. this.materialIndex = materialIndex;
  12411. this.verticesStart = verticesStart;
  12412. this.verticesCount = verticesCount;
  12413. this.indexStart = indexStart;
  12414. this.indexCount = indexCount;
  12415. this._renderId = 0;
  12416. this._mesh = mesh;
  12417. this._renderingMesh = renderingMesh || mesh;
  12418. mesh.subMeshes.push(this);
  12419. this._id = mesh.subMeshes.length - 1;
  12420. if (createBoundingBox) {
  12421. this.refreshBoundingInfo();
  12422. mesh.computeWorldMatrix(true);
  12423. }
  12424. }
  12425. SubMesh.prototype.getBoundingInfo = function () {
  12426. return this._boundingInfo;
  12427. };
  12428. SubMesh.prototype.getMesh = function () {
  12429. return this._mesh;
  12430. };
  12431. SubMesh.prototype.getRenderingMesh = function () {
  12432. return this._renderingMesh;
  12433. };
  12434. SubMesh.prototype.getMaterial = function () {
  12435. var rootMaterial = this._renderingMesh.material;
  12436. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  12437. var multiMaterial = rootMaterial;
  12438. return multiMaterial.getSubMaterial(this.materialIndex);
  12439. }
  12440. if (!rootMaterial) {
  12441. return this._mesh.getScene().defaultMaterial;
  12442. }
  12443. return rootMaterial;
  12444. };
  12445. // Methods
  12446. SubMesh.prototype.refreshBoundingInfo = function () {
  12447. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12448. if (!data) {
  12449. this._boundingInfo = this._mesh._boundingInfo;
  12450. return;
  12451. }
  12452. var indices = this._renderingMesh.getIndices();
  12453. var extend;
  12454. if (this.indexStart === 0 && this.indexCount === indices.length) {
  12455. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  12456. }
  12457. else {
  12458. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  12459. }
  12460. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  12461. };
  12462. SubMesh.prototype._checkCollision = function (collider) {
  12463. return this._boundingInfo._checkCollision(collider);
  12464. };
  12465. SubMesh.prototype.updateBoundingInfo = function (world) {
  12466. if (!this._boundingInfo) {
  12467. this.refreshBoundingInfo();
  12468. }
  12469. this._boundingInfo._update(world);
  12470. };
  12471. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  12472. return this._boundingInfo.isInFrustum(frustumPlanes);
  12473. };
  12474. SubMesh.prototype.render = function () {
  12475. this._renderingMesh.render(this);
  12476. };
  12477. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  12478. if (!this._linesIndexBuffer) {
  12479. var linesIndices = [];
  12480. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  12481. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  12482. }
  12483. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  12484. this.linesIndexCount = linesIndices.length;
  12485. }
  12486. return this._linesIndexBuffer;
  12487. };
  12488. SubMesh.prototype.canIntersects = function (ray) {
  12489. return ray.intersectsBox(this._boundingInfo.boundingBox);
  12490. };
  12491. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  12492. var intersectInfo = null;
  12493. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  12494. var p0 = positions[indices[index]];
  12495. var p1 = positions[indices[index + 1]];
  12496. var p2 = positions[indices[index + 2]];
  12497. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  12498. if (currentIntersectInfo) {
  12499. if (currentIntersectInfo.distance < 0) {
  12500. continue;
  12501. }
  12502. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12503. intersectInfo = currentIntersectInfo;
  12504. intersectInfo.faceId = index / 3;
  12505. if (fastCheck) {
  12506. break;
  12507. }
  12508. }
  12509. }
  12510. }
  12511. return intersectInfo;
  12512. };
  12513. // Clone
  12514. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  12515. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  12516. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  12517. return result;
  12518. };
  12519. // Dispose
  12520. SubMesh.prototype.dispose = function () {
  12521. if (this._linesIndexBuffer) {
  12522. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  12523. this._linesIndexBuffer = null;
  12524. }
  12525. // Remove from mesh
  12526. var index = this._mesh.subMeshes.indexOf(this);
  12527. this._mesh.subMeshes.splice(index, 1);
  12528. };
  12529. // Statics
  12530. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  12531. var minVertexIndex = Number.MAX_VALUE;
  12532. var maxVertexIndex = -Number.MAX_VALUE;
  12533. renderingMesh = renderingMesh || mesh;
  12534. var indices = renderingMesh.getIndices();
  12535. for (var index = startIndex; index < startIndex + indexCount; index++) {
  12536. var vertexIndex = indices[index];
  12537. if (vertexIndex < minVertexIndex)
  12538. minVertexIndex = vertexIndex;
  12539. if (vertexIndex > maxVertexIndex)
  12540. maxVertexIndex = vertexIndex;
  12541. }
  12542. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  12543. };
  12544. return SubMesh;
  12545. })();
  12546. BABYLON.SubMesh = SubMesh;
  12547. })(BABYLON || (BABYLON = {}));
  12548. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  12549. (function (BABYLON) {
  12550. var BaseTexture = (function () {
  12551. function BaseTexture(scene) {
  12552. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  12553. this.hasAlpha = false;
  12554. this.getAlphaFromRGB = false;
  12555. this.level = 1;
  12556. this.isCube = false;
  12557. this.isRenderTarget = false;
  12558. this.animations = new Array();
  12559. this.coordinatesIndex = 0;
  12560. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  12561. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12562. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12563. this.anisotropicFilteringLevel = 4;
  12564. this._scene = scene;
  12565. this._scene.textures.push(this);
  12566. }
  12567. BaseTexture.prototype.getScene = function () {
  12568. return this._scene;
  12569. };
  12570. BaseTexture.prototype.getTextureMatrix = function () {
  12571. return null;
  12572. };
  12573. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  12574. return null;
  12575. };
  12576. BaseTexture.prototype.getInternalTexture = function () {
  12577. return this._texture;
  12578. };
  12579. BaseTexture.prototype.isReady = function () {
  12580. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12581. return true;
  12582. }
  12583. if (this._texture) {
  12584. return this._texture.isReady;
  12585. }
  12586. return false;
  12587. };
  12588. BaseTexture.prototype.getSize = function () {
  12589. if (this._texture._width) {
  12590. return { width: this._texture._width, height: this._texture._height };
  12591. }
  12592. if (this._texture._size) {
  12593. return { width: this._texture._size, height: this._texture._size };
  12594. }
  12595. return { width: 0, height: 0 };
  12596. };
  12597. BaseTexture.prototype.getBaseSize = function () {
  12598. if (!this.isReady())
  12599. return { width: 0, height: 0 };
  12600. if (this._texture._size) {
  12601. return { width: this._texture._size, height: this._texture._size };
  12602. }
  12603. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  12604. };
  12605. BaseTexture.prototype.scale = function (ratio) {
  12606. };
  12607. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  12608. get: function () {
  12609. return false;
  12610. },
  12611. enumerable: true,
  12612. configurable: true
  12613. });
  12614. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  12615. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12616. for (var index = 0; index < texturesCache.length; index++) {
  12617. var texturesCacheEntry = texturesCache[index];
  12618. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  12619. texturesCache.splice(index, 1);
  12620. return;
  12621. }
  12622. }
  12623. };
  12624. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  12625. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12626. for (var index = 0; index < texturesCache.length; index++) {
  12627. var texturesCacheEntry = texturesCache[index];
  12628. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  12629. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  12630. texturesCacheEntry.references++;
  12631. return texturesCacheEntry;
  12632. }
  12633. }
  12634. }
  12635. return null;
  12636. };
  12637. BaseTexture.prototype.delayLoad = function () {
  12638. };
  12639. BaseTexture.prototype.releaseInternalTexture = function () {
  12640. if (!this._texture) {
  12641. return;
  12642. }
  12643. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12644. this._texture.references--;
  12645. // Final reference ?
  12646. if (this._texture.references === 0) {
  12647. var index = texturesCache.indexOf(this._texture);
  12648. texturesCache.splice(index, 1);
  12649. this._scene.getEngine()._releaseTexture(this._texture);
  12650. delete this._texture;
  12651. }
  12652. };
  12653. BaseTexture.prototype.clone = function () {
  12654. return null;
  12655. };
  12656. BaseTexture.prototype.dispose = function () {
  12657. // Remove from scene
  12658. var index = this._scene.textures.indexOf(this);
  12659. if (index >= 0) {
  12660. this._scene.textures.splice(index, 1);
  12661. }
  12662. if (this._texture === undefined) {
  12663. return;
  12664. }
  12665. this.releaseInternalTexture();
  12666. // Callback
  12667. if (this.onDispose) {
  12668. this.onDispose();
  12669. }
  12670. };
  12671. return BaseTexture;
  12672. })();
  12673. BABYLON.BaseTexture = BaseTexture;
  12674. })(BABYLON || (BABYLON = {}));
  12675. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  12676. (function (BABYLON) {
  12677. var RenderingGroup = (function () {
  12678. function RenderingGroup(index, scene) {
  12679. this.index = index;
  12680. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12681. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12682. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12683. this._scene = scene;
  12684. }
  12685. RenderingGroup.prototype.render = function (customRenderFunction) {
  12686. if (customRenderFunction) {
  12687. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12688. return true;
  12689. }
  12690. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12691. return false;
  12692. }
  12693. var engine = this._scene.getEngine();
  12694. // Opaque
  12695. var subIndex;
  12696. var submesh;
  12697. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12698. submesh = this._opaqueSubMeshes.data[subIndex];
  12699. submesh.render();
  12700. }
  12701. // Alpha test
  12702. engine.setAlphaTesting(true);
  12703. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12704. submesh = this._alphaTestSubMeshes.data[subIndex];
  12705. submesh.render();
  12706. }
  12707. engine.setAlphaTesting(false);
  12708. // Transparent
  12709. if (this._transparentSubMeshes.length) {
  12710. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12711. submesh = this._transparentSubMeshes.data[subIndex];
  12712. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12713. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  12714. }
  12715. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12716. sortedArray.sort(function (a, b) {
  12717. // Alpha index first
  12718. if (a._alphaIndex > b._alphaIndex) {
  12719. return 1;
  12720. }
  12721. if (a._alphaIndex < b._alphaIndex) {
  12722. return -1;
  12723. }
  12724. // Then distance to camera
  12725. if (a._distanceToCamera < b._distanceToCamera) {
  12726. return 1;
  12727. }
  12728. if (a._distanceToCamera > b._distanceToCamera) {
  12729. return -1;
  12730. }
  12731. return 0;
  12732. });
  12733. // Rendering
  12734. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12735. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12736. submesh = sortedArray[subIndex];
  12737. submesh.render();
  12738. }
  12739. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12740. }
  12741. return true;
  12742. };
  12743. RenderingGroup.prototype.prepare = function () {
  12744. this._opaqueSubMeshes.reset();
  12745. this._transparentSubMeshes.reset();
  12746. this._alphaTestSubMeshes.reset();
  12747. };
  12748. RenderingGroup.prototype.dispatch = function (subMesh) {
  12749. var material = subMesh.getMaterial();
  12750. var mesh = subMesh.getMesh();
  12751. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12752. this._transparentSubMeshes.push(subMesh);
  12753. }
  12754. else if (material.needAlphaTesting()) {
  12755. this._alphaTestSubMeshes.push(subMesh);
  12756. }
  12757. else {
  12758. this._opaqueSubMeshes.push(subMesh); // Opaque
  12759. }
  12760. };
  12761. return RenderingGroup;
  12762. })();
  12763. BABYLON.RenderingGroup = RenderingGroup;
  12764. })(BABYLON || (BABYLON = {}));
  12765. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  12766. (function (BABYLON) {
  12767. var RenderingManager = (function () {
  12768. function RenderingManager(scene) {
  12769. this._renderingGroups = new Array();
  12770. this._scene = scene;
  12771. }
  12772. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12773. if (this._scene._activeParticleSystems.length === 0) {
  12774. return;
  12775. }
  12776. // Particles
  12777. var beforeParticlesDate = BABYLON.Tools.Now;
  12778. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12779. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12780. if (particleSystem.renderingGroupId !== index) {
  12781. continue;
  12782. }
  12783. this._clearDepthBuffer();
  12784. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12785. this._scene._activeParticles += particleSystem.render();
  12786. }
  12787. }
  12788. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12789. };
  12790. RenderingManager.prototype._renderSprites = function (index) {
  12791. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12792. return;
  12793. }
  12794. // Sprites
  12795. var beforeSpritessDate = BABYLON.Tools.Now;
  12796. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12797. var spriteManager = this._scene.spriteManagers[id];
  12798. if (spriteManager.renderingGroupId === index) {
  12799. this._clearDepthBuffer();
  12800. spriteManager.render();
  12801. }
  12802. }
  12803. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12804. };
  12805. RenderingManager.prototype._clearDepthBuffer = function () {
  12806. if (this._depthBufferAlreadyCleaned) {
  12807. return;
  12808. }
  12809. this._scene.getEngine().clear(0, false, true);
  12810. this._depthBufferAlreadyCleaned = true;
  12811. };
  12812. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12813. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12814. this._depthBufferAlreadyCleaned = false;
  12815. var renderingGroup = this._renderingGroups[index];
  12816. var needToStepBack = false;
  12817. if (renderingGroup) {
  12818. this._clearDepthBuffer();
  12819. if (!renderingGroup.render(customRenderFunction)) {
  12820. this._renderingGroups.splice(index, 1);
  12821. needToStepBack = true;
  12822. }
  12823. }
  12824. if (renderSprites) {
  12825. this._renderSprites(index);
  12826. }
  12827. if (renderParticles) {
  12828. this._renderParticles(index, activeMeshes);
  12829. }
  12830. if (needToStepBack) {
  12831. index--;
  12832. }
  12833. }
  12834. };
  12835. RenderingManager.prototype.reset = function () {
  12836. for (var index in this._renderingGroups) {
  12837. var renderingGroup = this._renderingGroups[index];
  12838. renderingGroup.prepare();
  12839. }
  12840. };
  12841. RenderingManager.prototype.dispatch = function (subMesh) {
  12842. var mesh = subMesh.getMesh();
  12843. var renderingGroupId = mesh.renderingGroupId || 0;
  12844. if (!this._renderingGroups[renderingGroupId]) {
  12845. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12846. }
  12847. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12848. };
  12849. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12850. return RenderingManager;
  12851. })();
  12852. BABYLON.RenderingManager = RenderingManager;
  12853. })(BABYLON || (BABYLON = {}));
  12854. //# sourceMappingURL=babylon.renderingManager.js.map
  12855. var BABYLON;
  12856. (function (BABYLON) {
  12857. var Texture = (function (_super) {
  12858. __extends(Texture, _super);
  12859. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  12860. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12861. if (onLoad === void 0) { onLoad = null; }
  12862. if (onError === void 0) { onError = null; }
  12863. if (buffer === void 0) { buffer = null; }
  12864. if (deleteBuffer === void 0) { deleteBuffer = false; }
  12865. _super.call(this, scene);
  12866. this.uOffset = 0;
  12867. this.vOffset = 0;
  12868. this.uScale = 1.0;
  12869. this.vScale = 1.0;
  12870. this.uAng = 0;
  12871. this.vAng = 0;
  12872. this.wAng = 0;
  12873. this.name = url;
  12874. this.url = url;
  12875. this._noMipmap = noMipmap;
  12876. this._invertY = invertY;
  12877. this._samplingMode = samplingMode;
  12878. this._buffer = buffer;
  12879. this._deleteBuffer = deleteBuffer;
  12880. if (!url) {
  12881. return;
  12882. }
  12883. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  12884. if (!this._texture) {
  12885. if (!scene.useDelayedTextureLoading) {
  12886. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  12887. if (deleteBuffer) {
  12888. delete this._buffer;
  12889. }
  12890. }
  12891. else {
  12892. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12893. }
  12894. }
  12895. }
  12896. Texture.prototype.delayLoad = function () {
  12897. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12898. return;
  12899. }
  12900. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  12901. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  12902. if (!this._texture) {
  12903. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  12904. if (this._deleteBuffer) {
  12905. delete this._buffer;
  12906. }
  12907. }
  12908. };
  12909. Texture.prototype.updateSamplingMode = function (samplingMode) {
  12910. if (!this._texture) {
  12911. return;
  12912. }
  12913. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  12914. };
  12915. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  12916. x -= this.uOffset + 0.5;
  12917. y -= this.vOffset + 0.5;
  12918. z -= 0.5;
  12919. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  12920. t.x *= this.uScale;
  12921. t.y *= this.vScale;
  12922. t.x += 0.5;
  12923. t.y += 0.5;
  12924. t.z += 0.5;
  12925. };
  12926. Texture.prototype.getTextureMatrix = function () {
  12927. 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) {
  12928. return this._cachedTextureMatrix;
  12929. }
  12930. this._cachedUOffset = this.uOffset;
  12931. this._cachedVOffset = this.vOffset;
  12932. this._cachedUScale = this.uScale;
  12933. this._cachedVScale = this.vScale;
  12934. this._cachedUAng = this.uAng;
  12935. this._cachedVAng = this.vAng;
  12936. this._cachedWAng = this.wAng;
  12937. if (!this._cachedTextureMatrix) {
  12938. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  12939. this._rowGenerationMatrix = new BABYLON.Matrix();
  12940. this._t0 = BABYLON.Vector3.Zero();
  12941. this._t1 = BABYLON.Vector3.Zero();
  12942. this._t2 = BABYLON.Vector3.Zero();
  12943. }
  12944. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  12945. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  12946. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  12947. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  12948. this._t1.subtractInPlace(this._t0);
  12949. this._t2.subtractInPlace(this._t0);
  12950. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12951. this._cachedTextureMatrix.m[0] = this._t1.x;
  12952. this._cachedTextureMatrix.m[1] = this._t1.y;
  12953. this._cachedTextureMatrix.m[2] = this._t1.z;
  12954. this._cachedTextureMatrix.m[4] = this._t2.x;
  12955. this._cachedTextureMatrix.m[5] = this._t2.y;
  12956. this._cachedTextureMatrix.m[6] = this._t2.z;
  12957. this._cachedTextureMatrix.m[8] = this._t0.x;
  12958. this._cachedTextureMatrix.m[9] = this._t0.y;
  12959. this._cachedTextureMatrix.m[10] = this._t0.z;
  12960. return this._cachedTextureMatrix;
  12961. };
  12962. Texture.prototype.getReflectionTextureMatrix = function () {
  12963. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  12964. return this._cachedTextureMatrix;
  12965. }
  12966. if (!this._cachedTextureMatrix) {
  12967. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  12968. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  12969. }
  12970. this._cachedCoordinatesMode = this.coordinatesMode;
  12971. switch (this.coordinatesMode) {
  12972. case Texture.SPHERICAL_MODE:
  12973. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12974. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  12975. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  12976. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  12977. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  12978. break;
  12979. case Texture.PLANAR_MODE:
  12980. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12981. this._cachedTextureMatrix[0] = this.uScale;
  12982. this._cachedTextureMatrix[5] = this.vScale;
  12983. this._cachedTextureMatrix[12] = this.uOffset;
  12984. this._cachedTextureMatrix[13] = this.vOffset;
  12985. break;
  12986. case Texture.PROJECTION_MODE:
  12987. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  12988. this._projectionModeMatrix.m[0] = 0.5;
  12989. this._projectionModeMatrix.m[5] = -0.5;
  12990. this._projectionModeMatrix.m[10] = 0.0;
  12991. this._projectionModeMatrix.m[12] = 0.5;
  12992. this._projectionModeMatrix.m[13] = 0.5;
  12993. this._projectionModeMatrix.m[14] = 1.0;
  12994. this._projectionModeMatrix.m[15] = 1.0;
  12995. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  12996. break;
  12997. default:
  12998. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12999. break;
  13000. }
  13001. return this._cachedTextureMatrix;
  13002. };
  13003. Texture.prototype.clone = function () {
  13004. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  13005. // Base texture
  13006. newTexture.hasAlpha = this.hasAlpha;
  13007. newTexture.level = this.level;
  13008. newTexture.wrapU = this.wrapU;
  13009. newTexture.wrapV = this.wrapV;
  13010. newTexture.coordinatesIndex = this.coordinatesIndex;
  13011. newTexture.coordinatesMode = this.coordinatesMode;
  13012. // Texture
  13013. newTexture.uOffset = this.uOffset;
  13014. newTexture.vOffset = this.vOffset;
  13015. newTexture.uScale = this.uScale;
  13016. newTexture.vScale = this.vScale;
  13017. newTexture.uAng = this.uAng;
  13018. newTexture.vAng = this.vAng;
  13019. newTexture.wAng = this.wAng;
  13020. return newTexture;
  13021. };
  13022. // Statics
  13023. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  13024. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  13025. if (onLoad === void 0) { onLoad = null; }
  13026. if (onError === void 0) { onError = null; }
  13027. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  13028. };
  13029. // Constants
  13030. Texture.NEAREST_SAMPLINGMODE = 1;
  13031. Texture.BILINEAR_SAMPLINGMODE = 2;
  13032. Texture.TRILINEAR_SAMPLINGMODE = 3;
  13033. Texture.EXPLICIT_MODE = 0;
  13034. Texture.SPHERICAL_MODE = 1;
  13035. Texture.PLANAR_MODE = 2;
  13036. Texture.CUBIC_MODE = 3;
  13037. Texture.PROJECTION_MODE = 4;
  13038. Texture.SKYBOX_MODE = 5;
  13039. Texture.CLAMP_ADDRESSMODE = 0;
  13040. Texture.WRAP_ADDRESSMODE = 1;
  13041. Texture.MIRROR_ADDRESSMODE = 2;
  13042. return Texture;
  13043. })(BABYLON.BaseTexture);
  13044. BABYLON.Texture = Texture;
  13045. })(BABYLON || (BABYLON = {}));
  13046. //# sourceMappingURL=babylon.texture.js.map
  13047. var BABYLON;
  13048. (function (BABYLON) {
  13049. var CubeTexture = (function (_super) {
  13050. __extends(CubeTexture, _super);
  13051. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  13052. _super.call(this, scene);
  13053. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  13054. this.name = rootUrl;
  13055. this.url = rootUrl;
  13056. this._noMipmap = noMipmap;
  13057. this.hasAlpha = false;
  13058. this._texture = this._getFromCache(rootUrl, noMipmap);
  13059. if (!extensions) {
  13060. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  13061. }
  13062. this._extensions = extensions;
  13063. if (!this._texture) {
  13064. if (!scene.useDelayedTextureLoading) {
  13065. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  13066. }
  13067. else {
  13068. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  13069. }
  13070. }
  13071. this.isCube = true;
  13072. this._textureMatrix = BABYLON.Matrix.Identity();
  13073. }
  13074. CubeTexture.prototype.clone = function () {
  13075. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  13076. // Base texture
  13077. newTexture.level = this.level;
  13078. newTexture.wrapU = this.wrapU;
  13079. newTexture.wrapV = this.wrapV;
  13080. newTexture.coordinatesIndex = this.coordinatesIndex;
  13081. newTexture.coordinatesMode = this.coordinatesMode;
  13082. return newTexture;
  13083. };
  13084. // Methods
  13085. CubeTexture.prototype.delayLoad = function () {
  13086. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  13087. return;
  13088. }
  13089. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  13090. this._texture = this._getFromCache(this.url, this._noMipmap);
  13091. if (!this._texture) {
  13092. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  13093. }
  13094. };
  13095. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  13096. return this._textureMatrix;
  13097. };
  13098. return CubeTexture;
  13099. })(BABYLON.BaseTexture);
  13100. BABYLON.CubeTexture = CubeTexture;
  13101. })(BABYLON || (BABYLON = {}));
  13102. //# sourceMappingURL=babylon.cubeTexture.js.map
  13103. var BABYLON;
  13104. (function (BABYLON) {
  13105. var RenderTargetTexture = (function (_super) {
  13106. __extends(RenderTargetTexture, _super);
  13107. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  13108. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  13109. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  13110. _super.call(this, null, scene, !generateMipMaps);
  13111. this.renderList = new Array();
  13112. this.renderParticles = true;
  13113. this.renderSprites = false;
  13114. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  13115. this._currentRefreshId = -1;
  13116. this._refreshRate = 1;
  13117. this.name = name;
  13118. this.isRenderTarget = true;
  13119. this._size = size;
  13120. this._generateMipMaps = generateMipMaps;
  13121. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  13122. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  13123. // Rendering groups
  13124. this._renderingManager = new BABYLON.RenderingManager(scene);
  13125. }
  13126. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  13127. this._currentRefreshId = -1;
  13128. };
  13129. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  13130. get: function () {
  13131. return this._refreshRate;
  13132. },
  13133. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  13134. set: function (value) {
  13135. this._refreshRate = value;
  13136. this.resetRefreshCounter();
  13137. },
  13138. enumerable: true,
  13139. configurable: true
  13140. });
  13141. RenderTargetTexture.prototype._shouldRender = function () {
  13142. if (this._currentRefreshId === -1) {
  13143. this._currentRefreshId = 1;
  13144. return true;
  13145. }
  13146. if (this.refreshRate === this._currentRefreshId) {
  13147. this._currentRefreshId = 1;
  13148. return true;
  13149. }
  13150. this._currentRefreshId++;
  13151. return false;
  13152. };
  13153. RenderTargetTexture.prototype.isReady = function () {
  13154. if (!this.getScene().renderTargetsEnabled) {
  13155. return false;
  13156. }
  13157. return _super.prototype.isReady.call(this);
  13158. };
  13159. RenderTargetTexture.prototype.getRenderSize = function () {
  13160. return this._size;
  13161. };
  13162. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  13163. get: function () {
  13164. return true;
  13165. },
  13166. enumerable: true,
  13167. configurable: true
  13168. });
  13169. RenderTargetTexture.prototype.scale = function (ratio) {
  13170. var newSize = this._size * ratio;
  13171. this.resize(newSize, this._generateMipMaps);
  13172. };
  13173. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  13174. this.releaseInternalTexture();
  13175. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  13176. };
  13177. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  13178. var scene = this.getScene();
  13179. var engine = scene.getEngine();
  13180. if (this._waitingRenderList) {
  13181. this.renderList = [];
  13182. for (var index = 0; index < this._waitingRenderList.length; index++) {
  13183. var id = this._waitingRenderList[index];
  13184. this.renderList.push(scene.getMeshByID(id));
  13185. }
  13186. delete this._waitingRenderList;
  13187. }
  13188. if (this.renderList && this.renderList.length === 0) {
  13189. return;
  13190. }
  13191. // Bind
  13192. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  13193. engine.bindFramebuffer(this._texture);
  13194. }
  13195. this._renderingManager.reset();
  13196. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  13197. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  13198. var mesh = currentRenderList[meshIndex];
  13199. if (mesh) {
  13200. if (!mesh.isReady()) {
  13201. // Reset _currentRefreshId
  13202. this.resetRefreshCounter();
  13203. continue;
  13204. }
  13205. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  13206. mesh._activate(scene.getRenderId());
  13207. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  13208. var subMesh = mesh.subMeshes[subIndex];
  13209. scene._activeVertices += subMesh.indexCount;
  13210. this._renderingManager.dispatch(subMesh);
  13211. }
  13212. }
  13213. }
  13214. }
  13215. if (this.onBeforeRender) {
  13216. this.onBeforeRender();
  13217. }
  13218. // Clear
  13219. if (this.onClear) {
  13220. this.onClear(engine);
  13221. }
  13222. else {
  13223. engine.clear(scene.clearColor, true, true);
  13224. }
  13225. if (!this._doNotChangeAspectRatio) {
  13226. scene.updateTransformMatrix(true);
  13227. }
  13228. // Render
  13229. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  13230. if (useCameraPostProcess) {
  13231. scene.postProcessManager._finalizeFrame(false, this._texture);
  13232. }
  13233. if (!this._doNotChangeAspectRatio) {
  13234. scene.updateTransformMatrix(true);
  13235. }
  13236. if (this.onAfterRender) {
  13237. this.onAfterRender();
  13238. }
  13239. // Dump ?
  13240. if (dumpForDebug) {
  13241. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  13242. }
  13243. // Unbind
  13244. engine.unBindFramebuffer(this._texture);
  13245. if (this.onAfterUnbind) {
  13246. this.onAfterUnbind();
  13247. }
  13248. };
  13249. RenderTargetTexture.prototype.clone = function () {
  13250. var textureSize = this.getSize();
  13251. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13252. // Base texture
  13253. newTexture.hasAlpha = this.hasAlpha;
  13254. newTexture.level = this.level;
  13255. // RenderTarget Texture
  13256. newTexture.coordinatesMode = this.coordinatesMode;
  13257. newTexture.renderList = this.renderList.slice(0);
  13258. return newTexture;
  13259. };
  13260. return RenderTargetTexture;
  13261. })(BABYLON.Texture);
  13262. BABYLON.RenderTargetTexture = RenderTargetTexture;
  13263. })(BABYLON || (BABYLON = {}));
  13264. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  13265. var BABYLON;
  13266. (function (BABYLON) {
  13267. var ProceduralTexture = (function (_super) {
  13268. __extends(ProceduralTexture, _super);
  13269. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  13270. if (generateMipMaps === void 0) { generateMipMaps = true; }
  13271. _super.call(this, null, scene, !generateMipMaps);
  13272. this._currentRefreshId = -1;
  13273. this._refreshRate = 1;
  13274. this._vertexDeclaration = [2];
  13275. this._vertexStrideSize = 2 * 4;
  13276. this._uniforms = new Array();
  13277. this._samplers = new Array();
  13278. this._textures = new Array();
  13279. this._floats = new Array();
  13280. this._floatsArrays = {};
  13281. this._colors3 = new Array();
  13282. this._colors4 = new Array();
  13283. this._vectors2 = new Array();
  13284. this._vectors3 = new Array();
  13285. this._matrices = new Array();
  13286. this._fallbackTextureUsed = false;
  13287. scene._proceduralTextures.push(this);
  13288. this.name = name;
  13289. this.isRenderTarget = true;
  13290. this._size = size;
  13291. this._generateMipMaps = generateMipMaps;
  13292. this.setFragment(fragment);
  13293. this._fallbackTexture = fallbackTexture;
  13294. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  13295. // VBO
  13296. var vertices = [];
  13297. vertices.push(1, 1);
  13298. vertices.push(-1, 1);
  13299. vertices.push(-1, -1);
  13300. vertices.push(1, -1);
  13301. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  13302. // Indices
  13303. var indices = [];
  13304. indices.push(0);
  13305. indices.push(1);
  13306. indices.push(2);
  13307. indices.push(0);
  13308. indices.push(2);
  13309. indices.push(3);
  13310. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13311. }
  13312. ProceduralTexture.prototype.reset = function () {
  13313. if (this._effect === undefined) {
  13314. return;
  13315. }
  13316. var engine = this.getScene().getEngine();
  13317. engine._releaseEffect(this._effect);
  13318. };
  13319. ProceduralTexture.prototype.isReady = function () {
  13320. var _this = this;
  13321. var engine = this.getScene().getEngine();
  13322. var shaders;
  13323. if (!this._fragment) {
  13324. return false;
  13325. }
  13326. if (this._fallbackTextureUsed) {
  13327. return true;
  13328. }
  13329. if (this._fragment.fragmentElement !== undefined) {
  13330. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  13331. }
  13332. else {
  13333. shaders = { vertex: "procedural", fragment: this._fragment };
  13334. }
  13335. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  13336. _this.releaseInternalTexture();
  13337. if (_this._fallbackTexture) {
  13338. _this._texture = _this._fallbackTexture._texture;
  13339. _this._texture.references++;
  13340. }
  13341. _this._fallbackTextureUsed = true;
  13342. });
  13343. return this._effect.isReady();
  13344. };
  13345. ProceduralTexture.prototype.resetRefreshCounter = function () {
  13346. this._currentRefreshId = -1;
  13347. };
  13348. ProceduralTexture.prototype.setFragment = function (fragment) {
  13349. this._fragment = fragment;
  13350. };
  13351. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  13352. get: function () {
  13353. return this._refreshRate;
  13354. },
  13355. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  13356. set: function (value) {
  13357. this._refreshRate = value;
  13358. this.resetRefreshCounter();
  13359. },
  13360. enumerable: true,
  13361. configurable: true
  13362. });
  13363. ProceduralTexture.prototype._shouldRender = function () {
  13364. if (!this.isReady() || !this._texture) {
  13365. return false;
  13366. }
  13367. if (this._fallbackTextureUsed) {
  13368. return false;
  13369. }
  13370. if (this._currentRefreshId === -1) {
  13371. this._currentRefreshId = 1;
  13372. return true;
  13373. }
  13374. if (this.refreshRate === this._currentRefreshId) {
  13375. this._currentRefreshId = 1;
  13376. return true;
  13377. }
  13378. this._currentRefreshId++;
  13379. return false;
  13380. };
  13381. ProceduralTexture.prototype.getRenderSize = function () {
  13382. return this._size;
  13383. };
  13384. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  13385. if (this._fallbackTextureUsed) {
  13386. return;
  13387. }
  13388. this.releaseInternalTexture();
  13389. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  13390. };
  13391. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  13392. if (this._uniforms.indexOf(uniformName) === -1) {
  13393. this._uniforms.push(uniformName);
  13394. }
  13395. };
  13396. ProceduralTexture.prototype.setTexture = function (name, texture) {
  13397. if (this._samplers.indexOf(name) === -1) {
  13398. this._samplers.push(name);
  13399. }
  13400. this._textures[name] = texture;
  13401. return this;
  13402. };
  13403. ProceduralTexture.prototype.setFloat = function (name, value) {
  13404. this._checkUniform(name);
  13405. this._floats[name] = value;
  13406. return this;
  13407. };
  13408. ProceduralTexture.prototype.setFloats = function (name, value) {
  13409. this._checkUniform(name);
  13410. this._floatsArrays[name] = value;
  13411. return this;
  13412. };
  13413. ProceduralTexture.prototype.setColor3 = function (name, value) {
  13414. this._checkUniform(name);
  13415. this._colors3[name] = value;
  13416. return this;
  13417. };
  13418. ProceduralTexture.prototype.setColor4 = function (name, value) {
  13419. this._checkUniform(name);
  13420. this._colors4[name] = value;
  13421. return this;
  13422. };
  13423. ProceduralTexture.prototype.setVector2 = function (name, value) {
  13424. this._checkUniform(name);
  13425. this._vectors2[name] = value;
  13426. return this;
  13427. };
  13428. ProceduralTexture.prototype.setVector3 = function (name, value) {
  13429. this._checkUniform(name);
  13430. this._vectors3[name] = value;
  13431. return this;
  13432. };
  13433. ProceduralTexture.prototype.setMatrix = function (name, value) {
  13434. this._checkUniform(name);
  13435. this._matrices[name] = value;
  13436. return this;
  13437. };
  13438. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13439. var scene = this.getScene();
  13440. var engine = scene.getEngine();
  13441. engine.bindFramebuffer(this._texture);
  13442. // Clear
  13443. engine.clear(scene.clearColor, true, true);
  13444. // Render
  13445. engine.enableEffect(this._effect);
  13446. engine.setState(false);
  13447. for (var name in this._textures) {
  13448. this._effect.setTexture(name, this._textures[name]);
  13449. }
  13450. for (name in this._floats) {
  13451. this._effect.setFloat(name, this._floats[name]);
  13452. }
  13453. for (name in this._floatsArrays) {
  13454. this._effect.setArray(name, this._floatsArrays[name]);
  13455. }
  13456. for (name in this._colors3) {
  13457. this._effect.setColor3(name, this._colors3[name]);
  13458. }
  13459. for (name in this._colors4) {
  13460. var color = this._colors4[name];
  13461. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  13462. }
  13463. for (name in this._vectors2) {
  13464. this._effect.setVector2(name, this._vectors2[name]);
  13465. }
  13466. for (name in this._vectors3) {
  13467. this._effect.setVector3(name, this._vectors3[name]);
  13468. }
  13469. for (name in this._matrices) {
  13470. this._effect.setMatrix(name, this._matrices[name]);
  13471. }
  13472. // VBOs
  13473. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  13474. // Draw order
  13475. engine.draw(true, 0, 6);
  13476. // Unbind
  13477. engine.unBindFramebuffer(this._texture);
  13478. };
  13479. ProceduralTexture.prototype.clone = function () {
  13480. var textureSize = this.getSize();
  13481. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  13482. // Base texture
  13483. newTexture.hasAlpha = this.hasAlpha;
  13484. newTexture.level = this.level;
  13485. // RenderTarget Texture
  13486. newTexture.coordinatesMode = this.coordinatesMode;
  13487. return newTexture;
  13488. };
  13489. ProceduralTexture.prototype.dispose = function () {
  13490. var index = this.getScene()._proceduralTextures.indexOf(this);
  13491. if (index >= 0) {
  13492. this.getScene()._proceduralTextures.splice(index, 1);
  13493. }
  13494. _super.prototype.dispose.call(this);
  13495. };
  13496. return ProceduralTexture;
  13497. })(BABYLON.Texture);
  13498. BABYLON.ProceduralTexture = ProceduralTexture;
  13499. })(BABYLON || (BABYLON = {}));
  13500. //# sourceMappingURL=babylon.proceduralTexture.js.map
  13501. var BABYLON;
  13502. (function (BABYLON) {
  13503. var WoodProceduralTexture = (function (_super) {
  13504. __extends(WoodProceduralTexture, _super);
  13505. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13506. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  13507. this._ampScale = 100.0;
  13508. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  13509. this.updateShaderUniforms();
  13510. this.refreshRate = 0;
  13511. }
  13512. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  13513. this.setFloat("ampScale", this._ampScale);
  13514. this.setColor3("woodColor", this._woodColor);
  13515. };
  13516. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  13517. get: function () {
  13518. return this._ampScale;
  13519. },
  13520. set: function (value) {
  13521. this._ampScale = value;
  13522. this.updateShaderUniforms();
  13523. },
  13524. enumerable: true,
  13525. configurable: true
  13526. });
  13527. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  13528. get: function () {
  13529. return this._woodColor;
  13530. },
  13531. set: function (value) {
  13532. this._woodColor = value;
  13533. this.updateShaderUniforms();
  13534. },
  13535. enumerable: true,
  13536. configurable: true
  13537. });
  13538. return WoodProceduralTexture;
  13539. })(BABYLON.ProceduralTexture);
  13540. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  13541. var FireProceduralTexture = (function (_super) {
  13542. __extends(FireProceduralTexture, _super);
  13543. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13544. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  13545. this._time = 0.0;
  13546. this._speed = new BABYLON.Vector2(0.5, 0.3);
  13547. this._autoGenerateTime = true;
  13548. this._alphaThreshold = 0.5;
  13549. this._fireColors = FireProceduralTexture.RedFireColors;
  13550. this.updateShaderUniforms();
  13551. this.refreshRate = 1;
  13552. }
  13553. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  13554. this.setFloat("time", this._time);
  13555. this.setVector2("speed", this._speed);
  13556. this.setColor3("c1", this._fireColors[0]);
  13557. this.setColor3("c2", this._fireColors[1]);
  13558. this.setColor3("c3", this._fireColors[2]);
  13559. this.setColor3("c4", this._fireColors[3]);
  13560. this.setColor3("c5", this._fireColors[4]);
  13561. this.setColor3("c6", this._fireColors[5]);
  13562. this.setFloat("alphaThreshold", this._alphaThreshold);
  13563. };
  13564. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13565. if (this._autoGenerateTime) {
  13566. this._time += this.getScene().getAnimationRatio() * 0.03;
  13567. this.updateShaderUniforms();
  13568. }
  13569. _super.prototype.render.call(this, useCameraPostProcess);
  13570. };
  13571. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  13572. get: function () {
  13573. return [
  13574. new BABYLON.Color3(0.5, 0.0, 1.0),
  13575. new BABYLON.Color3(0.9, 0.0, 1.0),
  13576. new BABYLON.Color3(0.2, 0.0, 1.0),
  13577. new BABYLON.Color3(1.0, 0.9, 1.0),
  13578. new BABYLON.Color3(0.1, 0.1, 1.0),
  13579. new BABYLON.Color3(0.9, 0.9, 1.0)
  13580. ];
  13581. },
  13582. enumerable: true,
  13583. configurable: true
  13584. });
  13585. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  13586. get: function () {
  13587. return [
  13588. new BABYLON.Color3(0.5, 1.0, 0.0),
  13589. new BABYLON.Color3(0.5, 1.0, 0.0),
  13590. new BABYLON.Color3(0.3, 0.4, 0.0),
  13591. new BABYLON.Color3(0.5, 1.0, 0.0),
  13592. new BABYLON.Color3(0.2, 0.0, 0.0),
  13593. new BABYLON.Color3(0.5, 1.0, 0.0)
  13594. ];
  13595. },
  13596. enumerable: true,
  13597. configurable: true
  13598. });
  13599. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  13600. get: function () {
  13601. return [
  13602. new BABYLON.Color3(0.5, 0.0, 0.1),
  13603. new BABYLON.Color3(0.9, 0.0, 0.0),
  13604. new BABYLON.Color3(0.2, 0.0, 0.0),
  13605. new BABYLON.Color3(1.0, 0.9, 0.0),
  13606. new BABYLON.Color3(0.1, 0.1, 0.1),
  13607. new BABYLON.Color3(0.9, 0.9, 0.9)
  13608. ];
  13609. },
  13610. enumerable: true,
  13611. configurable: true
  13612. });
  13613. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  13614. get: function () {
  13615. return [
  13616. new BABYLON.Color3(0.1, 0.0, 0.5),
  13617. new BABYLON.Color3(0.0, 0.0, 0.5),
  13618. new BABYLON.Color3(0.1, 0.0, 0.2),
  13619. new BABYLON.Color3(0.0, 0.0, 1.0),
  13620. new BABYLON.Color3(0.1, 0.2, 0.3),
  13621. new BABYLON.Color3(0.0, 0.2, 0.9)
  13622. ];
  13623. },
  13624. enumerable: true,
  13625. configurable: true
  13626. });
  13627. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  13628. get: function () {
  13629. return this._fireColors;
  13630. },
  13631. set: function (value) {
  13632. this._fireColors = value;
  13633. this.updateShaderUniforms();
  13634. },
  13635. enumerable: true,
  13636. configurable: true
  13637. });
  13638. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  13639. get: function () {
  13640. return this._time;
  13641. },
  13642. set: function (value) {
  13643. this._time = value;
  13644. this.updateShaderUniforms();
  13645. },
  13646. enumerable: true,
  13647. configurable: true
  13648. });
  13649. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  13650. get: function () {
  13651. return this._speed;
  13652. },
  13653. set: function (value) {
  13654. this._speed = value;
  13655. this.updateShaderUniforms();
  13656. },
  13657. enumerable: true,
  13658. configurable: true
  13659. });
  13660. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  13661. get: function () {
  13662. return this._alphaThreshold;
  13663. },
  13664. set: function (value) {
  13665. this._alphaThreshold = value;
  13666. this.updateShaderUniforms();
  13667. },
  13668. enumerable: true,
  13669. configurable: true
  13670. });
  13671. return FireProceduralTexture;
  13672. })(BABYLON.ProceduralTexture);
  13673. BABYLON.FireProceduralTexture = FireProceduralTexture;
  13674. var CloudProceduralTexture = (function (_super) {
  13675. __extends(CloudProceduralTexture, _super);
  13676. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13677. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  13678. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  13679. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  13680. this.updateShaderUniforms();
  13681. this.refreshRate = 0;
  13682. }
  13683. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  13684. this.setColor3("skyColor", this._skyColor);
  13685. this.setColor3("cloudColor", this._cloudColor);
  13686. };
  13687. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  13688. get: function () {
  13689. return this._skyColor;
  13690. },
  13691. set: function (value) {
  13692. this._skyColor = value;
  13693. this.updateShaderUniforms();
  13694. },
  13695. enumerable: true,
  13696. configurable: true
  13697. });
  13698. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  13699. get: function () {
  13700. return this._cloudColor;
  13701. },
  13702. set: function (value) {
  13703. this._cloudColor = value;
  13704. this.updateShaderUniforms();
  13705. },
  13706. enumerable: true,
  13707. configurable: true
  13708. });
  13709. return CloudProceduralTexture;
  13710. })(BABYLON.ProceduralTexture);
  13711. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  13712. var GrassProceduralTexture = (function (_super) {
  13713. __extends(GrassProceduralTexture, _super);
  13714. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13715. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  13716. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  13717. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  13718. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  13719. this._groundColor = new BABYLON.Color3(1, 1, 1);
  13720. this._grassColors = [
  13721. new BABYLON.Color3(0.29, 0.38, 0.02),
  13722. new BABYLON.Color3(0.36, 0.49, 0.09),
  13723. new BABYLON.Color3(0.51, 0.6, 0.28)
  13724. ];
  13725. this.updateShaderUniforms();
  13726. this.refreshRate = 0;
  13727. }
  13728. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  13729. this.setColor3("herb1Color", this._grassColors[0]);
  13730. this.setColor3("herb2Color", this._grassColors[1]);
  13731. this.setColor3("herb3Color", this._grassColors[2]);
  13732. this.setColor3("groundColor", this._groundColor);
  13733. };
  13734. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  13735. get: function () {
  13736. return this._grassColors;
  13737. },
  13738. set: function (value) {
  13739. this._grassColors = value;
  13740. this.updateShaderUniforms();
  13741. },
  13742. enumerable: true,
  13743. configurable: true
  13744. });
  13745. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  13746. get: function () {
  13747. return this._groundColor;
  13748. },
  13749. set: function (value) {
  13750. this.groundColor = value;
  13751. this.updateShaderUniforms();
  13752. },
  13753. enumerable: true,
  13754. configurable: true
  13755. });
  13756. return GrassProceduralTexture;
  13757. })(BABYLON.ProceduralTexture);
  13758. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  13759. var RoadProceduralTexture = (function (_super) {
  13760. __extends(RoadProceduralTexture, _super);
  13761. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13762. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  13763. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  13764. this.updateShaderUniforms();
  13765. this.refreshRate = 0;
  13766. }
  13767. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  13768. this.setColor3("roadColor", this._roadColor);
  13769. };
  13770. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  13771. get: function () {
  13772. return this._roadColor;
  13773. },
  13774. set: function (value) {
  13775. this._roadColor = value;
  13776. this.updateShaderUniforms();
  13777. },
  13778. enumerable: true,
  13779. configurable: true
  13780. });
  13781. return RoadProceduralTexture;
  13782. })(BABYLON.ProceduralTexture);
  13783. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  13784. var BrickProceduralTexture = (function (_super) {
  13785. __extends(BrickProceduralTexture, _super);
  13786. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13787. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  13788. this._numberOfBricksHeight = 15;
  13789. this._numberOfBricksWidth = 5;
  13790. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13791. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13792. this.updateShaderUniforms();
  13793. this.refreshRate = 0;
  13794. }
  13795. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  13796. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  13797. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  13798. this.setColor3("brickColor", this._brickColor);
  13799. this.setColor3("jointColor", this._jointColor);
  13800. };
  13801. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  13802. get: function () {
  13803. return this._numberOfBricksHeight;
  13804. },
  13805. set: function (value) {
  13806. this._numberOfBricksHeight = value;
  13807. this.updateShaderUniforms();
  13808. },
  13809. enumerable: true,
  13810. configurable: true
  13811. });
  13812. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  13813. get: function () {
  13814. return this._numberOfBricksWidth;
  13815. },
  13816. set: function (value) {
  13817. this._numberOfBricksHeight = value;
  13818. this.updateShaderUniforms();
  13819. },
  13820. enumerable: true,
  13821. configurable: true
  13822. });
  13823. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  13824. get: function () {
  13825. return this._jointColor;
  13826. },
  13827. set: function (value) {
  13828. this._jointColor = value;
  13829. this.updateShaderUniforms();
  13830. },
  13831. enumerable: true,
  13832. configurable: true
  13833. });
  13834. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  13835. get: function () {
  13836. return this._brickColor;
  13837. },
  13838. set: function (value) {
  13839. this._brickColor = value;
  13840. this.updateShaderUniforms();
  13841. },
  13842. enumerable: true,
  13843. configurable: true
  13844. });
  13845. return BrickProceduralTexture;
  13846. })(BABYLON.ProceduralTexture);
  13847. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  13848. var MarbleProceduralTexture = (function (_super) {
  13849. __extends(MarbleProceduralTexture, _super);
  13850. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13851. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  13852. this._numberOfTilesHeight = 3;
  13853. this._numberOfTilesWidth = 3;
  13854. this._amplitude = 9.0;
  13855. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13856. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13857. this.updateShaderUniforms();
  13858. this.refreshRate = 0;
  13859. }
  13860. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  13861. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  13862. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  13863. this.setFloat("amplitude", this._amplitude);
  13864. this.setColor3("marbleColor", this._marbleColor);
  13865. this.setColor3("jointColor", this._jointColor);
  13866. };
  13867. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  13868. get: function () {
  13869. return this._numberOfTilesHeight;
  13870. },
  13871. set: function (value) {
  13872. this._numberOfTilesHeight = value;
  13873. this.updateShaderUniforms();
  13874. },
  13875. enumerable: true,
  13876. configurable: true
  13877. });
  13878. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  13879. get: function () {
  13880. return this._numberOfTilesWidth;
  13881. },
  13882. set: function (value) {
  13883. this._numberOfTilesWidth = value;
  13884. this.updateShaderUniforms();
  13885. },
  13886. enumerable: true,
  13887. configurable: true
  13888. });
  13889. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  13890. get: function () {
  13891. return this._jointColor;
  13892. },
  13893. set: function (value) {
  13894. this._jointColor = value;
  13895. this.updateShaderUniforms();
  13896. },
  13897. enumerable: true,
  13898. configurable: true
  13899. });
  13900. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  13901. get: function () {
  13902. return this._marbleColor;
  13903. },
  13904. set: function (value) {
  13905. this._marbleColor = value;
  13906. this.updateShaderUniforms();
  13907. },
  13908. enumerable: true,
  13909. configurable: true
  13910. });
  13911. return MarbleProceduralTexture;
  13912. })(BABYLON.ProceduralTexture);
  13913. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  13914. })(BABYLON || (BABYLON = {}));
  13915. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  13916. var BABYLON;
  13917. (function (BABYLON) {
  13918. var CustomProceduralTexture = (function (_super) {
  13919. __extends(CustomProceduralTexture, _super);
  13920. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  13921. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  13922. this._animate = true;
  13923. this._time = 0;
  13924. this._texturePath = texturePath;
  13925. //Try to load json
  13926. this.loadJson(texturePath);
  13927. this.refreshRate = 1;
  13928. }
  13929. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  13930. var _this = this;
  13931. var that = this;
  13932. function noConfigFile() {
  13933. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  13934. try {
  13935. that.setFragment(that._texturePath);
  13936. }
  13937. catch (ex) {
  13938. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  13939. }
  13940. }
  13941. var configFileUrl = jsonUrl + "/config.json";
  13942. var xhr = new XMLHttpRequest();
  13943. xhr.open("GET", configFileUrl, true);
  13944. xhr.addEventListener("load", function () {
  13945. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13946. try {
  13947. _this._config = JSON.parse(xhr.response);
  13948. _this.updateShaderUniforms();
  13949. _this.updateTextures();
  13950. _this.setFragment(_this._texturePath + "/custom");
  13951. _this._animate = _this._config.animate;
  13952. _this.refreshRate = _this._config.refreshrate;
  13953. }
  13954. catch (ex) {
  13955. noConfigFile();
  13956. }
  13957. }
  13958. else {
  13959. noConfigFile();
  13960. }
  13961. }, false);
  13962. xhr.addEventListener("error", function () {
  13963. noConfigFile();
  13964. }, false);
  13965. try {
  13966. xhr.send();
  13967. }
  13968. catch (ex) {
  13969. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  13970. }
  13971. };
  13972. CustomProceduralTexture.prototype.isReady = function () {
  13973. if (!_super.prototype.isReady.call(this)) {
  13974. return false;
  13975. }
  13976. for (var name in this._textures) {
  13977. var texture = this._textures[name];
  13978. if (!texture.isReady()) {
  13979. return false;
  13980. }
  13981. }
  13982. return true;
  13983. };
  13984. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13985. if (this._animate) {
  13986. this._time += this.getScene().getAnimationRatio() * 0.03;
  13987. this.updateShaderUniforms();
  13988. }
  13989. _super.prototype.render.call(this, useCameraPostProcess);
  13990. };
  13991. CustomProceduralTexture.prototype.updateTextures = function () {
  13992. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  13993. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  13994. }
  13995. };
  13996. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  13997. if (this._config) {
  13998. for (var j = 0; j < this._config.uniforms.length; j++) {
  13999. var uniform = this._config.uniforms[j];
  14000. switch (uniform.type) {
  14001. case "float":
  14002. this.setFloat(uniform.name, uniform.value);
  14003. break;
  14004. case "color3":
  14005. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  14006. break;
  14007. case "color4":
  14008. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  14009. break;
  14010. case "vector2":
  14011. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  14012. break;
  14013. case "vector3":
  14014. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  14015. break;
  14016. }
  14017. }
  14018. }
  14019. this.setFloat("time", this._time);
  14020. };
  14021. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  14022. get: function () {
  14023. return this._animate;
  14024. },
  14025. set: function (value) {
  14026. this._animate = value;
  14027. },
  14028. enumerable: true,
  14029. configurable: true
  14030. });
  14031. return CustomProceduralTexture;
  14032. })(BABYLON.ProceduralTexture);
  14033. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  14034. })(BABYLON || (BABYLON = {}));
  14035. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  14036. var BABYLON;
  14037. (function (BABYLON) {
  14038. var MirrorTexture = (function (_super) {
  14039. __extends(MirrorTexture, _super);
  14040. function MirrorTexture(name, size, scene, generateMipMaps) {
  14041. var _this = this;
  14042. _super.call(this, name, size, scene, generateMipMaps, true);
  14043. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  14044. this._transformMatrix = BABYLON.Matrix.Zero();
  14045. this._mirrorMatrix = BABYLON.Matrix.Zero();
  14046. this.onBeforeRender = function () {
  14047. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  14048. _this._savedViewMatrix = scene.getViewMatrix();
  14049. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  14050. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  14051. scene.clipPlane = _this.mirrorPlane;
  14052. scene.getEngine().cullBackFaces = false;
  14053. };
  14054. this.onAfterRender = function () {
  14055. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  14056. scene.getEngine().cullBackFaces = true;
  14057. delete scene.clipPlane;
  14058. };
  14059. }
  14060. MirrorTexture.prototype.clone = function () {
  14061. var textureSize = this.getSize();
  14062. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  14063. // Base texture
  14064. newTexture.hasAlpha = this.hasAlpha;
  14065. newTexture.level = this.level;
  14066. // Mirror Texture
  14067. newTexture.mirrorPlane = this.mirrorPlane.clone();
  14068. newTexture.renderList = this.renderList.slice(0);
  14069. return newTexture;
  14070. };
  14071. return MirrorTexture;
  14072. })(BABYLON.RenderTargetTexture);
  14073. BABYLON.MirrorTexture = MirrorTexture;
  14074. })(BABYLON || (BABYLON = {}));
  14075. //# sourceMappingURL=babylon.mirrorTexture.js.map
  14076. var BABYLON;
  14077. (function (BABYLON) {
  14078. var DynamicTexture = (function (_super) {
  14079. __extends(DynamicTexture, _super);
  14080. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  14081. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14082. _super.call(this, null, scene, !generateMipMaps);
  14083. this.name = name;
  14084. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14085. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14086. this._generateMipMaps = generateMipMaps;
  14087. if (options.getContext) {
  14088. this._canvas = options;
  14089. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  14090. }
  14091. else {
  14092. this._canvas = document.createElement("canvas");
  14093. if (options.width) {
  14094. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  14095. }
  14096. else {
  14097. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  14098. }
  14099. }
  14100. var textureSize = this.getSize();
  14101. this._canvas.width = textureSize.width;
  14102. this._canvas.height = textureSize.height;
  14103. this._context = this._canvas.getContext("2d");
  14104. }
  14105. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  14106. get: function () {
  14107. return true;
  14108. },
  14109. enumerable: true,
  14110. configurable: true
  14111. });
  14112. DynamicTexture.prototype.scale = function (ratio) {
  14113. var textureSize = this.getSize();
  14114. textureSize.width *= ratio;
  14115. textureSize.height *= ratio;
  14116. this._canvas.width = textureSize.width;
  14117. this._canvas.height = textureSize.height;
  14118. this.releaseInternalTexture();
  14119. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  14120. };
  14121. DynamicTexture.prototype.getContext = function () {
  14122. return this._context;
  14123. };
  14124. DynamicTexture.prototype.clear = function () {
  14125. var size = this.getSize();
  14126. this._context.fillRect(0, 0, size.width, size.height);
  14127. };
  14128. DynamicTexture.prototype.update = function (invertY) {
  14129. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  14130. };
  14131. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  14132. if (update === void 0) { update = true; }
  14133. var size = this.getSize();
  14134. if (clearColor) {
  14135. this._context.fillStyle = clearColor;
  14136. this._context.fillRect(0, 0, size.width, size.height);
  14137. }
  14138. this._context.font = font;
  14139. if (x === null) {
  14140. var textSize = this._context.measureText(text);
  14141. x = (size.width - textSize.width) / 2;
  14142. }
  14143. this._context.fillStyle = color;
  14144. this._context.fillText(text, x, y);
  14145. if (update) {
  14146. this.update(invertY);
  14147. }
  14148. };
  14149. DynamicTexture.prototype.clone = function () {
  14150. var textureSize = this.getSize();
  14151. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  14152. // Base texture
  14153. newTexture.hasAlpha = this.hasAlpha;
  14154. newTexture.level = this.level;
  14155. // Dynamic Texture
  14156. newTexture.wrapU = this.wrapU;
  14157. newTexture.wrapV = this.wrapV;
  14158. return newTexture;
  14159. };
  14160. return DynamicTexture;
  14161. })(BABYLON.Texture);
  14162. BABYLON.DynamicTexture = DynamicTexture;
  14163. })(BABYLON || (BABYLON = {}));
  14164. //# sourceMappingURL=babylon.dynamicTexture.js.map
  14165. var BABYLON;
  14166. (function (BABYLON) {
  14167. var VideoTexture = (function (_super) {
  14168. __extends(VideoTexture, _super);
  14169. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  14170. var _this = this;
  14171. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14172. _super.call(this, null, scene, !generateMipMaps, invertY);
  14173. this._autoLaunch = true;
  14174. this.name = name;
  14175. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  14176. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  14177. var requiredWidth = size.width || size;
  14178. var requiredHeight = size.height || size;
  14179. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  14180. var textureSize = this.getSize();
  14181. this.video = document.createElement("video");
  14182. this.video.width = textureSize.width;
  14183. this.video.height = textureSize.height;
  14184. this.video.autoplay = false;
  14185. this.video.loop = true;
  14186. this.video.addEventListener("canplaythrough", function () {
  14187. if (_this._texture) {
  14188. _this._texture.isReady = true;
  14189. }
  14190. });
  14191. urls.forEach(function (url) {
  14192. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  14193. var source = document.createElement("source");
  14194. source.src = url;
  14195. _this.video.appendChild(source);
  14196. });
  14197. this._lastUpdate = BABYLON.Tools.Now;
  14198. }
  14199. VideoTexture.prototype.update = function () {
  14200. if (this._autoLaunch) {
  14201. this._autoLaunch = false;
  14202. this.video.play();
  14203. }
  14204. var now = BABYLON.Tools.Now;
  14205. if (now - this._lastUpdate < 15) {
  14206. return false;
  14207. }
  14208. this._lastUpdate = now;
  14209. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  14210. return true;
  14211. };
  14212. return VideoTexture;
  14213. })(BABYLON.Texture);
  14214. BABYLON.VideoTexture = VideoTexture;
  14215. })(BABYLON || (BABYLON = {}));
  14216. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  14217. (function (BABYLON) {
  14218. var EffectFallbacks = (function () {
  14219. function EffectFallbacks() {
  14220. this._defines = {};
  14221. this._currentRank = 32;
  14222. this._maxRank = -1;
  14223. }
  14224. EffectFallbacks.prototype.addFallback = function (rank, define) {
  14225. if (!this._defines[rank]) {
  14226. if (rank < this._currentRank) {
  14227. this._currentRank = rank;
  14228. }
  14229. if (rank > this._maxRank) {
  14230. this._maxRank = rank;
  14231. }
  14232. this._defines[rank] = new Array();
  14233. }
  14234. this._defines[rank].push(define);
  14235. };
  14236. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  14237. get: function () {
  14238. return this._currentRank <= this._maxRank;
  14239. },
  14240. enumerable: true,
  14241. configurable: true
  14242. });
  14243. EffectFallbacks.prototype.reduce = function (currentDefines) {
  14244. var currentFallbacks = this._defines[this._currentRank];
  14245. for (var index = 0; index < currentFallbacks.length; index++) {
  14246. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  14247. }
  14248. this._currentRank++;
  14249. return currentDefines;
  14250. };
  14251. return EffectFallbacks;
  14252. })();
  14253. BABYLON.EffectFallbacks = EffectFallbacks;
  14254. var Effect = (function () {
  14255. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  14256. var _this = this;
  14257. this._isReady = false;
  14258. this._compilationError = "";
  14259. this._valueCache = [];
  14260. this._engine = engine;
  14261. this.name = baseName;
  14262. this.defines = defines;
  14263. this._uniformsNames = uniformsNames.concat(samplers);
  14264. this._samplers = samplers;
  14265. this._attributesNames = attributesNames;
  14266. this.onError = onError;
  14267. this.onCompiled = onCompiled;
  14268. var vertexSource;
  14269. var fragmentSource;
  14270. if (baseName.vertexElement) {
  14271. vertexSource = document.getElementById(baseName.vertexElement);
  14272. if (!vertexSource) {
  14273. vertexSource = baseName.vertexElement;
  14274. }
  14275. }
  14276. else {
  14277. vertexSource = baseName.vertex || baseName;
  14278. }
  14279. if (baseName.fragmentElement) {
  14280. fragmentSource = document.getElementById(baseName.fragmentElement);
  14281. if (!fragmentSource) {
  14282. fragmentSource = baseName.fragmentElement;
  14283. }
  14284. }
  14285. else {
  14286. fragmentSource = baseName.fragment || baseName;
  14287. }
  14288. this._loadVertexShader(vertexSource, function (vertexCode) {
  14289. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  14290. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  14291. });
  14292. });
  14293. }
  14294. // Properties
  14295. Effect.prototype.isReady = function () {
  14296. return this._isReady;
  14297. };
  14298. Effect.prototype.getProgram = function () {
  14299. return this._program;
  14300. };
  14301. Effect.prototype.getAttributesNames = function () {
  14302. return this._attributesNames;
  14303. };
  14304. Effect.prototype.getAttributeLocation = function (index) {
  14305. return this._attributes[index];
  14306. };
  14307. Effect.prototype.getAttributeLocationByName = function (name) {
  14308. var index = this._attributesNames.indexOf(name);
  14309. return this._attributes[index];
  14310. };
  14311. Effect.prototype.getAttributesCount = function () {
  14312. return this._attributes.length;
  14313. };
  14314. Effect.prototype.getUniformIndex = function (uniformName) {
  14315. return this._uniformsNames.indexOf(uniformName);
  14316. };
  14317. Effect.prototype.getUniform = function (uniformName) {
  14318. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  14319. };
  14320. Effect.prototype.getSamplers = function () {
  14321. return this._samplers;
  14322. };
  14323. Effect.prototype.getCompilationError = function () {
  14324. return this._compilationError;
  14325. };
  14326. // Methods
  14327. Effect.prototype._loadVertexShader = function (vertex, callback) {
  14328. // DOM element ?
  14329. if (vertex instanceof HTMLElement) {
  14330. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  14331. callback(vertexCode);
  14332. return;
  14333. }
  14334. // Is in local store ?
  14335. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  14336. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  14337. return;
  14338. }
  14339. var vertexShaderUrl;
  14340. if (vertex[0] === ".") {
  14341. vertexShaderUrl = vertex;
  14342. }
  14343. else {
  14344. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  14345. }
  14346. // Vertex shader
  14347. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  14348. };
  14349. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  14350. // DOM element ?
  14351. if (fragment instanceof HTMLElement) {
  14352. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  14353. callback(fragmentCode);
  14354. return;
  14355. }
  14356. // Is in local store ?
  14357. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  14358. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  14359. return;
  14360. }
  14361. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  14362. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  14363. return;
  14364. }
  14365. var fragmentShaderUrl;
  14366. if (fragment[0] === ".") {
  14367. fragmentShaderUrl = fragment;
  14368. }
  14369. else {
  14370. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  14371. }
  14372. // Fragment shader
  14373. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  14374. };
  14375. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  14376. try {
  14377. var engine = this._engine;
  14378. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  14379. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  14380. this._attributes = engine.getAttributes(this._program, attributesNames);
  14381. for (var index = 0; index < this._samplers.length; index++) {
  14382. var sampler = this.getUniform(this._samplers[index]);
  14383. if (sampler == null) {
  14384. this._samplers.splice(index, 1);
  14385. index--;
  14386. }
  14387. }
  14388. engine.bindSamplers(this);
  14389. this._isReady = true;
  14390. if (this.onCompiled) {
  14391. this.onCompiled(this);
  14392. }
  14393. }
  14394. catch (e) {
  14395. // Is it a problem with precision?
  14396. if (e.message.indexOf("highp") !== -1) {
  14397. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  14398. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  14399. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  14400. return;
  14401. }
  14402. // Let's go through fallbacks then
  14403. if (fallbacks && fallbacks.isMoreFallbacks) {
  14404. defines = fallbacks.reduce(defines);
  14405. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  14406. }
  14407. else {
  14408. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  14409. BABYLON.Tools.Error("Defines: " + defines);
  14410. BABYLON.Tools.Error("Error: " + e.message);
  14411. this._compilationError = e.message;
  14412. if (this.onError) {
  14413. this.onError(this, this._compilationError);
  14414. }
  14415. }
  14416. }
  14417. };
  14418. Effect.prototype._bindTexture = function (channel, texture) {
  14419. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  14420. };
  14421. Effect.prototype.setTexture = function (channel, texture) {
  14422. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  14423. };
  14424. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14425. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  14426. };
  14427. //public _cacheMatrix(uniformName, matrix) {
  14428. // if (!this._valueCache[uniformName]) {
  14429. // this._valueCache[uniformName] = new BABYLON.Matrix();
  14430. // }
  14431. // for (var index = 0; index < 16; index++) {
  14432. // this._valueCache[uniformName].m[index] = matrix.m[index];
  14433. // }
  14434. //};
  14435. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  14436. if (!this._valueCache[uniformName]) {
  14437. this._valueCache[uniformName] = [x, y];
  14438. return;
  14439. }
  14440. this._valueCache[uniformName][0] = x;
  14441. this._valueCache[uniformName][1] = y;
  14442. };
  14443. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  14444. if (!this._valueCache[uniformName]) {
  14445. this._valueCache[uniformName] = [x, y, z];
  14446. return;
  14447. }
  14448. this._valueCache[uniformName][0] = x;
  14449. this._valueCache[uniformName][1] = y;
  14450. this._valueCache[uniformName][2] = z;
  14451. };
  14452. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  14453. if (!this._valueCache[uniformName]) {
  14454. this._valueCache[uniformName] = [x, y, z, w];
  14455. return;
  14456. }
  14457. this._valueCache[uniformName][0] = x;
  14458. this._valueCache[uniformName][1] = y;
  14459. this._valueCache[uniformName][2] = z;
  14460. this._valueCache[uniformName][3] = w;
  14461. };
  14462. Effect.prototype.setArray = function (uniformName, array) {
  14463. this._engine.setArray(this.getUniform(uniformName), array);
  14464. return this;
  14465. };
  14466. Effect.prototype.setArray2 = function (uniformName, array) {
  14467. this._engine.setArray2(this.getUniform(uniformName), array);
  14468. return this;
  14469. };
  14470. Effect.prototype.setArray3 = function (uniformName, array) {
  14471. this._engine.setArray3(this.getUniform(uniformName), array);
  14472. return this;
  14473. };
  14474. Effect.prototype.setArray4 = function (uniformName, array) {
  14475. this._engine.setArray4(this.getUniform(uniformName), array);
  14476. return this;
  14477. };
  14478. Effect.prototype.setMatrices = function (uniformName, matrices) {
  14479. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  14480. return this;
  14481. };
  14482. Effect.prototype.setMatrix = function (uniformName, matrix) {
  14483. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  14484. // return;
  14485. //this._cacheMatrix(uniformName, matrix);
  14486. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  14487. return this;
  14488. };
  14489. Effect.prototype.setFloat = function (uniformName, value) {
  14490. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  14491. return this;
  14492. this._valueCache[uniformName] = value;
  14493. this._engine.setFloat(this.getUniform(uniformName), value);
  14494. return this;
  14495. };
  14496. Effect.prototype.setBool = function (uniformName, bool) {
  14497. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  14498. return this;
  14499. this._valueCache[uniformName] = bool;
  14500. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  14501. return this;
  14502. };
  14503. Effect.prototype.setVector2 = function (uniformName, vector2) {
  14504. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  14505. return this;
  14506. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  14507. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  14508. return this;
  14509. };
  14510. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  14511. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  14512. return this;
  14513. this._cacheFloat2(uniformName, x, y);
  14514. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  14515. return this;
  14516. };
  14517. Effect.prototype.setVector3 = function (uniformName, vector3) {
  14518. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  14519. return this;
  14520. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  14521. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  14522. return this;
  14523. };
  14524. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  14525. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  14526. return this;
  14527. this._cacheFloat3(uniformName, x, y, z);
  14528. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  14529. return this;
  14530. };
  14531. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  14532. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  14533. return this;
  14534. this._cacheFloat4(uniformName, x, y, z, w);
  14535. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  14536. return this;
  14537. };
  14538. Effect.prototype.setColor3 = function (uniformName, color3) {
  14539. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  14540. return this;
  14541. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  14542. this._engine.setColor3(this.getUniform(uniformName), color3);
  14543. return this;
  14544. };
  14545. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  14546. 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)
  14547. return this;
  14548. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  14549. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  14550. return this;
  14551. };
  14552. // Statics
  14553. 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}",
  14554. 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}",
  14555. 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}",
  14556. 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}",
  14557. 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}",
  14558. 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}",
  14559. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\ngl_FragColor = color;\n}",
  14560. colorVertexShader:"precision highp float;\n\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\n\nvoid main(void) {\ngl_Position = worldViewProjection * vec4(position, 1.0);\n}",
  14561. 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}",
  14562. 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}",
  14563. 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}",
  14564. 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}",
  14565. 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}",
  14566. 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}",
  14567. 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}",
  14568. 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}",
  14569. 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}",
  14570. 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}",
  14571. 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}",
  14572. 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}",
  14573. 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}",
  14574. 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}",
  14575. 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}",
  14576. 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}",
  14577. 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}",
  14578. 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}",
  14579. 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}",
  14580. 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}",
  14581. 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}",
  14582. 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}",
  14583. 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}",
  14584. 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}",
  14585. 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}",
  14586. 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}",
  14587. 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}",
  14588. 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}",
  14589. 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}",
  14590. 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}",
  14591. 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}",
  14592. 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}",
  14593. 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}",
  14594. 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}",
  14595. 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}",
  14596. 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}",
  14597. 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}",
  14598. 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}",
  14599. 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}",
  14600. 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}",
  14601. };
  14602. return Effect;
  14603. })();
  14604. BABYLON.Effect = Effect;
  14605. })(BABYLON || (BABYLON = {}));
  14606. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  14607. (function (BABYLON) {
  14608. var Material = (function () {
  14609. function Material(name, scene, doNotAdd) {
  14610. this.name = name;
  14611. this.checkReadyOnEveryCall = true;
  14612. this.checkReadyOnlyOnce = false;
  14613. this.state = "";
  14614. this.alpha = 1.0;
  14615. this.backFaceCulling = true;
  14616. this._wasPreviouslyReady = false;
  14617. this._fillMode = Material.TriangleFillMode;
  14618. this.pointSize = 1.0;
  14619. this.zOffset = 0;
  14620. this.id = name;
  14621. this._scene = scene;
  14622. if (!doNotAdd) {
  14623. scene.materials.push(this);
  14624. }
  14625. }
  14626. Object.defineProperty(Material, "TriangleFillMode", {
  14627. get: function () {
  14628. return Material._TriangleFillMode;
  14629. },
  14630. enumerable: true,
  14631. configurable: true
  14632. });
  14633. Object.defineProperty(Material, "WireFrameFillMode", {
  14634. get: function () {
  14635. return Material._WireFrameFillMode;
  14636. },
  14637. enumerable: true,
  14638. configurable: true
  14639. });
  14640. Object.defineProperty(Material, "PointFillMode", {
  14641. get: function () {
  14642. return Material._PointFillMode;
  14643. },
  14644. enumerable: true,
  14645. configurable: true
  14646. });
  14647. Object.defineProperty(Material.prototype, "wireframe", {
  14648. get: function () {
  14649. return this._fillMode === Material.WireFrameFillMode;
  14650. },
  14651. set: function (value) {
  14652. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  14653. },
  14654. enumerable: true,
  14655. configurable: true
  14656. });
  14657. Object.defineProperty(Material.prototype, "pointsCloud", {
  14658. get: function () {
  14659. return this._fillMode === Material.PointFillMode;
  14660. },
  14661. set: function (value) {
  14662. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  14663. },
  14664. enumerable: true,
  14665. configurable: true
  14666. });
  14667. Object.defineProperty(Material.prototype, "fillMode", {
  14668. get: function () {
  14669. return this._fillMode;
  14670. },
  14671. set: function (value) {
  14672. this._fillMode = value;
  14673. },
  14674. enumerable: true,
  14675. configurable: true
  14676. });
  14677. Material.prototype.isReady = function (mesh, useInstances) {
  14678. return true;
  14679. };
  14680. Material.prototype.getEffect = function () {
  14681. return this._effect;
  14682. };
  14683. Material.prototype.getScene = function () {
  14684. return this._scene;
  14685. };
  14686. Material.prototype.needAlphaBlending = function () {
  14687. return (this.alpha < 1.0);
  14688. };
  14689. Material.prototype.needAlphaTesting = function () {
  14690. return false;
  14691. };
  14692. Material.prototype.getAlphaTestTexture = function () {
  14693. return null;
  14694. };
  14695. Material.prototype.trackCreation = function (onCompiled, onError) {
  14696. };
  14697. Material.prototype._preBind = function () {
  14698. var engine = this._scene.getEngine();
  14699. engine.enableEffect(this._effect);
  14700. engine.setState(this.backFaceCulling, this.zOffset);
  14701. };
  14702. Material.prototype.bind = function (world, mesh) {
  14703. this._scene._cachedMaterial = this;
  14704. if (this.onBind) {
  14705. this.onBind(this, mesh);
  14706. }
  14707. };
  14708. Material.prototype.bindOnlyWorldMatrix = function (world) {
  14709. };
  14710. Material.prototype.unbind = function () {
  14711. };
  14712. Material.prototype.dispose = function (forceDisposeEffect) {
  14713. // Remove from scene
  14714. var index = this._scene.materials.indexOf(this);
  14715. this._scene.materials.splice(index, 1);
  14716. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  14717. if (forceDisposeEffect && this._effect) {
  14718. this._scene.getEngine()._releaseEffect(this._effect);
  14719. this._effect = null;
  14720. }
  14721. // Callback
  14722. if (this.onDispose) {
  14723. this.onDispose();
  14724. }
  14725. };
  14726. Material._TriangleFillMode = 0;
  14727. Material._WireFrameFillMode = 1;
  14728. Material._PointFillMode = 2;
  14729. return Material;
  14730. })();
  14731. BABYLON.Material = Material;
  14732. })(BABYLON || (BABYLON = {}));
  14733. //# sourceMappingURL=babylon.material.js.map
  14734. var BABYLON;
  14735. (function (BABYLON) {
  14736. var maxSimultaneousLights = 4;
  14737. var FresnelParameters = (function () {
  14738. function FresnelParameters() {
  14739. this.isEnabled = true;
  14740. this.leftColor = BABYLON.Color3.White();
  14741. this.rightColor = BABYLON.Color3.Black();
  14742. this.bias = 0;
  14743. this.power = 1;
  14744. }
  14745. return FresnelParameters;
  14746. })();
  14747. BABYLON.FresnelParameters = FresnelParameters;
  14748. var StandardMaterial = (function (_super) {
  14749. __extends(StandardMaterial, _super);
  14750. function StandardMaterial(name, scene) {
  14751. var _this = this;
  14752. _super.call(this, name, scene);
  14753. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14754. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  14755. this.specularColor = new BABYLON.Color3(1, 1, 1);
  14756. this.specularPower = 64;
  14757. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  14758. this.useAlphaFromDiffuseTexture = false;
  14759. this.useSpecularOverAlpha = true;
  14760. this.fogEnabled = true;
  14761. this._cachedDefines = null;
  14762. this._renderTargets = new BABYLON.SmartArray(16);
  14763. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  14764. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  14765. this._scaledDiffuse = new BABYLON.Color3();
  14766. this._scaledSpecular = new BABYLON.Color3();
  14767. this.getRenderTargetTextures = function () {
  14768. _this._renderTargets.reset();
  14769. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  14770. _this._renderTargets.push(_this.reflectionTexture);
  14771. }
  14772. return _this._renderTargets;
  14773. };
  14774. }
  14775. StandardMaterial.prototype.needAlphaBlending = function () {
  14776. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  14777. };
  14778. StandardMaterial.prototype.needAlphaTesting = function () {
  14779. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  14780. };
  14781. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  14782. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  14783. };
  14784. StandardMaterial.prototype.getAlphaTestTexture = function () {
  14785. return this.diffuseTexture;
  14786. };
  14787. // Methods
  14788. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  14789. if (this.checkReadyOnlyOnce) {
  14790. if (this._wasPreviouslyReady) {
  14791. }
  14792. }
  14793. var scene = this.getScene();
  14794. if (!this.checkReadyOnEveryCall) {
  14795. if (this._renderId === scene.getRenderId()) {
  14796. }
  14797. }
  14798. var engine = scene.getEngine();
  14799. var defines = [];
  14800. var fallbacks = new BABYLON.EffectFallbacks();
  14801. var needNormals = false;
  14802. var needUVs = false;
  14803. // Textures
  14804. if (scene.texturesEnabled) {
  14805. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14806. if (!this.diffuseTexture.isReady()) {
  14807. return false;
  14808. }
  14809. else {
  14810. needUVs = true;
  14811. defines.push("#define DIFFUSE");
  14812. }
  14813. }
  14814. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14815. if (!this.ambientTexture.isReady()) {
  14816. return false;
  14817. }
  14818. else {
  14819. needUVs = true;
  14820. defines.push("#define AMBIENT");
  14821. }
  14822. }
  14823. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14824. if (!this.opacityTexture.isReady()) {
  14825. return false;
  14826. }
  14827. else {
  14828. needUVs = true;
  14829. defines.push("#define OPACITY");
  14830. if (this.opacityTexture.getAlphaFromRGB) {
  14831. defines.push("#define OPACITYRGB");
  14832. }
  14833. }
  14834. }
  14835. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14836. if (!this.reflectionTexture.isReady()) {
  14837. return false;
  14838. }
  14839. else {
  14840. needNormals = true;
  14841. needUVs = true;
  14842. defines.push("#define REFLECTION");
  14843. fallbacks.addFallback(0, "REFLECTION");
  14844. }
  14845. }
  14846. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14847. if (!this.emissiveTexture.isReady()) {
  14848. return false;
  14849. }
  14850. else {
  14851. needUVs = true;
  14852. defines.push("#define EMISSIVE");
  14853. }
  14854. }
  14855. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14856. if (!this.specularTexture.isReady()) {
  14857. return false;
  14858. }
  14859. else {
  14860. needUVs = true;
  14861. defines.push("#define SPECULAR");
  14862. fallbacks.addFallback(0, "SPECULAR");
  14863. }
  14864. }
  14865. }
  14866. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  14867. if (!this.bumpTexture.isReady()) {
  14868. return false;
  14869. }
  14870. else {
  14871. needUVs = true;
  14872. defines.push("#define BUMP");
  14873. fallbacks.addFallback(0, "BUMP");
  14874. }
  14875. }
  14876. // Effect
  14877. if (this.useSpecularOverAlpha) {
  14878. defines.push("#define SPECULAROVERALPHA");
  14879. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  14880. }
  14881. if (scene.clipPlane) {
  14882. defines.push("#define CLIPPLANE");
  14883. }
  14884. if (engine.getAlphaTesting()) {
  14885. defines.push("#define ALPHATEST");
  14886. }
  14887. if (this._shouldUseAlphaFromDiffuseTexture()) {
  14888. defines.push("#define ALPHAFROMDIFFUSE");
  14889. }
  14890. // Point size
  14891. if (this.pointsCloud || scene.forcePointsCloud) {
  14892. defines.push("#define POINTSIZE");
  14893. }
  14894. // Fog
  14895. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14896. defines.push("#define FOG");
  14897. fallbacks.addFallback(1, "FOG");
  14898. }
  14899. var shadowsActivated = false;
  14900. var lightIndex = 0;
  14901. if (scene.lightsEnabled) {
  14902. for (var index = 0; index < scene.lights.length; index++) {
  14903. var light = scene.lights[index];
  14904. if (!light.isEnabled()) {
  14905. continue;
  14906. }
  14907. // Excluded check
  14908. if (light._excludedMeshesIds.length > 0) {
  14909. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  14910. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  14911. if (excludedMesh) {
  14912. light.excludedMeshes.push(excludedMesh);
  14913. }
  14914. }
  14915. light._excludedMeshesIds = [];
  14916. }
  14917. // Included check
  14918. if (light._includedOnlyMeshesIds.length > 0) {
  14919. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  14920. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  14921. if (includedOnlyMesh) {
  14922. light.includedOnlyMeshes.push(includedOnlyMesh);
  14923. }
  14924. }
  14925. light._includedOnlyMeshesIds = [];
  14926. }
  14927. if (!light.canAffectMesh(mesh)) {
  14928. continue;
  14929. }
  14930. needNormals = true;
  14931. defines.push("#define LIGHT" + lightIndex);
  14932. if (lightIndex > 0) {
  14933. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  14934. }
  14935. var type;
  14936. if (light instanceof BABYLON.SpotLight) {
  14937. type = "#define SPOTLIGHT" + lightIndex;
  14938. }
  14939. else if (light instanceof BABYLON.HemisphericLight) {
  14940. type = "#define HEMILIGHT" + lightIndex;
  14941. }
  14942. else {
  14943. type = "#define POINTDIRLIGHT" + lightIndex;
  14944. }
  14945. defines.push(type);
  14946. if (lightIndex > 0) {
  14947. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  14948. }
  14949. // Shadows
  14950. if (scene.shadowsEnabled) {
  14951. var shadowGenerator = light.getShadowGenerator();
  14952. if (mesh && mesh.receiveShadows && shadowGenerator) {
  14953. defines.push("#define SHADOW" + lightIndex);
  14954. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  14955. if (!shadowsActivated) {
  14956. defines.push("#define SHADOWS");
  14957. shadowsActivated = true;
  14958. }
  14959. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  14960. defines.push("#define SHADOWVSM" + lightIndex);
  14961. if (lightIndex > 0) {
  14962. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  14963. }
  14964. }
  14965. if (shadowGenerator.usePoissonSampling) {
  14966. defines.push("#define SHADOWPCF" + lightIndex);
  14967. if (lightIndex > 0) {
  14968. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  14969. }
  14970. }
  14971. }
  14972. }
  14973. lightIndex++;
  14974. if (lightIndex === maxSimultaneousLights)
  14975. break;
  14976. }
  14977. }
  14978. if (StandardMaterial.FresnelEnabled) {
  14979. // Fresnel
  14980. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14981. var fresnelRank = 1;
  14982. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  14983. defines.push("#define DIFFUSEFRESNEL");
  14984. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  14985. fresnelRank++;
  14986. }
  14987. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  14988. defines.push("#define OPACITYFRESNEL");
  14989. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  14990. fresnelRank++;
  14991. }
  14992. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14993. defines.push("#define REFLECTIONFRESNEL");
  14994. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  14995. fresnelRank++;
  14996. }
  14997. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  14998. defines.push("#define EMISSIVEFRESNEL");
  14999. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  15000. fresnelRank++;
  15001. }
  15002. needNormals = true;
  15003. defines.push("#define FRESNEL");
  15004. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  15005. }
  15006. }
  15007. // Attribs
  15008. var attribs = [BABYLON.VertexBuffer.PositionKind];
  15009. if (mesh) {
  15010. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  15011. attribs.push(BABYLON.VertexBuffer.NormalKind);
  15012. defines.push("#define NORMAL");
  15013. }
  15014. if (needUVs) {
  15015. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  15016. attribs.push(BABYLON.VertexBuffer.UVKind);
  15017. defines.push("#define UV1");
  15018. }
  15019. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  15020. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  15021. defines.push("#define UV2");
  15022. }
  15023. }
  15024. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  15025. attribs.push(BABYLON.VertexBuffer.ColorKind);
  15026. defines.push("#define VERTEXCOLOR");
  15027. if (mesh.hasVertexAlpha) {
  15028. defines.push("#define VERTEXALPHA");
  15029. }
  15030. }
  15031. if (mesh.useBones) {
  15032. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  15033. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  15034. defines.push("#define BONES");
  15035. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  15036. defines.push("#define BONES4");
  15037. fallbacks.addFallback(0, "BONES4");
  15038. }
  15039. // Instances
  15040. if (useInstances) {
  15041. defines.push("#define INSTANCES");
  15042. attribs.push("world0");
  15043. attribs.push("world1");
  15044. attribs.push("world2");
  15045. attribs.push("world3");
  15046. }
  15047. }
  15048. // Get correct effect
  15049. var join = defines.join("\n");
  15050. if (this._cachedDefines !== join) {
  15051. this._cachedDefines = join;
  15052. scene.resetCachedMaterial();
  15053. // Legacy browser patch
  15054. var shaderName = "default";
  15055. if (!scene.getEngine().getCaps().standardDerivatives) {
  15056. shaderName = "legacydefault";
  15057. }
  15058. 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);
  15059. }
  15060. if (!this._effect.isReady()) {
  15061. return false;
  15062. }
  15063. this._renderId = scene.getRenderId();
  15064. this._wasPreviouslyReady = true;
  15065. return true;
  15066. };
  15067. StandardMaterial.prototype.unbind = function () {
  15068. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  15069. this._effect.setTexture("reflection2DSampler", null);
  15070. }
  15071. };
  15072. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  15073. this._effect.setMatrix("world", world);
  15074. };
  15075. StandardMaterial.prototype.bind = function (world, mesh) {
  15076. var scene = this.getScene();
  15077. // Matrices
  15078. this.bindOnlyWorldMatrix(world);
  15079. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  15080. // Bones
  15081. if (mesh && mesh.useBones) {
  15082. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  15083. }
  15084. if (scene.getCachedMaterial() !== this) {
  15085. if (StandardMaterial.FresnelEnabled) {
  15086. // Fresnel
  15087. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  15088. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  15089. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  15090. }
  15091. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  15092. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  15093. }
  15094. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  15095. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  15096. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  15097. }
  15098. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  15099. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  15100. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  15101. }
  15102. }
  15103. // Textures
  15104. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  15105. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  15106. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  15107. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  15108. }
  15109. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  15110. this._effect.setTexture("ambientSampler", this.ambientTexture);
  15111. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  15112. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  15113. }
  15114. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  15115. this._effect.setTexture("opacitySampler", this.opacityTexture);
  15116. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  15117. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  15118. }
  15119. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  15120. if (this.reflectionTexture.isCube) {
  15121. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  15122. }
  15123. else {
  15124. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  15125. }
  15126. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  15127. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  15128. }
  15129. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  15130. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  15131. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  15132. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  15133. }
  15134. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  15135. this._effect.setTexture("specularSampler", this.specularTexture);
  15136. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  15137. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  15138. }
  15139. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  15140. this._effect.setTexture("bumpSampler", this.bumpTexture);
  15141. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  15142. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  15143. }
  15144. // Clip plane
  15145. if (scene.clipPlane) {
  15146. var clipPlane = scene.clipPlane;
  15147. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  15148. }
  15149. // Point size
  15150. if (this.pointsCloud) {
  15151. this._effect.setFloat("pointSize", this.pointSize);
  15152. }
  15153. // Colors
  15154. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  15155. // Scaling down color according to emissive
  15156. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  15157. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  15158. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  15159. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  15160. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  15161. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  15162. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  15163. }
  15164. // Scaling down color according to emissive
  15165. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  15166. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  15167. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  15168. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  15169. if (scene.lightsEnabled) {
  15170. var lightIndex = 0;
  15171. for (var index = 0; index < scene.lights.length; index++) {
  15172. var light = scene.lights[index];
  15173. if (!light.isEnabled()) {
  15174. continue;
  15175. }
  15176. if (!light.canAffectMesh(mesh)) {
  15177. continue;
  15178. }
  15179. if (light instanceof BABYLON.PointLight) {
  15180. // Point Light
  15181. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  15182. }
  15183. else if (light instanceof BABYLON.DirectionalLight) {
  15184. // Directional Light
  15185. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  15186. }
  15187. else if (light instanceof BABYLON.SpotLight) {
  15188. // Spot Light
  15189. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  15190. }
  15191. else if (light instanceof BABYLON.HemisphericLight) {
  15192. // Hemispheric Light
  15193. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  15194. }
  15195. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  15196. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  15197. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  15198. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  15199. // Shadows
  15200. if (scene.shadowsEnabled) {
  15201. var shadowGenerator = light.getShadowGenerator();
  15202. if (mesh.receiveShadows && shadowGenerator) {
  15203. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  15204. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  15205. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  15206. }
  15207. }
  15208. lightIndex++;
  15209. if (lightIndex === maxSimultaneousLights)
  15210. break;
  15211. }
  15212. }
  15213. // View
  15214. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  15215. this._effect.setMatrix("view", scene.getViewMatrix());
  15216. }
  15217. // Fog
  15218. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  15219. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  15220. this._effect.setColor3("vFogColor", scene.fogColor);
  15221. }
  15222. _super.prototype.bind.call(this, world, mesh);
  15223. };
  15224. StandardMaterial.prototype.getAnimatables = function () {
  15225. var results = [];
  15226. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  15227. results.push(this.diffuseTexture);
  15228. }
  15229. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  15230. results.push(this.ambientTexture);
  15231. }
  15232. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  15233. results.push(this.opacityTexture);
  15234. }
  15235. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  15236. results.push(this.reflectionTexture);
  15237. }
  15238. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  15239. results.push(this.emissiveTexture);
  15240. }
  15241. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  15242. results.push(this.specularTexture);
  15243. }
  15244. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  15245. results.push(this.bumpTexture);
  15246. }
  15247. return results;
  15248. };
  15249. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  15250. if (this.diffuseTexture) {
  15251. this.diffuseTexture.dispose();
  15252. }
  15253. if (this.ambientTexture) {
  15254. this.ambientTexture.dispose();
  15255. }
  15256. if (this.opacityTexture) {
  15257. this.opacityTexture.dispose();
  15258. }
  15259. if (this.reflectionTexture) {
  15260. this.reflectionTexture.dispose();
  15261. }
  15262. if (this.emissiveTexture) {
  15263. this.emissiveTexture.dispose();
  15264. }
  15265. if (this.specularTexture) {
  15266. this.specularTexture.dispose();
  15267. }
  15268. if (this.bumpTexture) {
  15269. this.bumpTexture.dispose();
  15270. }
  15271. _super.prototype.dispose.call(this, forceDisposeEffect);
  15272. };
  15273. StandardMaterial.prototype.clone = function (name) {
  15274. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  15275. // Base material
  15276. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  15277. newStandardMaterial.alpha = this.alpha;
  15278. newStandardMaterial.fillMode = this.fillMode;
  15279. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  15280. // Standard material
  15281. if (this.diffuseTexture && this.diffuseTexture.clone) {
  15282. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  15283. }
  15284. if (this.ambientTexture && this.ambientTexture.clone) {
  15285. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  15286. }
  15287. if (this.opacityTexture && this.opacityTexture.clone) {
  15288. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  15289. }
  15290. if (this.reflectionTexture && this.reflectionTexture.clone) {
  15291. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  15292. }
  15293. if (this.emissiveTexture && this.emissiveTexture.clone) {
  15294. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  15295. }
  15296. if (this.specularTexture && this.specularTexture.clone) {
  15297. newStandardMaterial.specularTexture = this.specularTexture.clone();
  15298. }
  15299. if (this.bumpTexture && this.bumpTexture.clone) {
  15300. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  15301. }
  15302. newStandardMaterial.ambientColor = this.ambientColor.clone();
  15303. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  15304. newStandardMaterial.specularColor = this.specularColor.clone();
  15305. newStandardMaterial.specularPower = this.specularPower;
  15306. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  15307. return newStandardMaterial;
  15308. };
  15309. // Statics
  15310. // Flags used to enable or disable a type of texture for all Standard Materials
  15311. StandardMaterial.DiffuseTextureEnabled = true;
  15312. StandardMaterial.AmbientTextureEnabled = true;
  15313. StandardMaterial.OpacityTextureEnabled = true;
  15314. StandardMaterial.ReflectionTextureEnabled = true;
  15315. StandardMaterial.EmissiveTextureEnabled = true;
  15316. StandardMaterial.SpecularTextureEnabled = true;
  15317. StandardMaterial.BumpTextureEnabled = true;
  15318. StandardMaterial.FresnelEnabled = true;
  15319. return StandardMaterial;
  15320. })(BABYLON.Material);
  15321. BABYLON.StandardMaterial = StandardMaterial;
  15322. })(BABYLON || (BABYLON = {}));
  15323. //# sourceMappingURL=babylon.standardMaterial.js.map
  15324. var BABYLON;
  15325. (function (BABYLON) {
  15326. var MultiMaterial = (function (_super) {
  15327. __extends(MultiMaterial, _super);
  15328. function MultiMaterial(name, scene) {
  15329. _super.call(this, name, scene, true);
  15330. this.subMaterials = new Array();
  15331. scene.multiMaterials.push(this);
  15332. }
  15333. // Properties
  15334. MultiMaterial.prototype.getSubMaterial = function (index) {
  15335. if (index < 0 || index >= this.subMaterials.length) {
  15336. return this.getScene().defaultMaterial;
  15337. }
  15338. return this.subMaterials[index];
  15339. };
  15340. // Methods
  15341. MultiMaterial.prototype.isReady = function (mesh) {
  15342. for (var index = 0; index < this.subMaterials.length; index++) {
  15343. var subMaterial = this.subMaterials[index];
  15344. if (subMaterial) {
  15345. if (!this.subMaterials[index].isReady(mesh)) {
  15346. return false;
  15347. }
  15348. }
  15349. }
  15350. return true;
  15351. };
  15352. return MultiMaterial;
  15353. })(BABYLON.Material);
  15354. BABYLON.MultiMaterial = MultiMaterial;
  15355. })(BABYLON || (BABYLON = {}));
  15356. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  15357. (function (BABYLON) {
  15358. var Database = (function () {
  15359. function Database(urlToScene, callbackManifestChecked) {
  15360. // Handling various flavors of prefixed version of IndexedDB
  15361. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  15362. this.callbackManifestChecked = callbackManifestChecked;
  15363. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  15364. this.db = null;
  15365. this.enableSceneOffline = false;
  15366. this.enableTexturesOffline = false;
  15367. this.manifestVersionFound = 0;
  15368. this.mustUpdateRessources = false;
  15369. this.hasReachedQuota = false;
  15370. this.checkManifestFile();
  15371. }
  15372. Database.prototype.checkManifestFile = function () {
  15373. var _this = this;
  15374. function noManifestFile() {
  15375. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  15376. that.enableSceneOffline = false;
  15377. that.enableTexturesOffline = false;
  15378. that.callbackManifestChecked(false);
  15379. }
  15380. var that = this;
  15381. var manifestURL = this.currentSceneUrl + ".manifest";
  15382. var xhr = new XMLHttpRequest();
  15383. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  15384. xhr.open("GET", manifestURLTimeStamped, true);
  15385. xhr.addEventListener("load", function () {
  15386. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  15387. try {
  15388. var manifestFile = JSON.parse(xhr.response);
  15389. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  15390. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  15391. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  15392. _this.manifestVersionFound = manifestFile.version;
  15393. }
  15394. if (_this.callbackManifestChecked) {
  15395. _this.callbackManifestChecked(true);
  15396. }
  15397. }
  15398. catch (ex) {
  15399. noManifestFile();
  15400. }
  15401. }
  15402. else {
  15403. noManifestFile();
  15404. }
  15405. }, false);
  15406. xhr.addEventListener("error", function (event) {
  15407. noManifestFile();
  15408. }, false);
  15409. try {
  15410. xhr.send();
  15411. }
  15412. catch (ex) {
  15413. BABYLON.Tools.Error("Error on XHR send request.");
  15414. that.callbackManifestChecked(false);
  15415. }
  15416. };
  15417. Database.prototype.openAsync = function (successCallback, errorCallback) {
  15418. var _this = this;
  15419. function handleError() {
  15420. that.isSupported = false;
  15421. if (errorCallback)
  15422. errorCallback();
  15423. }
  15424. var that = this;
  15425. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  15426. // Your browser doesn't support IndexedDB
  15427. this.isSupported = false;
  15428. if (errorCallback)
  15429. errorCallback();
  15430. }
  15431. else {
  15432. // If the DB hasn't been opened or created yet
  15433. if (!this.db) {
  15434. this.hasReachedQuota = false;
  15435. this.isSupported = true;
  15436. var request = this.idbFactory.open("babylonjs", 1);
  15437. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  15438. request.onerror = function (event) {
  15439. handleError();
  15440. };
  15441. // executes when a version change transaction cannot complete due to other active transactions
  15442. request.onblocked = function (event) {
  15443. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  15444. handleError();
  15445. };
  15446. // DB has been opened successfully
  15447. request.onsuccess = function (event) {
  15448. _this.db = request.result;
  15449. successCallback();
  15450. };
  15451. // Initialization of the DB. Creating Scenes & Textures stores
  15452. request.onupgradeneeded = function (event) {
  15453. _this.db = (event.target).result;
  15454. try {
  15455. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  15456. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  15457. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  15458. }
  15459. catch (ex) {
  15460. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  15461. handleError();
  15462. }
  15463. };
  15464. }
  15465. else {
  15466. if (successCallback)
  15467. successCallback();
  15468. }
  15469. }
  15470. };
  15471. Database.prototype.loadImageFromDB = function (url, image) {
  15472. var _this = this;
  15473. var completeURL = Database.ReturnFullUrlLocation(url);
  15474. var saveAndLoadImage = function () {
  15475. if (!_this.hasReachedQuota && _this.db !== null) {
  15476. // the texture is not yet in the DB, let's try to save it
  15477. _this._saveImageIntoDBAsync(completeURL, image);
  15478. }
  15479. else {
  15480. image.src = url;
  15481. }
  15482. };
  15483. if (!this.mustUpdateRessources) {
  15484. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  15485. }
  15486. else {
  15487. saveAndLoadImage();
  15488. }
  15489. };
  15490. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  15491. if (this.isSupported && this.db !== null) {
  15492. var texture;
  15493. var transaction = this.db.transaction(["textures"]);
  15494. transaction.onabort = function (event) {
  15495. image.src = url;
  15496. };
  15497. transaction.oncomplete = function (event) {
  15498. var blobTextureURL;
  15499. if (texture) {
  15500. var URL = window.URL || window.webkitURL;
  15501. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  15502. image.onerror = function () {
  15503. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  15504. image.src = url;
  15505. };
  15506. image.src = blobTextureURL;
  15507. }
  15508. else {
  15509. notInDBCallback();
  15510. }
  15511. };
  15512. var getRequest = transaction.objectStore("textures").get(url);
  15513. getRequest.onsuccess = function (event) {
  15514. texture = (event.target).result;
  15515. };
  15516. getRequest.onerror = function (event) {
  15517. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  15518. image.src = url;
  15519. };
  15520. }
  15521. else {
  15522. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15523. image.src = url;
  15524. }
  15525. };
  15526. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  15527. var _this = this;
  15528. if (this.isSupported) {
  15529. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  15530. var generateBlobUrl = function () {
  15531. var blobTextureURL;
  15532. if (blob) {
  15533. var URL = window.URL || window.webkitURL;
  15534. try {
  15535. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  15536. }
  15537. catch (ex) {
  15538. blobTextureURL = URL.createObjectURL(blob);
  15539. }
  15540. }
  15541. image.src = blobTextureURL;
  15542. };
  15543. if (Database.isUASupportingBlobStorage) {
  15544. var xhr = new XMLHttpRequest(), blob;
  15545. xhr.open("GET", url, true);
  15546. xhr.responseType = "blob";
  15547. xhr.addEventListener("load", function () {
  15548. if (xhr.status === 200) {
  15549. // Blob as response (XHR2)
  15550. blob = xhr.response;
  15551. var transaction = _this.db.transaction(["textures"], "readwrite");
  15552. // the transaction could abort because of a QuotaExceededError error
  15553. transaction.onabort = function (event) {
  15554. try {
  15555. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15556. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15557. this.hasReachedQuota = true;
  15558. }
  15559. }
  15560. catch (ex) {
  15561. }
  15562. generateBlobUrl();
  15563. };
  15564. transaction.oncomplete = function (event) {
  15565. generateBlobUrl();
  15566. };
  15567. var newTexture = { textureUrl: url, data: blob };
  15568. try {
  15569. // Put the blob into the dabase
  15570. var addRequest = transaction.objectStore("textures").put(newTexture);
  15571. addRequest.onsuccess = function (event) {
  15572. };
  15573. addRequest.onerror = function (event) {
  15574. generateBlobUrl();
  15575. };
  15576. }
  15577. catch (ex) {
  15578. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  15579. if (ex.code === 25) {
  15580. Database.isUASupportingBlobStorage = false;
  15581. }
  15582. image.src = url;
  15583. }
  15584. }
  15585. else {
  15586. image.src = url;
  15587. }
  15588. }, false);
  15589. xhr.addEventListener("error", function (event) {
  15590. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  15591. image.src = url;
  15592. }, false);
  15593. xhr.send();
  15594. }
  15595. else {
  15596. image.src = url;
  15597. }
  15598. }
  15599. else {
  15600. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15601. image.src = url;
  15602. }
  15603. };
  15604. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  15605. var _this = this;
  15606. var updateVersion = function (event) {
  15607. // the version is not yet in the DB or we need to update it
  15608. _this._saveVersionIntoDBAsync(url, versionLoaded);
  15609. };
  15610. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  15611. };
  15612. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  15613. var _this = this;
  15614. if (this.isSupported) {
  15615. var version;
  15616. try {
  15617. var transaction = this.db.transaction(["versions"]);
  15618. transaction.oncomplete = function (event) {
  15619. if (version) {
  15620. // If the version in the JSON file is > than the version in DB
  15621. if (_this.manifestVersionFound > version.data) {
  15622. _this.mustUpdateRessources = true;
  15623. updateInDBCallback();
  15624. }
  15625. else {
  15626. callback(version.data);
  15627. }
  15628. }
  15629. else {
  15630. _this.mustUpdateRessources = true;
  15631. updateInDBCallback();
  15632. }
  15633. };
  15634. transaction.onabort = function (event) {
  15635. callback(-1);
  15636. };
  15637. var getRequest = transaction.objectStore("versions").get(url);
  15638. getRequest.onsuccess = function (event) {
  15639. version = (event.target).result;
  15640. };
  15641. getRequest.onerror = function (event) {
  15642. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  15643. callback(-1);
  15644. };
  15645. }
  15646. catch (ex) {
  15647. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  15648. callback(-1);
  15649. }
  15650. }
  15651. else {
  15652. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15653. callback(-1);
  15654. }
  15655. };
  15656. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  15657. var _this = this;
  15658. if (this.isSupported && !this.hasReachedQuota) {
  15659. try {
  15660. // Open a transaction to the database
  15661. var transaction = this.db.transaction(["versions"], "readwrite");
  15662. // the transaction could abort because of a QuotaExceededError error
  15663. transaction.onabort = function (event) {
  15664. try {
  15665. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15666. _this.hasReachedQuota = true;
  15667. }
  15668. }
  15669. catch (ex) {
  15670. }
  15671. callback(-1);
  15672. };
  15673. transaction.oncomplete = function (event) {
  15674. callback(_this.manifestVersionFound);
  15675. };
  15676. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  15677. // Put the scene into the database
  15678. var addRequest = transaction.objectStore("versions").put(newVersion);
  15679. addRequest.onsuccess = function (event) {
  15680. };
  15681. addRequest.onerror = function (event) {
  15682. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  15683. };
  15684. }
  15685. catch (ex) {
  15686. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  15687. callback(-1);
  15688. }
  15689. }
  15690. else {
  15691. callback(-1);
  15692. }
  15693. };
  15694. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  15695. var _this = this;
  15696. var completeUrl = Database.ReturnFullUrlLocation(url);
  15697. var saveAndLoadFile = function (event) {
  15698. // the scene is not yet in the DB, let's try to save it
  15699. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  15700. };
  15701. this._checkVersionFromDB(completeUrl, function (version) {
  15702. if (version !== -1) {
  15703. if (!_this.mustUpdateRessources) {
  15704. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  15705. }
  15706. else {
  15707. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  15708. }
  15709. }
  15710. else {
  15711. errorCallback();
  15712. }
  15713. });
  15714. };
  15715. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  15716. if (this.isSupported) {
  15717. var targetStore;
  15718. if (url.indexOf(".babylon") !== -1) {
  15719. targetStore = "scenes";
  15720. }
  15721. else {
  15722. targetStore = "textures";
  15723. }
  15724. var file;
  15725. var transaction = this.db.transaction([targetStore]);
  15726. transaction.oncomplete = function (event) {
  15727. if (file) {
  15728. callback(file.data);
  15729. }
  15730. else {
  15731. notInDBCallback();
  15732. }
  15733. };
  15734. transaction.onabort = function (event) {
  15735. notInDBCallback();
  15736. };
  15737. var getRequest = transaction.objectStore(targetStore).get(url);
  15738. getRequest.onsuccess = function (event) {
  15739. file = (event.target).result;
  15740. };
  15741. getRequest.onerror = function (event) {
  15742. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  15743. notInDBCallback();
  15744. };
  15745. }
  15746. else {
  15747. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15748. callback();
  15749. }
  15750. };
  15751. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  15752. var _this = this;
  15753. if (this.isSupported) {
  15754. var targetStore;
  15755. if (url.indexOf(".babylon") !== -1) {
  15756. targetStore = "scenes";
  15757. }
  15758. else {
  15759. targetStore = "textures";
  15760. }
  15761. // Create XHR
  15762. var xhr = new XMLHttpRequest(), fileData;
  15763. xhr.open("GET", url, true);
  15764. if (useArrayBuffer) {
  15765. xhr.responseType = "arraybuffer";
  15766. }
  15767. xhr.onprogress = progressCallback;
  15768. xhr.addEventListener("load", function () {
  15769. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  15770. // Blob as response (XHR2)
  15771. //fileData = xhr.responseText;
  15772. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  15773. if (!_this.hasReachedQuota) {
  15774. // Open a transaction to the database
  15775. var transaction = _this.db.transaction([targetStore], "readwrite");
  15776. // the transaction could abort because of a QuotaExceededError error
  15777. transaction.onabort = function (event) {
  15778. try {
  15779. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15780. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15781. this.hasReachedQuota = true;
  15782. }
  15783. }
  15784. catch (ex) {
  15785. }
  15786. callback(fileData);
  15787. };
  15788. transaction.oncomplete = function (event) {
  15789. callback(fileData);
  15790. };
  15791. var newFile;
  15792. if (targetStore === "scenes") {
  15793. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  15794. }
  15795. else {
  15796. newFile = { textureUrl: url, data: fileData };
  15797. }
  15798. try {
  15799. // Put the scene into the database
  15800. var addRequest = transaction.objectStore(targetStore).put(newFile);
  15801. addRequest.onsuccess = function (event) {
  15802. };
  15803. addRequest.onerror = function (event) {
  15804. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  15805. };
  15806. }
  15807. catch (ex) {
  15808. callback(fileData);
  15809. }
  15810. }
  15811. else {
  15812. callback(fileData);
  15813. }
  15814. }
  15815. else {
  15816. callback();
  15817. }
  15818. }, false);
  15819. xhr.addEventListener("error", function (event) {
  15820. BABYLON.Tools.Error("error on XHR request.");
  15821. callback();
  15822. }, false);
  15823. xhr.send();
  15824. }
  15825. else {
  15826. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15827. callback();
  15828. }
  15829. };
  15830. Database.isUASupportingBlobStorage = true;
  15831. Database.parseURL = function (url) {
  15832. var a = document.createElement('a');
  15833. a.href = url;
  15834. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  15835. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  15836. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  15837. return absLocation;
  15838. };
  15839. Database.ReturnFullUrlLocation = function (url) {
  15840. if (url.indexOf("http:/") === -1) {
  15841. return (BABYLON.Database.parseURL(window.location.href) + url);
  15842. }
  15843. else {
  15844. return url;
  15845. }
  15846. };
  15847. return Database;
  15848. })();
  15849. BABYLON.Database = Database;
  15850. })(BABYLON || (BABYLON = {}));
  15851. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  15852. (function (BABYLON) {
  15853. var SpriteManager = (function () {
  15854. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  15855. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15856. this.name = name;
  15857. this.cellSize = cellSize;
  15858. this.sprites = new Array();
  15859. this.renderingGroupId = 0;
  15860. this.fogEnabled = true;
  15861. this._vertexDeclaration = [4, 4, 4, 4];
  15862. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  15863. this._capacity = capacity;
  15864. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  15865. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15866. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15867. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  15868. this._scene = scene;
  15869. this._scene.spriteManagers.push(this);
  15870. // VBO
  15871. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15872. var indices = [];
  15873. var index = 0;
  15874. for (var count = 0; count < capacity; count++) {
  15875. indices.push(index);
  15876. indices.push(index + 1);
  15877. indices.push(index + 2);
  15878. indices.push(index);
  15879. indices.push(index + 2);
  15880. indices.push(index + 3);
  15881. index += 4;
  15882. }
  15883. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15884. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15885. // Effects
  15886. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  15887. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  15888. }
  15889. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  15890. var arrayOffset = index * 16;
  15891. if (offsetX === 0)
  15892. offsetX = this._epsilon;
  15893. else if (offsetX === 1)
  15894. offsetX = 1 - this._epsilon;
  15895. if (offsetY === 0)
  15896. offsetY = this._epsilon;
  15897. else if (offsetY === 1)
  15898. offsetY = 1 - this._epsilon;
  15899. this._vertices[arrayOffset] = sprite.position.x;
  15900. this._vertices[arrayOffset + 1] = sprite.position.y;
  15901. this._vertices[arrayOffset + 2] = sprite.position.z;
  15902. this._vertices[arrayOffset + 3] = sprite.angle;
  15903. this._vertices[arrayOffset + 4] = sprite.width;
  15904. this._vertices[arrayOffset + 5] = sprite.height;
  15905. this._vertices[arrayOffset + 6] = offsetX;
  15906. this._vertices[arrayOffset + 7] = offsetY;
  15907. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  15908. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  15909. var offset = (sprite.cellIndex / rowSize) >> 0;
  15910. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  15911. this._vertices[arrayOffset + 11] = offset;
  15912. // Color
  15913. this._vertices[arrayOffset + 12] = sprite.color.r;
  15914. this._vertices[arrayOffset + 13] = sprite.color.g;
  15915. this._vertices[arrayOffset + 14] = sprite.color.b;
  15916. this._vertices[arrayOffset + 15] = sprite.color.a;
  15917. };
  15918. SpriteManager.prototype.render = function () {
  15919. // Check
  15920. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  15921. return;
  15922. var engine = this._scene.getEngine();
  15923. var baseSize = this._spriteTexture.getBaseSize();
  15924. // Sprites
  15925. var deltaTime = engine.getDeltaTime();
  15926. var max = Math.min(this._capacity, this.sprites.length);
  15927. var rowSize = baseSize.width / this.cellSize;
  15928. var offset = 0;
  15929. for (var index = 0; index < max; index++) {
  15930. var sprite = this.sprites[index];
  15931. if (!sprite) {
  15932. continue;
  15933. }
  15934. sprite._animate(deltaTime);
  15935. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  15936. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  15937. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  15938. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  15939. }
  15940. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15941. // Render
  15942. var effect = this._effectBase;
  15943. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15944. effect = this._effectFog;
  15945. }
  15946. engine.enableEffect(effect);
  15947. var viewMatrix = this._scene.getViewMatrix();
  15948. effect.setTexture("diffuseSampler", this._spriteTexture);
  15949. effect.setMatrix("view", viewMatrix);
  15950. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15951. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  15952. // Fog
  15953. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15954. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  15955. effect.setColor3("vFogColor", this._scene.fogColor);
  15956. }
  15957. // VBOs
  15958. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15959. // Draw order
  15960. effect.setBool("alphaTest", true);
  15961. engine.setColorWrite(false);
  15962. engine.draw(true, 0, max * 6);
  15963. engine.setColorWrite(true);
  15964. effect.setBool("alphaTest", false);
  15965. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15966. engine.draw(true, 0, max * 6);
  15967. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15968. };
  15969. SpriteManager.prototype.dispose = function () {
  15970. if (this._vertexBuffer) {
  15971. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15972. this._vertexBuffer = null;
  15973. }
  15974. if (this._indexBuffer) {
  15975. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15976. this._indexBuffer = null;
  15977. }
  15978. if (this._spriteTexture) {
  15979. this._spriteTexture.dispose();
  15980. this._spriteTexture = null;
  15981. }
  15982. // Remove from scene
  15983. var index = this._scene.spriteManagers.indexOf(this);
  15984. this._scene.spriteManagers.splice(index, 1);
  15985. // Callback
  15986. if (this.onDispose) {
  15987. this.onDispose();
  15988. }
  15989. };
  15990. return SpriteManager;
  15991. })();
  15992. BABYLON.SpriteManager = SpriteManager;
  15993. })(BABYLON || (BABYLON = {}));
  15994. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  15995. (function (BABYLON) {
  15996. var Sprite = (function () {
  15997. function Sprite(name, manager) {
  15998. this.name = name;
  15999. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16000. this.width = 1.0;
  16001. this.height = 1.0;
  16002. this.angle = 0;
  16003. this.cellIndex = 0;
  16004. this.invertU = 0;
  16005. this.invertV = 0;
  16006. this.animations = new Array();
  16007. this._animationStarted = false;
  16008. this._loopAnimation = false;
  16009. this._fromIndex = 0;
  16010. this._toIndex = 0;
  16011. this._delay = 0;
  16012. this._direction = 1;
  16013. this._frameCount = 0;
  16014. this._time = 0;
  16015. this._manager = manager;
  16016. this._manager.sprites.push(this);
  16017. this.position = BABYLON.Vector3.Zero();
  16018. }
  16019. Object.defineProperty(Sprite.prototype, "size", {
  16020. get: function () {
  16021. return this.width;
  16022. },
  16023. set: function (value) {
  16024. this.width = value;
  16025. this.height = value;
  16026. },
  16027. enumerable: true,
  16028. configurable: true
  16029. });
  16030. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  16031. this._fromIndex = from;
  16032. this._toIndex = to;
  16033. this._loopAnimation = loop;
  16034. this._delay = delay;
  16035. this._animationStarted = true;
  16036. this._direction = from < to ? 1 : -1;
  16037. this.cellIndex = from;
  16038. this._time = 0;
  16039. };
  16040. Sprite.prototype.stopAnimation = function () {
  16041. this._animationStarted = false;
  16042. };
  16043. Sprite.prototype._animate = function (deltaTime) {
  16044. if (!this._animationStarted)
  16045. return;
  16046. this._time += deltaTime;
  16047. if (this._time > this._delay) {
  16048. this._time = this._time % this._delay;
  16049. this.cellIndex += this._direction;
  16050. if (this.cellIndex == this._toIndex) {
  16051. if (this._loopAnimation) {
  16052. this.cellIndex = this._fromIndex;
  16053. }
  16054. else {
  16055. this._animationStarted = false;
  16056. if (this.disposeWhenFinishedAnimating) {
  16057. this.dispose();
  16058. }
  16059. }
  16060. }
  16061. }
  16062. };
  16063. Sprite.prototype.dispose = function () {
  16064. for (var i = 0; i < this._manager.sprites.length; i++) {
  16065. if (this._manager.sprites[i] == this) {
  16066. this._manager.sprites.splice(i, 1);
  16067. }
  16068. }
  16069. };
  16070. return Sprite;
  16071. })();
  16072. BABYLON.Sprite = Sprite;
  16073. })(BABYLON || (BABYLON = {}));
  16074. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  16075. (function (BABYLON) {
  16076. var Layer = (function () {
  16077. function Layer(name, imgUrl, scene, isBackground, color) {
  16078. this.name = name;
  16079. this._vertexDeclaration = [2];
  16080. this._vertexStrideSize = 2 * 4;
  16081. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  16082. this.isBackground = isBackground === undefined ? true : isBackground;
  16083. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  16084. this._scene = scene;
  16085. this._scene.layers.push(this);
  16086. // VBO
  16087. var vertices = [];
  16088. vertices.push(1, 1);
  16089. vertices.push(-1, 1);
  16090. vertices.push(-1, -1);
  16091. vertices.push(1, -1);
  16092. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16093. // Indices
  16094. var indices = [];
  16095. indices.push(0);
  16096. indices.push(1);
  16097. indices.push(2);
  16098. indices.push(0);
  16099. indices.push(2);
  16100. indices.push(3);
  16101. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16102. // Effects
  16103. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  16104. }
  16105. Layer.prototype.render = function () {
  16106. // Check
  16107. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  16108. return;
  16109. var engine = this._scene.getEngine();
  16110. // Render
  16111. engine.enableEffect(this._effect);
  16112. engine.setState(false);
  16113. // Texture
  16114. this._effect.setTexture("textureSampler", this.texture);
  16115. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  16116. // Color
  16117. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  16118. // VBOs
  16119. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16120. // Draw order
  16121. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16122. engine.draw(true, 0, 6);
  16123. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16124. };
  16125. Layer.prototype.dispose = function () {
  16126. if (this._vertexBuffer) {
  16127. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16128. this._vertexBuffer = null;
  16129. }
  16130. if (this._indexBuffer) {
  16131. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16132. this._indexBuffer = null;
  16133. }
  16134. if (this.texture) {
  16135. this.texture.dispose();
  16136. this.texture = null;
  16137. }
  16138. // Remove from scene
  16139. var index = this._scene.layers.indexOf(this);
  16140. this._scene.layers.splice(index, 1);
  16141. // Callback
  16142. if (this.onDispose) {
  16143. this.onDispose();
  16144. }
  16145. };
  16146. return Layer;
  16147. })();
  16148. BABYLON.Layer = Layer;
  16149. })(BABYLON || (BABYLON = {}));
  16150. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  16151. (function (BABYLON) {
  16152. var Particle = (function () {
  16153. function Particle() {
  16154. this.position = BABYLON.Vector3.Zero();
  16155. this.direction = BABYLON.Vector3.Zero();
  16156. this.color = new BABYLON.Color4(0, 0, 0, 0);
  16157. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  16158. this.lifeTime = 1.0;
  16159. this.age = 0;
  16160. this.size = 0;
  16161. this.angle = 0;
  16162. this.angularSpeed = 0;
  16163. }
  16164. Particle.prototype.copyTo = function (other) {
  16165. other.position.copyFrom(this.position);
  16166. other.direction.copyFrom(this.direction);
  16167. other.color.copyFrom(this.color);
  16168. other.colorStep.copyFrom(this.colorStep);
  16169. other.lifeTime = this.lifeTime;
  16170. other.age = this.age;
  16171. other.size = this.size;
  16172. other.angle = this.angle;
  16173. other.angularSpeed = this.angularSpeed;
  16174. };
  16175. return Particle;
  16176. })();
  16177. BABYLON.Particle = Particle;
  16178. })(BABYLON || (BABYLON = {}));
  16179. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  16180. (function (BABYLON) {
  16181. var randomNumber = function (min, max) {
  16182. if (min === max) {
  16183. return (min);
  16184. }
  16185. var random = Math.random();
  16186. return ((random * (max - min)) + min);
  16187. };
  16188. var ParticleSystem = (function () {
  16189. function ParticleSystem(name, capacity, scene, customEffect) {
  16190. var _this = this;
  16191. this.name = name;
  16192. this.renderingGroupId = 0;
  16193. this.emitter = null;
  16194. this.emitRate = 10;
  16195. this.manualEmitCount = -1;
  16196. this.updateSpeed = 0.01;
  16197. this.targetStopDuration = 0;
  16198. this.disposeOnStop = false;
  16199. this.minEmitPower = 1;
  16200. this.maxEmitPower = 1;
  16201. this.minLifeTime = 1;
  16202. this.maxLifeTime = 1;
  16203. this.minSize = 1;
  16204. this.maxSize = 1;
  16205. this.minAngularSpeed = 0;
  16206. this.maxAngularSpeed = 0;
  16207. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  16208. this.forceDepthWrite = false;
  16209. this.gravity = BABYLON.Vector3.Zero();
  16210. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  16211. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  16212. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  16213. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  16214. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16215. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16216. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  16217. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  16218. this.particles = new Array();
  16219. this._vertexDeclaration = [3, 4, 4];
  16220. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  16221. this._stockParticles = new Array();
  16222. this._newPartsExcess = 0;
  16223. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  16224. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  16225. this._scaledDirection = BABYLON.Vector3.Zero();
  16226. this._scaledGravity = BABYLON.Vector3.Zero();
  16227. this._currentRenderId = -1;
  16228. this._started = false;
  16229. this._stopped = false;
  16230. this._actualFrame = 0;
  16231. this.id = name;
  16232. this._capacity = capacity;
  16233. this._scene = scene;
  16234. this._customEffect = customEffect;
  16235. scene.particleSystems.push(this);
  16236. // VBO
  16237. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  16238. var indices = [];
  16239. var index = 0;
  16240. for (var count = 0; count < capacity; count++) {
  16241. indices.push(index);
  16242. indices.push(index + 1);
  16243. indices.push(index + 2);
  16244. indices.push(index);
  16245. indices.push(index + 2);
  16246. indices.push(index + 3);
  16247. index += 4;
  16248. }
  16249. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16250. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  16251. // Default behaviors
  16252. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  16253. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  16254. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  16255. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  16256. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  16257. };
  16258. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  16259. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  16260. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  16261. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  16262. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  16263. };
  16264. this.updateFunction = function (particles) {
  16265. for (var index = 0; index < particles.length; index++) {
  16266. var particle = particles[index];
  16267. particle.age += _this._scaledUpdateSpeed;
  16268. if (particle.age >= particle.lifeTime) {
  16269. _this.recycleParticle(particle);
  16270. index--;
  16271. continue;
  16272. }
  16273. else {
  16274. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  16275. particle.color.addInPlace(_this._scaledColorStep);
  16276. if (particle.color.a < 0)
  16277. particle.color.a = 0;
  16278. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  16279. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  16280. particle.position.addInPlace(_this._scaledDirection);
  16281. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  16282. particle.direction.addInPlace(_this._scaledGravity);
  16283. }
  16284. }
  16285. };
  16286. }
  16287. ParticleSystem.prototype.recycleParticle = function (particle) {
  16288. var lastParticle = this.particles.pop();
  16289. if (lastParticle !== particle) {
  16290. lastParticle.copyTo(particle);
  16291. this._stockParticles.push(lastParticle);
  16292. }
  16293. };
  16294. ParticleSystem.prototype.getCapacity = function () {
  16295. return this._capacity;
  16296. };
  16297. ParticleSystem.prototype.isAlive = function () {
  16298. return this._alive;
  16299. };
  16300. ParticleSystem.prototype.isStarted = function () {
  16301. return this._started;
  16302. };
  16303. ParticleSystem.prototype.start = function () {
  16304. this._started = true;
  16305. this._stopped = false;
  16306. this._actualFrame = 0;
  16307. };
  16308. ParticleSystem.prototype.stop = function () {
  16309. this._stopped = true;
  16310. };
  16311. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  16312. var offset = index * 11;
  16313. this._vertices[offset] = particle.position.x;
  16314. this._vertices[offset + 1] = particle.position.y;
  16315. this._vertices[offset + 2] = particle.position.z;
  16316. this._vertices[offset + 3] = particle.color.r;
  16317. this._vertices[offset + 4] = particle.color.g;
  16318. this._vertices[offset + 5] = particle.color.b;
  16319. this._vertices[offset + 6] = particle.color.a;
  16320. this._vertices[offset + 7] = particle.angle;
  16321. this._vertices[offset + 8] = particle.size;
  16322. this._vertices[offset + 9] = offsetX;
  16323. this._vertices[offset + 10] = offsetY;
  16324. };
  16325. ParticleSystem.prototype._update = function (newParticles) {
  16326. // Update current
  16327. this._alive = this.particles.length > 0;
  16328. this.updateFunction(this.particles);
  16329. // Add new ones
  16330. var worldMatrix;
  16331. if (this.emitter.position) {
  16332. worldMatrix = this.emitter.getWorldMatrix();
  16333. }
  16334. else {
  16335. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  16336. }
  16337. for (var index = 0; index < newParticles; index++) {
  16338. if (this.particles.length === this._capacity) {
  16339. break;
  16340. }
  16341. if (this._stockParticles.length !== 0) {
  16342. var particle = this._stockParticles.pop();
  16343. particle.age = 0;
  16344. }
  16345. else {
  16346. particle = new BABYLON.Particle();
  16347. }
  16348. this.particles.push(particle);
  16349. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  16350. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  16351. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  16352. particle.size = randomNumber(this.minSize, this.maxSize);
  16353. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  16354. this.startPositionFunction(worldMatrix, particle.position);
  16355. var step = randomNumber(0, 1.0);
  16356. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  16357. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  16358. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  16359. }
  16360. };
  16361. ParticleSystem.prototype._getEffect = function () {
  16362. if (this._customEffect) {
  16363. return this._customEffect;
  16364. }
  16365. ;
  16366. var defines = [];
  16367. if (this._scene.clipPlane) {
  16368. defines.push("#define CLIPPLANE");
  16369. }
  16370. // Effect
  16371. var join = defines.join("\n");
  16372. if (this._cachedDefines !== join) {
  16373. this._cachedDefines = join;
  16374. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  16375. }
  16376. return this._effect;
  16377. };
  16378. ParticleSystem.prototype.animate = function () {
  16379. if (!this._started)
  16380. return;
  16381. var effect = this._getEffect();
  16382. // Check
  16383. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  16384. return;
  16385. if (this._currentRenderId === this._scene.getRenderId()) {
  16386. return;
  16387. }
  16388. this._currentRenderId = this._scene.getRenderId();
  16389. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  16390. // determine the number of particles we need to create
  16391. var emitCout;
  16392. if (this.manualEmitCount > -1) {
  16393. emitCout = this.manualEmitCount;
  16394. this.manualEmitCount = 0;
  16395. }
  16396. else {
  16397. emitCout = this.emitRate;
  16398. }
  16399. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  16400. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  16401. if (this._newPartsExcess > 1.0) {
  16402. newParticles += this._newPartsExcess >> 0;
  16403. this._newPartsExcess -= this._newPartsExcess >> 0;
  16404. }
  16405. this._alive = false;
  16406. if (!this._stopped) {
  16407. this._actualFrame += this._scaledUpdateSpeed;
  16408. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  16409. this.stop();
  16410. }
  16411. else {
  16412. newParticles = 0;
  16413. }
  16414. this._update(newParticles);
  16415. // Stopped?
  16416. if (this._stopped) {
  16417. if (!this._alive) {
  16418. this._started = false;
  16419. if (this.disposeOnStop) {
  16420. this._scene._toBeDisposed.push(this);
  16421. }
  16422. }
  16423. }
  16424. // Update VBO
  16425. var offset = 0;
  16426. for (var index = 0; index < this.particles.length; index++) {
  16427. var particle = this.particles[index];
  16428. this._appendParticleVertex(offset++, particle, 0, 0);
  16429. this._appendParticleVertex(offset++, particle, 1, 0);
  16430. this._appendParticleVertex(offset++, particle, 1, 1);
  16431. this._appendParticleVertex(offset++, particle, 0, 1);
  16432. }
  16433. var engine = this._scene.getEngine();
  16434. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  16435. };
  16436. ParticleSystem.prototype.render = function () {
  16437. var effect = this._getEffect();
  16438. // Check
  16439. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  16440. return 0;
  16441. var engine = this._scene.getEngine();
  16442. // Render
  16443. engine.enableEffect(effect);
  16444. engine.setState(false);
  16445. var viewMatrix = this._scene.getViewMatrix();
  16446. effect.setTexture("diffuseSampler", this.particleTexture);
  16447. effect.setMatrix("view", viewMatrix);
  16448. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  16449. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  16450. if (this._scene.clipPlane) {
  16451. var clipPlane = this._scene.clipPlane;
  16452. var invView = viewMatrix.clone();
  16453. invView.invert();
  16454. effect.setMatrix("invView", invView);
  16455. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  16456. }
  16457. // VBOs
  16458. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16459. // Draw order
  16460. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  16461. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  16462. }
  16463. else {
  16464. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16465. }
  16466. if (this.forceDepthWrite) {
  16467. engine.setDepthWrite(true);
  16468. }
  16469. engine.draw(true, 0, this.particles.length * 6);
  16470. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16471. return this.particles.length;
  16472. };
  16473. ParticleSystem.prototype.dispose = function () {
  16474. if (this._vertexBuffer) {
  16475. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16476. this._vertexBuffer = null;
  16477. }
  16478. if (this._indexBuffer) {
  16479. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16480. this._indexBuffer = null;
  16481. }
  16482. if (this.particleTexture) {
  16483. this.particleTexture.dispose();
  16484. this.particleTexture = null;
  16485. }
  16486. // Remove from scene
  16487. var index = this._scene.particleSystems.indexOf(this);
  16488. this._scene.particleSystems.splice(index, 1);
  16489. // Callback
  16490. if (this.onDispose) {
  16491. this.onDispose();
  16492. }
  16493. };
  16494. // Clone
  16495. ParticleSystem.prototype.clone = function (name, newEmitter) {
  16496. var result = new ParticleSystem(name, this._capacity, this._scene);
  16497. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  16498. if (newEmitter === undefined) {
  16499. newEmitter = this.emitter;
  16500. }
  16501. result.emitter = newEmitter;
  16502. if (this.particleTexture) {
  16503. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  16504. }
  16505. result.start();
  16506. return result;
  16507. };
  16508. // Statics
  16509. ParticleSystem.BLENDMODE_ONEONE = 0;
  16510. ParticleSystem.BLENDMODE_STANDARD = 1;
  16511. return ParticleSystem;
  16512. })();
  16513. BABYLON.ParticleSystem = ParticleSystem;
  16514. })(BABYLON || (BABYLON = {}));
  16515. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  16516. (function (BABYLON) {
  16517. var Animation = (function () {
  16518. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  16519. this.name = name;
  16520. this.targetProperty = targetProperty;
  16521. this.framePerSecond = framePerSecond;
  16522. this.dataType = dataType;
  16523. this.loopMode = loopMode;
  16524. this._offsetsCache = {};
  16525. this._highLimitsCache = {};
  16526. this._stopped = false;
  16527. this.targetPropertyPath = targetProperty.split(".");
  16528. this.dataType = dataType;
  16529. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  16530. }
  16531. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  16532. var dataType = undefined;
  16533. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  16534. dataType = Animation.ANIMATIONTYPE_FLOAT;
  16535. }
  16536. else if (from instanceof BABYLON.Quaternion) {
  16537. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  16538. }
  16539. else if (from instanceof BABYLON.Vector3) {
  16540. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  16541. }
  16542. else if (from instanceof BABYLON.Vector2) {
  16543. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  16544. }
  16545. else if (from instanceof BABYLON.Color3) {
  16546. dataType = Animation.ANIMATIONTYPE_COLOR3;
  16547. }
  16548. if (dataType == undefined) {
  16549. return null;
  16550. }
  16551. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  16552. var keys = [];
  16553. keys.push({ frame: 0, value: from });
  16554. keys.push({ frame: totalFrame, value: to });
  16555. animation.setKeys(keys);
  16556. mesh.animations.push(animation);
  16557. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  16558. };
  16559. // Methods
  16560. Animation.prototype.isStopped = function () {
  16561. return this._stopped;
  16562. };
  16563. Animation.prototype.getKeys = function () {
  16564. return this._keys;
  16565. };
  16566. Animation.prototype.getEasingFunction = function () {
  16567. return this._easingFunction;
  16568. };
  16569. Animation.prototype.setEasingFunction = function (easingFunction) {
  16570. this._easingFunction = easingFunction;
  16571. };
  16572. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  16573. return startValue + (endValue - startValue) * gradient;
  16574. };
  16575. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  16576. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  16577. };
  16578. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  16579. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  16580. };
  16581. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  16582. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  16583. };
  16584. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  16585. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  16586. };
  16587. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  16588. var startScale = new BABYLON.Vector3(0, 0, 0);
  16589. var startRotation = new BABYLON.Quaternion();
  16590. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  16591. startValue.decompose(startScale, startRotation, startTranslation);
  16592. var endScale = new BABYLON.Vector3(0, 0, 0);
  16593. var endRotation = new BABYLON.Quaternion();
  16594. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  16595. endValue.decompose(endScale, endRotation, endTranslation);
  16596. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  16597. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  16598. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  16599. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  16600. return result;
  16601. };
  16602. Animation.prototype.clone = function () {
  16603. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  16604. clone.setKeys(this._keys);
  16605. return clone;
  16606. };
  16607. Animation.prototype.setKeys = function (values) {
  16608. this._keys = values.slice(0);
  16609. this._offsetsCache = {};
  16610. this._highLimitsCache = {};
  16611. };
  16612. Animation.prototype._getKeyValue = function (value) {
  16613. if (typeof value === "function") {
  16614. return value();
  16615. }
  16616. return value;
  16617. };
  16618. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  16619. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  16620. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  16621. }
  16622. this.currentFrame = currentFrame;
  16623. // Try to get a hash to find the right key
  16624. 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));
  16625. if (this._keys[startKey].frame >= currentFrame) {
  16626. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  16627. startKey--;
  16628. }
  16629. }
  16630. for (var key = startKey; key < this._keys.length; key++) {
  16631. if (this._keys[key + 1].frame >= currentFrame) {
  16632. var startValue = this._getKeyValue(this._keys[key].value);
  16633. var endValue = this._getKeyValue(this._keys[key + 1].value);
  16634. // gradient : percent of currentFrame between the frame inf and the frame sup
  16635. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  16636. // check for easingFunction and correction of gradient
  16637. if (this._easingFunction != null) {
  16638. gradient = this._easingFunction.ease(gradient);
  16639. }
  16640. switch (this.dataType) {
  16641. case Animation.ANIMATIONTYPE_FLOAT:
  16642. switch (loopMode) {
  16643. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16644. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16645. return this.floatInterpolateFunction(startValue, endValue, gradient);
  16646. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16647. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  16648. }
  16649. break;
  16650. case Animation.ANIMATIONTYPE_QUATERNION:
  16651. var quaternion = null;
  16652. switch (loopMode) {
  16653. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16654. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16655. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  16656. break;
  16657. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16658. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16659. break;
  16660. }
  16661. return quaternion;
  16662. case Animation.ANIMATIONTYPE_VECTOR3:
  16663. switch (loopMode) {
  16664. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16665. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16666. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  16667. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16668. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16669. }
  16670. case Animation.ANIMATIONTYPE_VECTOR2:
  16671. switch (loopMode) {
  16672. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16673. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16674. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  16675. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16676. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16677. }
  16678. case Animation.ANIMATIONTYPE_COLOR3:
  16679. switch (loopMode) {
  16680. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16681. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16682. return this.color3InterpolateFunction(startValue, endValue, gradient);
  16683. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16684. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16685. }
  16686. case Animation.ANIMATIONTYPE_MATRIX:
  16687. switch (loopMode) {
  16688. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16689. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16690. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16691. return startValue;
  16692. }
  16693. default:
  16694. break;
  16695. }
  16696. break;
  16697. }
  16698. }
  16699. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  16700. };
  16701. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  16702. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  16703. this._stopped = true;
  16704. return false;
  16705. }
  16706. var returnValue = true;
  16707. // Adding a start key at frame 0 if missing
  16708. if (this._keys[0].frame !== 0) {
  16709. var newKey = { frame: 0, value: this._keys[0].value };
  16710. this._keys.splice(0, 0, newKey);
  16711. }
  16712. // Check limits
  16713. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  16714. from = this._keys[0].frame;
  16715. }
  16716. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  16717. to = this._keys[this._keys.length - 1].frame;
  16718. }
  16719. // Compute ratio
  16720. var range = to - from;
  16721. var offsetValue;
  16722. // ratio represents the frame delta between from and to
  16723. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  16724. var highLimitValue = 0;
  16725. if (ratio > range && !loop) {
  16726. returnValue = false;
  16727. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  16728. }
  16729. else {
  16730. // Get max value if required
  16731. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  16732. var keyOffset = to.toString() + from.toString();
  16733. if (!this._offsetsCache[keyOffset]) {
  16734. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16735. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16736. switch (this.dataType) {
  16737. case Animation.ANIMATIONTYPE_FLOAT:
  16738. this._offsetsCache[keyOffset] = toValue - fromValue;
  16739. break;
  16740. case Animation.ANIMATIONTYPE_QUATERNION:
  16741. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16742. break;
  16743. case Animation.ANIMATIONTYPE_VECTOR3:
  16744. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16745. case Animation.ANIMATIONTYPE_VECTOR2:
  16746. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16747. case Animation.ANIMATIONTYPE_COLOR3:
  16748. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16749. default:
  16750. break;
  16751. }
  16752. this._highLimitsCache[keyOffset] = toValue;
  16753. }
  16754. highLimitValue = this._highLimitsCache[keyOffset];
  16755. offsetValue = this._offsetsCache[keyOffset];
  16756. }
  16757. }
  16758. if (offsetValue === undefined) {
  16759. switch (this.dataType) {
  16760. case Animation.ANIMATIONTYPE_FLOAT:
  16761. offsetValue = 0;
  16762. break;
  16763. case Animation.ANIMATIONTYPE_QUATERNION:
  16764. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  16765. break;
  16766. case Animation.ANIMATIONTYPE_VECTOR3:
  16767. offsetValue = BABYLON.Vector3.Zero();
  16768. break;
  16769. case Animation.ANIMATIONTYPE_VECTOR2:
  16770. offsetValue = BABYLON.Vector2.Zero();
  16771. break;
  16772. case Animation.ANIMATIONTYPE_COLOR3:
  16773. offsetValue = BABYLON.Color3.Black();
  16774. }
  16775. }
  16776. // Compute value
  16777. var repeatCount = (ratio / range) >> 0;
  16778. var currentFrame = returnValue ? from + ratio % range : to;
  16779. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  16780. // Set value
  16781. if (this.targetPropertyPath.length > 1) {
  16782. var property = this._target[this.targetPropertyPath[0]];
  16783. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  16784. property = property[this.targetPropertyPath[index]];
  16785. }
  16786. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  16787. }
  16788. else {
  16789. this._target[this.targetPropertyPath[0]] = currentValue;
  16790. }
  16791. if (this._target.markAsDirty) {
  16792. this._target.markAsDirty(this.targetProperty);
  16793. }
  16794. if (!returnValue) {
  16795. this._stopped = true;
  16796. }
  16797. return returnValue;
  16798. };
  16799. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  16800. get: function () {
  16801. return Animation._ANIMATIONTYPE_FLOAT;
  16802. },
  16803. enumerable: true,
  16804. configurable: true
  16805. });
  16806. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  16807. get: function () {
  16808. return Animation._ANIMATIONTYPE_VECTOR3;
  16809. },
  16810. enumerable: true,
  16811. configurable: true
  16812. });
  16813. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  16814. get: function () {
  16815. return Animation._ANIMATIONTYPE_VECTOR2;
  16816. },
  16817. enumerable: true,
  16818. configurable: true
  16819. });
  16820. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  16821. get: function () {
  16822. return Animation._ANIMATIONTYPE_QUATERNION;
  16823. },
  16824. enumerable: true,
  16825. configurable: true
  16826. });
  16827. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  16828. get: function () {
  16829. return Animation._ANIMATIONTYPE_MATRIX;
  16830. },
  16831. enumerable: true,
  16832. configurable: true
  16833. });
  16834. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  16835. get: function () {
  16836. return Animation._ANIMATIONTYPE_COLOR3;
  16837. },
  16838. enumerable: true,
  16839. configurable: true
  16840. });
  16841. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  16842. get: function () {
  16843. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  16844. },
  16845. enumerable: true,
  16846. configurable: true
  16847. });
  16848. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  16849. get: function () {
  16850. return Animation._ANIMATIONLOOPMODE_CYCLE;
  16851. },
  16852. enumerable: true,
  16853. configurable: true
  16854. });
  16855. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  16856. get: function () {
  16857. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  16858. },
  16859. enumerable: true,
  16860. configurable: true
  16861. });
  16862. // Statics
  16863. Animation._ANIMATIONTYPE_FLOAT = 0;
  16864. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  16865. Animation._ANIMATIONTYPE_QUATERNION = 2;
  16866. Animation._ANIMATIONTYPE_MATRIX = 3;
  16867. Animation._ANIMATIONTYPE_COLOR3 = 4;
  16868. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  16869. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  16870. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  16871. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  16872. return Animation;
  16873. })();
  16874. BABYLON.Animation = Animation;
  16875. })(BABYLON || (BABYLON = {}));
  16876. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  16877. (function (BABYLON) {
  16878. var Animatable = (function () {
  16879. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  16880. if (fromFrame === void 0) { fromFrame = 0; }
  16881. if (toFrame === void 0) { toFrame = 100; }
  16882. if (loopAnimation === void 0) { loopAnimation = false; }
  16883. if (speedRatio === void 0) { speedRatio = 1.0; }
  16884. this.target = target;
  16885. this.fromFrame = fromFrame;
  16886. this.toFrame = toFrame;
  16887. this.loopAnimation = loopAnimation;
  16888. this.speedRatio = speedRatio;
  16889. this.onAnimationEnd = onAnimationEnd;
  16890. this._animations = new Array();
  16891. this._paused = false;
  16892. this.animationStarted = false;
  16893. if (animations) {
  16894. this.appendAnimations(target, animations);
  16895. }
  16896. this._scene = scene;
  16897. scene._activeAnimatables.push(this);
  16898. }
  16899. // Methods
  16900. Animatable.prototype.appendAnimations = function (target, animations) {
  16901. for (var index = 0; index < animations.length; index++) {
  16902. var animation = animations[index];
  16903. animation._target = target;
  16904. this._animations.push(animation);
  16905. }
  16906. };
  16907. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  16908. var animations = this._animations;
  16909. for (var index = 0; index < animations.length; index++) {
  16910. if (animations[index].targetProperty === property) {
  16911. return animations[index];
  16912. }
  16913. }
  16914. return null;
  16915. };
  16916. Animatable.prototype.pause = function () {
  16917. if (this._paused) {
  16918. return;
  16919. }
  16920. this._paused = true;
  16921. };
  16922. Animatable.prototype.restart = function () {
  16923. this._paused = false;
  16924. };
  16925. Animatable.prototype.stop = function () {
  16926. var index = this._scene._activeAnimatables.indexOf(this);
  16927. if (index > -1) {
  16928. this._scene._activeAnimatables.splice(index, 1);
  16929. }
  16930. if (this.onAnimationEnd) {
  16931. this.onAnimationEnd();
  16932. }
  16933. };
  16934. Animatable.prototype._animate = function (delay) {
  16935. if (this._paused) {
  16936. if (!this._pausedDelay) {
  16937. this._pausedDelay = delay;
  16938. }
  16939. return true;
  16940. }
  16941. if (!this._localDelayOffset) {
  16942. this._localDelayOffset = delay;
  16943. }
  16944. else if (this._pausedDelay) {
  16945. this._localDelayOffset += delay - this._pausedDelay;
  16946. this._pausedDelay = null;
  16947. }
  16948. // Animating
  16949. var running = false;
  16950. var animations = this._animations;
  16951. for (var index = 0; index < animations.length; index++) {
  16952. var animation = animations[index];
  16953. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  16954. running = running || isRunning;
  16955. }
  16956. if (!running) {
  16957. // Remove from active animatables
  16958. index = this._scene._activeAnimatables.indexOf(this);
  16959. this._scene._activeAnimatables.splice(index, 1);
  16960. }
  16961. if (!running && this.onAnimationEnd) {
  16962. this.onAnimationEnd();
  16963. }
  16964. return running;
  16965. };
  16966. return Animatable;
  16967. })();
  16968. BABYLON.Animatable = Animatable;
  16969. })(BABYLON || (BABYLON = {}));
  16970. //# sourceMappingURL=babylon.animatable.js.map
  16971. var BABYLON;
  16972. (function (BABYLON) {
  16973. var EasingFunction = (function () {
  16974. function EasingFunction() {
  16975. // Properties
  16976. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  16977. }
  16978. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  16979. get: function () {
  16980. return EasingFunction._EASINGMODE_EASEIN;
  16981. },
  16982. enumerable: true,
  16983. configurable: true
  16984. });
  16985. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  16986. get: function () {
  16987. return EasingFunction._EASINGMODE_EASEOUT;
  16988. },
  16989. enumerable: true,
  16990. configurable: true
  16991. });
  16992. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  16993. get: function () {
  16994. return EasingFunction._EASINGMODE_EASEINOUT;
  16995. },
  16996. enumerable: true,
  16997. configurable: true
  16998. });
  16999. EasingFunction.prototype.setEasingMode = function (easingMode) {
  17000. var n = Math.min(Math.max(easingMode, 0), 2);
  17001. this._easingMode = n;
  17002. };
  17003. EasingFunction.prototype.getEasingMode = function () {
  17004. return this._easingMode;
  17005. };
  17006. EasingFunction.prototype.easeInCore = function (gradient) {
  17007. throw new Error('You must implement this method');
  17008. };
  17009. EasingFunction.prototype.ease = function (gradient) {
  17010. switch (this._easingMode) {
  17011. case EasingFunction.EASINGMODE_EASEIN:
  17012. return this.easeInCore(gradient);
  17013. case EasingFunction.EASINGMODE_EASEOUT:
  17014. return (1 - this.easeInCore(1 - gradient));
  17015. }
  17016. if (gradient >= 0.5) {
  17017. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  17018. }
  17019. return (this.easeInCore(gradient * 2) * 0.5);
  17020. };
  17021. //Statics
  17022. EasingFunction._EASINGMODE_EASEIN = 0;
  17023. EasingFunction._EASINGMODE_EASEOUT = 1;
  17024. EasingFunction._EASINGMODE_EASEINOUT = 2;
  17025. return EasingFunction;
  17026. })();
  17027. BABYLON.EasingFunction = EasingFunction;
  17028. var CircleEase = (function (_super) {
  17029. __extends(CircleEase, _super);
  17030. function CircleEase() {
  17031. _super.apply(this, arguments);
  17032. }
  17033. CircleEase.prototype.easeInCore = function (gradient) {
  17034. gradient = Math.max(0, Math.min(1, gradient));
  17035. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  17036. };
  17037. return CircleEase;
  17038. })(EasingFunction);
  17039. BABYLON.CircleEase = CircleEase;
  17040. var BackEase = (function (_super) {
  17041. __extends(BackEase, _super);
  17042. function BackEase(amplitude) {
  17043. if (amplitude === void 0) { amplitude = 1; }
  17044. _super.call(this);
  17045. this.amplitude = amplitude;
  17046. }
  17047. BackEase.prototype.easeInCore = function (gradient) {
  17048. var num = Math.max(0, this.amplitude);
  17049. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  17050. };
  17051. return BackEase;
  17052. })(EasingFunction);
  17053. BABYLON.BackEase = BackEase;
  17054. var BounceEase = (function (_super) {
  17055. __extends(BounceEase, _super);
  17056. function BounceEase(bounces, bounciness) {
  17057. if (bounces === void 0) { bounces = 3; }
  17058. if (bounciness === void 0) { bounciness = 2; }
  17059. _super.call(this);
  17060. this.bounces = bounces;
  17061. this.bounciness = bounciness;
  17062. }
  17063. BounceEase.prototype.easeInCore = function (gradient) {
  17064. var y = Math.max(0.0, this.bounces);
  17065. var bounciness = this.bounciness;
  17066. if (bounciness <= 1.0) {
  17067. bounciness = 1.001;
  17068. }
  17069. var num9 = Math.pow(bounciness, y);
  17070. var num5 = 1.0 - bounciness;
  17071. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  17072. var num15 = gradient * num4;
  17073. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  17074. var num3 = Math.floor(num65);
  17075. var num13 = num3 + 1.0;
  17076. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  17077. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  17078. var num7 = (num8 + num12) * 0.5;
  17079. var num6 = gradient - num7;
  17080. var num2 = num7 - num8;
  17081. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  17082. };
  17083. return BounceEase;
  17084. })(EasingFunction);
  17085. BABYLON.BounceEase = BounceEase;
  17086. var CubicEase = (function (_super) {
  17087. __extends(CubicEase, _super);
  17088. function CubicEase() {
  17089. _super.apply(this, arguments);
  17090. }
  17091. CubicEase.prototype.easeInCore = function (gradient) {
  17092. return (gradient * gradient * gradient);
  17093. };
  17094. return CubicEase;
  17095. })(EasingFunction);
  17096. BABYLON.CubicEase = CubicEase;
  17097. var ElasticEase = (function (_super) {
  17098. __extends(ElasticEase, _super);
  17099. function ElasticEase(oscillations, springiness) {
  17100. if (oscillations === void 0) { oscillations = 3; }
  17101. if (springiness === void 0) { springiness = 3; }
  17102. _super.call(this);
  17103. this.oscillations = oscillations;
  17104. this.springiness = springiness;
  17105. }
  17106. ElasticEase.prototype.easeInCore = function (gradient) {
  17107. var num2;
  17108. var num3 = Math.max(0.0, this.oscillations);
  17109. var num = Math.max(0.0, this.springiness);
  17110. if (num == 0) {
  17111. num2 = gradient;
  17112. }
  17113. else {
  17114. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  17115. }
  17116. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  17117. };
  17118. return ElasticEase;
  17119. })(EasingFunction);
  17120. BABYLON.ElasticEase = ElasticEase;
  17121. var ExponentialEase = (function (_super) {
  17122. __extends(ExponentialEase, _super);
  17123. function ExponentialEase(exponent) {
  17124. if (exponent === void 0) { exponent = 2; }
  17125. _super.call(this);
  17126. this.exponent = exponent;
  17127. }
  17128. ExponentialEase.prototype.easeInCore = function (gradient) {
  17129. if (this.exponent <= 0) {
  17130. return gradient;
  17131. }
  17132. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  17133. };
  17134. return ExponentialEase;
  17135. })(EasingFunction);
  17136. BABYLON.ExponentialEase = ExponentialEase;
  17137. var PowerEase = (function (_super) {
  17138. __extends(PowerEase, _super);
  17139. function PowerEase(power) {
  17140. if (power === void 0) { power = 2; }
  17141. _super.call(this);
  17142. this.power = power;
  17143. }
  17144. PowerEase.prototype.easeInCore = function (gradient) {
  17145. var y = Math.max(0.0, this.power);
  17146. return Math.pow(gradient, y);
  17147. };
  17148. return PowerEase;
  17149. })(EasingFunction);
  17150. BABYLON.PowerEase = PowerEase;
  17151. var QuadraticEase = (function (_super) {
  17152. __extends(QuadraticEase, _super);
  17153. function QuadraticEase() {
  17154. _super.apply(this, arguments);
  17155. }
  17156. QuadraticEase.prototype.easeInCore = function (gradient) {
  17157. return (gradient * gradient);
  17158. };
  17159. return QuadraticEase;
  17160. })(EasingFunction);
  17161. BABYLON.QuadraticEase = QuadraticEase;
  17162. var QuarticEase = (function (_super) {
  17163. __extends(QuarticEase, _super);
  17164. function QuarticEase() {
  17165. _super.apply(this, arguments);
  17166. }
  17167. QuarticEase.prototype.easeInCore = function (gradient) {
  17168. return (gradient * gradient * gradient * gradient);
  17169. };
  17170. return QuarticEase;
  17171. })(EasingFunction);
  17172. BABYLON.QuarticEase = QuarticEase;
  17173. var QuinticEase = (function (_super) {
  17174. __extends(QuinticEase, _super);
  17175. function QuinticEase() {
  17176. _super.apply(this, arguments);
  17177. }
  17178. QuinticEase.prototype.easeInCore = function (gradient) {
  17179. return (gradient * gradient * gradient * gradient * gradient);
  17180. };
  17181. return QuinticEase;
  17182. })(EasingFunction);
  17183. BABYLON.QuinticEase = QuinticEase;
  17184. var SineEase = (function (_super) {
  17185. __extends(SineEase, _super);
  17186. function SineEase() {
  17187. _super.apply(this, arguments);
  17188. }
  17189. SineEase.prototype.easeInCore = function (gradient) {
  17190. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  17191. };
  17192. return SineEase;
  17193. })(EasingFunction);
  17194. BABYLON.SineEase = SineEase;
  17195. var BezierCurveEase = (function (_super) {
  17196. __extends(BezierCurveEase, _super);
  17197. function BezierCurveEase(x1, y1, x2, y2) {
  17198. if (x1 === void 0) { x1 = 0; }
  17199. if (y1 === void 0) { y1 = 0; }
  17200. if (x2 === void 0) { x2 = 1; }
  17201. if (y2 === void 0) { y2 = 1; }
  17202. _super.call(this);
  17203. this.x1 = x1;
  17204. this.y1 = y1;
  17205. this.x2 = x2;
  17206. this.y2 = y2;
  17207. }
  17208. BezierCurveEase.prototype.easeInCore = function (gradient) {
  17209. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  17210. };
  17211. return BezierCurveEase;
  17212. })(EasingFunction);
  17213. BABYLON.BezierCurveEase = BezierCurveEase;
  17214. })(BABYLON || (BABYLON = {}));
  17215. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  17216. (function (BABYLON) {
  17217. var Octree = (function () {
  17218. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  17219. if (maxDepth === void 0) { maxDepth = 2; }
  17220. this.maxDepth = maxDepth;
  17221. this.dynamicContent = new Array();
  17222. this._maxBlockCapacity = maxBlockCapacity || 64;
  17223. this._selectionContent = new BABYLON.SmartArray(1024);
  17224. this._creationFunc = creationFunc;
  17225. }
  17226. // Methods
  17227. Octree.prototype.update = function (worldMin, worldMax, entries) {
  17228. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  17229. };
  17230. Octree.prototype.addMesh = function (entry) {
  17231. for (var index = 0; index < this.blocks.length; index++) {
  17232. var block = this.blocks[index];
  17233. block.addEntry(entry);
  17234. }
  17235. };
  17236. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  17237. this._selectionContent.reset();
  17238. for (var index = 0; index < this.blocks.length; index++) {
  17239. var block = this.blocks[index];
  17240. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  17241. }
  17242. if (allowDuplicate) {
  17243. this._selectionContent.concat(this.dynamicContent);
  17244. }
  17245. else {
  17246. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  17247. }
  17248. return this._selectionContent;
  17249. };
  17250. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  17251. this._selectionContent.reset();
  17252. for (var index = 0; index < this.blocks.length; index++) {
  17253. var block = this.blocks[index];
  17254. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  17255. }
  17256. if (allowDuplicate) {
  17257. this._selectionContent.concat(this.dynamicContent);
  17258. }
  17259. else {
  17260. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  17261. }
  17262. return this._selectionContent;
  17263. };
  17264. Octree.prototype.intersectsRay = function (ray) {
  17265. this._selectionContent.reset();
  17266. for (var index = 0; index < this.blocks.length; index++) {
  17267. var block = this.blocks[index];
  17268. block.intersectsRay(ray, this._selectionContent);
  17269. }
  17270. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  17271. return this._selectionContent;
  17272. };
  17273. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  17274. target.blocks = new Array();
  17275. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  17276. for (var x = 0; x < 2; x++) {
  17277. for (var y = 0; y < 2; y++) {
  17278. for (var z = 0; z < 2; z++) {
  17279. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  17280. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  17281. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  17282. block.addEntries(entries);
  17283. target.blocks.push(block);
  17284. }
  17285. }
  17286. }
  17287. };
  17288. Octree.CreationFuncForMeshes = function (entry, block) {
  17289. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  17290. block.entries.push(entry);
  17291. }
  17292. };
  17293. Octree.CreationFuncForSubMeshes = function (entry, block) {
  17294. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  17295. block.entries.push(entry);
  17296. }
  17297. };
  17298. return Octree;
  17299. })();
  17300. BABYLON.Octree = Octree;
  17301. })(BABYLON || (BABYLON = {}));
  17302. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  17303. (function (BABYLON) {
  17304. var OctreeBlock = (function () {
  17305. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  17306. this.entries = new Array();
  17307. this._boundingVectors = new Array();
  17308. this._capacity = capacity;
  17309. this._depth = depth;
  17310. this._maxDepth = maxDepth;
  17311. this._creationFunc = creationFunc;
  17312. this._minPoint = minPoint;
  17313. this._maxPoint = maxPoint;
  17314. this._boundingVectors.push(minPoint.clone());
  17315. this._boundingVectors.push(maxPoint.clone());
  17316. this._boundingVectors.push(minPoint.clone());
  17317. this._boundingVectors[2].x = maxPoint.x;
  17318. this._boundingVectors.push(minPoint.clone());
  17319. this._boundingVectors[3].y = maxPoint.y;
  17320. this._boundingVectors.push(minPoint.clone());
  17321. this._boundingVectors[4].z = maxPoint.z;
  17322. this._boundingVectors.push(maxPoint.clone());
  17323. this._boundingVectors[5].z = minPoint.z;
  17324. this._boundingVectors.push(maxPoint.clone());
  17325. this._boundingVectors[6].x = minPoint.x;
  17326. this._boundingVectors.push(maxPoint.clone());
  17327. this._boundingVectors[7].y = minPoint.y;
  17328. }
  17329. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  17330. // Property
  17331. get: function () {
  17332. return this._capacity;
  17333. },
  17334. enumerable: true,
  17335. configurable: true
  17336. });
  17337. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  17338. get: function () {
  17339. return this._minPoint;
  17340. },
  17341. enumerable: true,
  17342. configurable: true
  17343. });
  17344. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  17345. get: function () {
  17346. return this._maxPoint;
  17347. },
  17348. enumerable: true,
  17349. configurable: true
  17350. });
  17351. // Methods
  17352. OctreeBlock.prototype.addEntry = function (entry) {
  17353. if (this.blocks) {
  17354. for (var index = 0; index < this.blocks.length; index++) {
  17355. var block = this.blocks[index];
  17356. block.addEntry(entry);
  17357. }
  17358. return;
  17359. }
  17360. this._creationFunc(entry, this);
  17361. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  17362. this.createInnerBlocks();
  17363. }
  17364. };
  17365. OctreeBlock.prototype.addEntries = function (entries) {
  17366. for (var index = 0; index < entries.length; index++) {
  17367. var mesh = entries[index];
  17368. this.addEntry(mesh);
  17369. }
  17370. };
  17371. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  17372. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  17373. if (this.blocks) {
  17374. for (var index = 0; index < this.blocks.length; index++) {
  17375. var block = this.blocks[index];
  17376. block.select(frustumPlanes, selection, allowDuplicate);
  17377. }
  17378. return;
  17379. }
  17380. if (allowDuplicate) {
  17381. selection.concat(this.entries);
  17382. }
  17383. else {
  17384. selection.concatWithNoDuplicate(this.entries);
  17385. }
  17386. }
  17387. };
  17388. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  17389. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  17390. if (this.blocks) {
  17391. for (var index = 0; index < this.blocks.length; index++) {
  17392. var block = this.blocks[index];
  17393. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  17394. }
  17395. return;
  17396. }
  17397. if (allowDuplicate) {
  17398. selection.concat(this.entries);
  17399. }
  17400. else {
  17401. selection.concatWithNoDuplicate(this.entries);
  17402. }
  17403. }
  17404. };
  17405. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  17406. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  17407. if (this.blocks) {
  17408. for (var index = 0; index < this.blocks.length; index++) {
  17409. var block = this.blocks[index];
  17410. block.intersectsRay(ray, selection);
  17411. }
  17412. return;
  17413. }
  17414. selection.concatWithNoDuplicate(this.entries);
  17415. }
  17416. };
  17417. OctreeBlock.prototype.createInnerBlocks = function () {
  17418. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  17419. };
  17420. return OctreeBlock;
  17421. })();
  17422. BABYLON.OctreeBlock = OctreeBlock;
  17423. })(BABYLON || (BABYLON = {}));
  17424. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  17425. (function (BABYLON) {
  17426. var Bone = (function () {
  17427. function Bone(name, skeleton, parentBone, matrix) {
  17428. this.name = name;
  17429. this.children = new Array();
  17430. this.animations = new Array();
  17431. this._worldTransform = new BABYLON.Matrix();
  17432. this._absoluteTransform = new BABYLON.Matrix();
  17433. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  17434. this._skeleton = skeleton;
  17435. this._matrix = matrix;
  17436. this._baseMatrix = matrix;
  17437. skeleton.bones.push(this);
  17438. if (parentBone) {
  17439. this._parent = parentBone;
  17440. parentBone.children.push(this);
  17441. }
  17442. else {
  17443. this._parent = null;
  17444. }
  17445. this._updateDifferenceMatrix();
  17446. }
  17447. // Members
  17448. Bone.prototype.getParent = function () {
  17449. return this._parent;
  17450. };
  17451. Bone.prototype.getLocalMatrix = function () {
  17452. return this._matrix;
  17453. };
  17454. Bone.prototype.getBaseMatrix = function () {
  17455. return this._baseMatrix;
  17456. };
  17457. Bone.prototype.getWorldMatrix = function () {
  17458. return this._worldTransform;
  17459. };
  17460. Bone.prototype.getInvertedAbsoluteTransform = function () {
  17461. return this._invertedAbsoluteTransform;
  17462. };
  17463. Bone.prototype.getAbsoluteMatrix = function () {
  17464. var matrix = this._matrix.clone();
  17465. var parent = this._parent;
  17466. while (parent) {
  17467. matrix = matrix.multiply(parent.getLocalMatrix());
  17468. parent = parent.getParent();
  17469. }
  17470. return matrix;
  17471. };
  17472. // Methods
  17473. Bone.prototype.updateMatrix = function (matrix) {
  17474. this._matrix = matrix;
  17475. this._skeleton._markAsDirty();
  17476. this._updateDifferenceMatrix();
  17477. };
  17478. Bone.prototype._updateDifferenceMatrix = function () {
  17479. if (this._parent) {
  17480. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  17481. }
  17482. else {
  17483. this._absoluteTransform.copyFrom(this._matrix);
  17484. }
  17485. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  17486. for (var index = 0; index < this.children.length; index++) {
  17487. this.children[index]._updateDifferenceMatrix();
  17488. }
  17489. };
  17490. Bone.prototype.markAsDirty = function () {
  17491. this._skeleton._markAsDirty();
  17492. };
  17493. return Bone;
  17494. })();
  17495. BABYLON.Bone = Bone;
  17496. })(BABYLON || (BABYLON = {}));
  17497. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  17498. (function (BABYLON) {
  17499. var Skeleton = (function () {
  17500. function Skeleton(name, id, scene) {
  17501. this.name = name;
  17502. this.id = id;
  17503. this.bones = new Array();
  17504. this._isDirty = true;
  17505. this._identity = BABYLON.Matrix.Identity();
  17506. this.bones = [];
  17507. this._scene = scene;
  17508. scene.skeletons.push(this);
  17509. this.prepare();
  17510. //make sure it will recalculate the matrix next time prepare is called.
  17511. this._isDirty = true;
  17512. }
  17513. // Members
  17514. Skeleton.prototype.getTransformMatrices = function () {
  17515. return this._transformMatrices;
  17516. };
  17517. // Methods
  17518. Skeleton.prototype._markAsDirty = function () {
  17519. this._isDirty = true;
  17520. };
  17521. Skeleton.prototype.prepare = function () {
  17522. if (!this._isDirty) {
  17523. return;
  17524. }
  17525. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  17526. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  17527. }
  17528. for (var index = 0; index < this.bones.length; index++) {
  17529. var bone = this.bones[index];
  17530. var parentBone = bone.getParent();
  17531. if (parentBone) {
  17532. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  17533. }
  17534. else {
  17535. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  17536. }
  17537. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  17538. }
  17539. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  17540. this._isDirty = false;
  17541. this._scene._activeBones += this.bones.length;
  17542. };
  17543. Skeleton.prototype.getAnimatables = function () {
  17544. if (!this._animatables || this._animatables.length !== this.bones.length) {
  17545. this._animatables = [];
  17546. for (var index = 0; index < this.bones.length; index++) {
  17547. this._animatables.push(this.bones[index]);
  17548. }
  17549. }
  17550. return this._animatables;
  17551. };
  17552. Skeleton.prototype.clone = function (name, id) {
  17553. var result = new Skeleton(name, id || name, this._scene);
  17554. for (var index = 0; index < this.bones.length; index++) {
  17555. var source = this.bones[index];
  17556. var parentBone = null;
  17557. if (source.getParent()) {
  17558. var parentIndex = this.bones.indexOf(source.getParent());
  17559. parentBone = result.bones[parentIndex];
  17560. }
  17561. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  17562. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  17563. }
  17564. return result;
  17565. };
  17566. return Skeleton;
  17567. })();
  17568. BABYLON.Skeleton = Skeleton;
  17569. })(BABYLON || (BABYLON = {}));
  17570. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  17571. (function (BABYLON) {
  17572. var PostProcess = (function () {
  17573. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  17574. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  17575. this.name = name;
  17576. this.width = -1;
  17577. this.height = -1;
  17578. this._reusable = false;
  17579. this._textures = new BABYLON.SmartArray(2);
  17580. this._currentRenderTextureInd = 0;
  17581. if (camera != null) {
  17582. this._camera = camera;
  17583. this._scene = camera.getScene();
  17584. camera.attachPostProcess(this);
  17585. this._engine = this._scene.getEngine();
  17586. }
  17587. else {
  17588. this._engine = engine;
  17589. }
  17590. this._renderRatio = ratio;
  17591. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  17592. this._reusable = reusable || false;
  17593. samplers = samplers || [];
  17594. samplers.push("textureSampler");
  17595. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  17596. }
  17597. PostProcess.prototype.isReusable = function () {
  17598. return this._reusable;
  17599. };
  17600. PostProcess.prototype.activate = function (camera, sourceTexture) {
  17601. camera = camera || this._camera;
  17602. var scene = camera.getScene();
  17603. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  17604. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  17605. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  17606. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  17607. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  17608. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  17609. if (this._textures.length > 0) {
  17610. for (var i = 0; i < this._textures.length; i++) {
  17611. this._engine._releaseTexture(this._textures.data[i]);
  17612. }
  17613. this._textures.reset();
  17614. }
  17615. this.width = desiredWidth;
  17616. this.height = desiredHeight;
  17617. 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 }));
  17618. if (this._reusable) {
  17619. 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 }));
  17620. }
  17621. if (this.onSizeChanged) {
  17622. this.onSizeChanged();
  17623. }
  17624. }
  17625. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  17626. if (this.onActivate) {
  17627. this.onActivate(camera);
  17628. }
  17629. // Clear
  17630. if (this.clearColor) {
  17631. this._engine.clear(this.clearColor, true, true);
  17632. }
  17633. else {
  17634. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  17635. }
  17636. if (this._reusable) {
  17637. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  17638. }
  17639. };
  17640. PostProcess.prototype.apply = function () {
  17641. // Check
  17642. if (!this._effect.isReady())
  17643. return null;
  17644. // States
  17645. this._engine.enableEffect(this._effect);
  17646. this._engine.setState(false);
  17647. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17648. this._engine.setDepthBuffer(false);
  17649. this._engine.setDepthWrite(false);
  17650. // Texture
  17651. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  17652. // Parameters
  17653. if (this.onApply) {
  17654. this.onApply(this._effect);
  17655. }
  17656. return this._effect;
  17657. };
  17658. PostProcess.prototype.dispose = function (camera) {
  17659. camera = camera || this._camera;
  17660. if (this._textures.length > 0) {
  17661. for (var i = 0; i < this._textures.length; i++) {
  17662. this._engine._releaseTexture(this._textures.data[i]);
  17663. }
  17664. this._textures.reset();
  17665. }
  17666. if (!camera) {
  17667. return;
  17668. }
  17669. camera.detachPostProcess(this);
  17670. var index = camera._postProcesses.indexOf(this);
  17671. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  17672. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  17673. }
  17674. };
  17675. return PostProcess;
  17676. })();
  17677. BABYLON.PostProcess = PostProcess;
  17678. })(BABYLON || (BABYLON = {}));
  17679. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  17680. (function (BABYLON) {
  17681. var PostProcessManager = (function () {
  17682. function PostProcessManager(scene) {
  17683. this._vertexDeclaration = [2];
  17684. this._vertexStrideSize = 2 * 4;
  17685. this._scene = scene;
  17686. }
  17687. PostProcessManager.prototype._prepareBuffers = function () {
  17688. if (this._vertexBuffer) {
  17689. return;
  17690. }
  17691. // VBO
  17692. var vertices = [];
  17693. vertices.push(1, 1);
  17694. vertices.push(-1, 1);
  17695. vertices.push(-1, -1);
  17696. vertices.push(1, -1);
  17697. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  17698. // Indices
  17699. var indices = [];
  17700. indices.push(0);
  17701. indices.push(1);
  17702. indices.push(2);
  17703. indices.push(0);
  17704. indices.push(2);
  17705. indices.push(3);
  17706. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  17707. };
  17708. // Methods
  17709. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  17710. var postProcesses = this._scene.activeCamera._postProcesses;
  17711. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17712. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17713. return false;
  17714. }
  17715. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  17716. return true;
  17717. };
  17718. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  17719. var engine = this._scene.getEngine();
  17720. for (var index = 0; index < postProcesses.length; index++) {
  17721. if (index < postProcesses.length - 1) {
  17722. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  17723. }
  17724. else {
  17725. if (targetTexture) {
  17726. engine.bindFramebuffer(targetTexture);
  17727. }
  17728. else {
  17729. engine.restoreDefaultFramebuffer();
  17730. }
  17731. }
  17732. var pp = postProcesses[index];
  17733. var effect = pp.apply();
  17734. if (effect) {
  17735. if (pp.onBeforeRender) {
  17736. pp.onBeforeRender(effect);
  17737. }
  17738. // VBOs
  17739. this._prepareBuffers();
  17740. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17741. // Draw order
  17742. engine.draw(true, 0, 6);
  17743. }
  17744. }
  17745. // Restore depth buffer
  17746. engine.setDepthBuffer(true);
  17747. engine.setDepthWrite(true);
  17748. };
  17749. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  17750. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  17751. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17752. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17753. return;
  17754. }
  17755. var engine = this._scene.getEngine();
  17756. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  17757. if (index < postProcessesTakenIndices.length - 1) {
  17758. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  17759. }
  17760. else {
  17761. if (targetTexture) {
  17762. engine.bindFramebuffer(targetTexture);
  17763. }
  17764. else {
  17765. engine.restoreDefaultFramebuffer();
  17766. }
  17767. }
  17768. if (doNotPresent) {
  17769. break;
  17770. }
  17771. var pp = postProcesses[postProcessesTakenIndices[index]];
  17772. var effect = pp.apply();
  17773. if (effect) {
  17774. if (pp.onBeforeRender) {
  17775. pp.onBeforeRender(effect);
  17776. }
  17777. // VBOs
  17778. this._prepareBuffers();
  17779. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17780. // Draw order
  17781. engine.draw(true, 0, 6);
  17782. }
  17783. }
  17784. // Restore depth buffer
  17785. engine.setDepthBuffer(true);
  17786. engine.setDepthWrite(true);
  17787. };
  17788. PostProcessManager.prototype.dispose = function () {
  17789. if (this._vertexBuffer) {
  17790. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17791. this._vertexBuffer = null;
  17792. }
  17793. if (this._indexBuffer) {
  17794. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17795. this._indexBuffer = null;
  17796. }
  17797. };
  17798. return PostProcessManager;
  17799. })();
  17800. BABYLON.PostProcessManager = PostProcessManager;
  17801. })(BABYLON || (BABYLON = {}));
  17802. //# sourceMappingURL=babylon.postProcessManager.js.map
  17803. var BABYLON;
  17804. (function (BABYLON) {
  17805. var PassPostProcess = (function (_super) {
  17806. __extends(PassPostProcess, _super);
  17807. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17808. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  17809. }
  17810. return PassPostProcess;
  17811. })(BABYLON.PostProcess);
  17812. BABYLON.PassPostProcess = PassPostProcess;
  17813. })(BABYLON || (BABYLON = {}));
  17814. //# sourceMappingURL=babylon.passPostProcess.js.map
  17815. var BABYLON;
  17816. (function (BABYLON) {
  17817. var BlurPostProcess = (function (_super) {
  17818. __extends(BlurPostProcess, _super);
  17819. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  17820. var _this = this;
  17821. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  17822. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  17823. this.direction = direction;
  17824. this.blurWidth = blurWidth;
  17825. this.onApply = function (effect) {
  17826. effect.setFloat2("screenSize", _this.width, _this.height);
  17827. effect.setVector2("direction", _this.direction);
  17828. effect.setFloat("blurWidth", _this.blurWidth);
  17829. };
  17830. }
  17831. return BlurPostProcess;
  17832. })(BABYLON.PostProcess);
  17833. BABYLON.BlurPostProcess = BlurPostProcess;
  17834. })(BABYLON || (BABYLON = {}));
  17835. //# sourceMappingURL=babylon.blurPostProcess.js.map
  17836. var BABYLON;
  17837. (function (BABYLON) {
  17838. var FilterPostProcess = (function (_super) {
  17839. __extends(FilterPostProcess, _super);
  17840. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  17841. var _this = this;
  17842. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  17843. this.kernelMatrix = kernelMatrix;
  17844. this.onApply = function (effect) {
  17845. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  17846. };
  17847. }
  17848. return FilterPostProcess;
  17849. })(BABYLON.PostProcess);
  17850. BABYLON.FilterPostProcess = FilterPostProcess;
  17851. })(BABYLON || (BABYLON = {}));
  17852. //# sourceMappingURL=babylon.filterPostProcess.js.map
  17853. var BABYLON;
  17854. (function (BABYLON) {
  17855. var RefractionPostProcess = (function (_super) {
  17856. __extends(RefractionPostProcess, _super);
  17857. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  17858. var _this = this;
  17859. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  17860. this.color = color;
  17861. this.depth = depth;
  17862. this.colorLevel = colorLevel;
  17863. this.onActivate = function (cam) {
  17864. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  17865. };
  17866. this.onApply = function (effect) {
  17867. effect.setColor3("baseColor", _this.color);
  17868. effect.setFloat("depth", _this.depth);
  17869. effect.setFloat("colorLevel", _this.colorLevel);
  17870. effect.setTexture("refractionSampler", _this._refRexture);
  17871. };
  17872. }
  17873. // Methods
  17874. RefractionPostProcess.prototype.dispose = function (camera) {
  17875. if (this._refRexture) {
  17876. this._refRexture.dispose();
  17877. }
  17878. _super.prototype.dispose.call(this, camera);
  17879. };
  17880. return RefractionPostProcess;
  17881. })(BABYLON.PostProcess);
  17882. BABYLON.RefractionPostProcess = RefractionPostProcess;
  17883. })(BABYLON || (BABYLON = {}));
  17884. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  17885. var BABYLON;
  17886. (function (BABYLON) {
  17887. var BlackAndWhitePostProcess = (function (_super) {
  17888. __extends(BlackAndWhitePostProcess, _super);
  17889. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17890. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  17891. }
  17892. return BlackAndWhitePostProcess;
  17893. })(BABYLON.PostProcess);
  17894. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  17895. })(BABYLON || (BABYLON = {}));
  17896. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  17897. var BABYLON;
  17898. (function (BABYLON) {
  17899. var ConvolutionPostProcess = (function (_super) {
  17900. __extends(ConvolutionPostProcess, _super);
  17901. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  17902. var _this = this;
  17903. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  17904. this.kernel = kernel;
  17905. this.onApply = function (effect) {
  17906. effect.setFloat2("screenSize", _this.width, _this.height);
  17907. effect.setArray("kernel", _this.kernel);
  17908. };
  17909. }
  17910. // Statics
  17911. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  17912. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  17913. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  17914. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  17915. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  17916. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  17917. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  17918. return ConvolutionPostProcess;
  17919. })(BABYLON.PostProcess);
  17920. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  17921. })(BABYLON || (BABYLON = {}));
  17922. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  17923. var BABYLON;
  17924. (function (BABYLON) {
  17925. var FxaaPostProcess = (function (_super) {
  17926. __extends(FxaaPostProcess, _super);
  17927. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17928. var _this = this;
  17929. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  17930. this.onSizeChanged = function () {
  17931. _this.texelWidth = 1.0 / _this.width;
  17932. _this.texelHeight = 1.0 / _this.height;
  17933. };
  17934. this.onApply = function (effect) {
  17935. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  17936. };
  17937. }
  17938. return FxaaPostProcess;
  17939. })(BABYLON.PostProcess);
  17940. BABYLON.FxaaPostProcess = FxaaPostProcess;
  17941. })(BABYLON || (BABYLON = {}));
  17942. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  17943. (function (BABYLON) {
  17944. var LensFlare = (function () {
  17945. function LensFlare(size, position, color, imgUrl, system) {
  17946. this.size = size;
  17947. this.position = position;
  17948. this.dispose = function () {
  17949. if (this.texture) {
  17950. this.texture.dispose();
  17951. }
  17952. // Remove from scene
  17953. var index = this._system.lensFlares.indexOf(this);
  17954. this._system.lensFlares.splice(index, 1);
  17955. };
  17956. this.color = color || new BABYLON.Color3(1, 1, 1);
  17957. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  17958. this._system = system;
  17959. system.lensFlares.push(this);
  17960. }
  17961. return LensFlare;
  17962. })();
  17963. BABYLON.LensFlare = LensFlare;
  17964. })(BABYLON || (BABYLON = {}));
  17965. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  17966. (function (BABYLON) {
  17967. var LensFlareSystem = (function () {
  17968. function LensFlareSystem(name, emitter, scene) {
  17969. this.name = name;
  17970. this.lensFlares = new Array();
  17971. this.borderLimit = 300;
  17972. this._vertexDeclaration = [2];
  17973. this._vertexStrideSize = 2 * 4;
  17974. this._isEnabled = true;
  17975. this._scene = scene;
  17976. this._emitter = emitter;
  17977. scene.lensFlareSystems.push(this);
  17978. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  17979. // VBO
  17980. var vertices = [];
  17981. vertices.push(1, 1);
  17982. vertices.push(-1, 1);
  17983. vertices.push(-1, -1);
  17984. vertices.push(1, -1);
  17985. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17986. // Indices
  17987. var indices = [];
  17988. indices.push(0);
  17989. indices.push(1);
  17990. indices.push(2);
  17991. indices.push(0);
  17992. indices.push(2);
  17993. indices.push(3);
  17994. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17995. // Effects
  17996. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  17997. }
  17998. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  17999. get: function () {
  18000. return this._isEnabled;
  18001. },
  18002. set: function (value) {
  18003. this._isEnabled = value;
  18004. },
  18005. enumerable: true,
  18006. configurable: true
  18007. });
  18008. LensFlareSystem.prototype.getScene = function () {
  18009. return this._scene;
  18010. };
  18011. LensFlareSystem.prototype.getEmitter = function () {
  18012. return this._emitter;
  18013. };
  18014. LensFlareSystem.prototype.getEmitterPosition = function () {
  18015. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  18016. };
  18017. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  18018. var position = this.getEmitterPosition();
  18019. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  18020. this._positionX = position.x;
  18021. this._positionY = position.y;
  18022. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  18023. if (position.z > 0) {
  18024. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  18025. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  18026. return true;
  18027. }
  18028. }
  18029. return false;
  18030. };
  18031. LensFlareSystem.prototype._isVisible = function () {
  18032. if (!this._isEnabled) {
  18033. return false;
  18034. }
  18035. var emitterPosition = this.getEmitterPosition();
  18036. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  18037. var distance = direction.length();
  18038. direction.normalize();
  18039. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  18040. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  18041. return !pickInfo.hit || pickInfo.distance > distance;
  18042. };
  18043. LensFlareSystem.prototype.render = function () {
  18044. if (!this._effect.isReady())
  18045. return false;
  18046. var engine = this._scene.getEngine();
  18047. var viewport = this._scene.activeCamera.viewport;
  18048. var globalViewport = viewport.toGlobal(engine);
  18049. // Position
  18050. if (!this.computeEffectivePosition(globalViewport)) {
  18051. return false;
  18052. }
  18053. // Visibility
  18054. if (!this._isVisible()) {
  18055. return false;
  18056. }
  18057. // Intensity
  18058. var awayX;
  18059. var awayY;
  18060. if (this._positionX < this.borderLimit + globalViewport.x) {
  18061. awayX = this.borderLimit + globalViewport.x - this._positionX;
  18062. }
  18063. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  18064. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  18065. }
  18066. else {
  18067. awayX = 0;
  18068. }
  18069. if (this._positionY < this.borderLimit + globalViewport.y) {
  18070. awayY = this.borderLimit + globalViewport.y - this._positionY;
  18071. }
  18072. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  18073. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  18074. }
  18075. else {
  18076. awayY = 0;
  18077. }
  18078. var away = (awayX > awayY) ? awayX : awayY;
  18079. if (away > this.borderLimit) {
  18080. away = this.borderLimit;
  18081. }
  18082. var intensity = 1.0 - (away / this.borderLimit);
  18083. if (intensity < 0) {
  18084. return false;
  18085. }
  18086. if (intensity > 1.0) {
  18087. intensity = 1.0;
  18088. }
  18089. // Position
  18090. var centerX = globalViewport.x + globalViewport.width / 2;
  18091. var centerY = globalViewport.y + globalViewport.height / 2;
  18092. var distX = centerX - this._positionX;
  18093. var distY = centerY - this._positionY;
  18094. // Effects
  18095. engine.enableEffect(this._effect);
  18096. engine.setState(false);
  18097. engine.setDepthBuffer(false);
  18098. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  18099. // VBOs
  18100. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  18101. for (var index = 0; index < this.lensFlares.length; index++) {
  18102. var flare = this.lensFlares[index];
  18103. var x = centerX - (distX * flare.position);
  18104. var y = centerY - (distY * flare.position);
  18105. var cw = flare.size;
  18106. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  18107. var cx = 2 * (x / globalViewport.width) - 1.0;
  18108. var cy = 1.0 - 2 * (y / globalViewport.height);
  18109. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  18110. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  18111. // Texture
  18112. this._effect.setTexture("textureSampler", flare.texture);
  18113. // Color
  18114. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  18115. // Draw order
  18116. engine.draw(true, 0, 6);
  18117. }
  18118. engine.setDepthBuffer(true);
  18119. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  18120. return true;
  18121. };
  18122. LensFlareSystem.prototype.dispose = function () {
  18123. if (this._vertexBuffer) {
  18124. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  18125. this._vertexBuffer = null;
  18126. }
  18127. if (this._indexBuffer) {
  18128. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  18129. this._indexBuffer = null;
  18130. }
  18131. while (this.lensFlares.length) {
  18132. this.lensFlares[0].dispose();
  18133. }
  18134. // Remove from scene
  18135. var index = this._scene.lensFlareSystems.indexOf(this);
  18136. this._scene.lensFlareSystems.splice(index, 1);
  18137. };
  18138. return LensFlareSystem;
  18139. })();
  18140. BABYLON.LensFlareSystem = LensFlareSystem;
  18141. })(BABYLON || (BABYLON = {}));
  18142. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  18143. (function (BABYLON) {
  18144. var IntersectionInfo = (function () {
  18145. function IntersectionInfo(bu, bv, distance) {
  18146. this.bu = bu;
  18147. this.bv = bv;
  18148. this.distance = distance;
  18149. this.faceId = 0;
  18150. this.subMeshId = 0;
  18151. }
  18152. return IntersectionInfo;
  18153. })();
  18154. BABYLON.IntersectionInfo = IntersectionInfo;
  18155. var PickingInfo = (function () {
  18156. function PickingInfo() {
  18157. this.hit = false;
  18158. this.distance = 0;
  18159. this.pickedPoint = null;
  18160. this.pickedMesh = null;
  18161. this.bu = 0;
  18162. this.bv = 0;
  18163. this.faceId = -1;
  18164. this.subMeshId = 0;
  18165. }
  18166. // Methods
  18167. PickingInfo.prototype.getNormal = function (useWorldCoordinates) {
  18168. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  18169. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18170. return null;
  18171. }
  18172. var indices = this.pickedMesh.getIndices();
  18173. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18174. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  18175. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  18176. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  18177. normal0 = normal0.scale(this.bu);
  18178. normal1 = normal1.scale(this.bv);
  18179. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  18180. var result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  18181. if (useWorldCoordinates) {
  18182. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  18183. }
  18184. return result;
  18185. };
  18186. PickingInfo.prototype.getTextureCoordinates = function () {
  18187. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18188. return null;
  18189. }
  18190. var indices = this.pickedMesh.getIndices();
  18191. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18192. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  18193. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  18194. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  18195. uv0 = uv0.scale(this.bu);
  18196. uv1 = uv1.scale(this.bv);
  18197. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  18198. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  18199. };
  18200. return PickingInfo;
  18201. })();
  18202. BABYLON.PickingInfo = PickingInfo;
  18203. })(BABYLON || (BABYLON = {}));
  18204. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  18205. (function (BABYLON) {
  18206. var FilesInput = (function () {
  18207. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  18208. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  18209. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  18210. this._engine = p_engine;
  18211. this._canvas = p_canvas;
  18212. this._currentScene = p_scene;
  18213. this._sceneLoadedCallback = p_sceneLoadedCallback;
  18214. this._progressCallback = p_progressCallback;
  18215. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  18216. this._textureLoadingCallback = p_textureLoadingCallback;
  18217. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  18218. }
  18219. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  18220. var _this = this;
  18221. if (p_elementToMonitor) {
  18222. this._elementToMonitor = p_elementToMonitor;
  18223. this._elementToMonitor.addEventListener("dragenter", function (e) {
  18224. _this.drag(e);
  18225. }, false);
  18226. this._elementToMonitor.addEventListener("dragover", function (e) {
  18227. _this.drag(e);
  18228. }, false);
  18229. this._elementToMonitor.addEventListener("drop", function (e) {
  18230. _this.drop(e);
  18231. }, false);
  18232. }
  18233. };
  18234. FilesInput.prototype.renderFunction = function () {
  18235. if (this._additionnalRenderLoopLogicCallback) {
  18236. this._additionnalRenderLoopLogicCallback();
  18237. }
  18238. if (this._currentScene) {
  18239. if (this._textureLoadingCallback) {
  18240. var remaining = this._currentScene.getWaitingItemsCount();
  18241. if (remaining > 0) {
  18242. this._textureLoadingCallback(remaining);
  18243. }
  18244. }
  18245. this._currentScene.render();
  18246. }
  18247. };
  18248. FilesInput.prototype.drag = function (e) {
  18249. e.stopPropagation();
  18250. e.preventDefault();
  18251. };
  18252. FilesInput.prototype.drop = function (eventDrop) {
  18253. eventDrop.stopPropagation();
  18254. eventDrop.preventDefault();
  18255. this.loadFiles(eventDrop);
  18256. };
  18257. FilesInput.prototype.loadFiles = function (event) {
  18258. if (this._startingProcessingFilesCallback)
  18259. this._startingProcessingFilesCallback();
  18260. // Handling data transfer via drag'n'drop
  18261. if (event && event.dataTransfer && event.dataTransfer.files) {
  18262. this._filesToLoad = event.dataTransfer.files;
  18263. }
  18264. // Handling files from input files
  18265. if (event && event.target && event.target.files) {
  18266. this._filesToLoad = event.target.files;
  18267. }
  18268. if (this._filesToLoad && this._filesToLoad.length > 0) {
  18269. for (var i = 0; i < this._filesToLoad.length; i++) {
  18270. switch (this._filesToLoad[i].type) {
  18271. case "image/jpeg":
  18272. case "image/png":
  18273. case "image/bmp":
  18274. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  18275. break;
  18276. case "image/targa":
  18277. case "image/vnd.ms-dds":
  18278. case "audio/wav":
  18279. case "audio/x-wav":
  18280. case "audio/mp3":
  18281. case "audio/mpeg":
  18282. case "audio/mpeg3":
  18283. case "audio/x-mpeg-3":
  18284. case "audio/ogg":
  18285. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  18286. break;
  18287. default:
  18288. 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) {
  18289. this._sceneFileToLoad = this._filesToLoad[i];
  18290. }
  18291. break;
  18292. }
  18293. }
  18294. this.reload();
  18295. }
  18296. };
  18297. FilesInput.prototype.reload = function () {
  18298. var _this = this;
  18299. var that = this;
  18300. // If a ".babylon" file has been provided
  18301. if (this._sceneFileToLoad) {
  18302. if (this._currentScene) {
  18303. this._engine.stopRenderLoop();
  18304. this._currentScene.dispose();
  18305. }
  18306. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  18307. that._currentScene = newScene;
  18308. // Wait for textures and shaders to be ready
  18309. that._currentScene.executeWhenReady(function () {
  18310. // Attach camera to canvas inputs
  18311. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  18312. that._currentScene.createDefaultCameraOrLight();
  18313. }
  18314. that._currentScene.activeCamera.attachControl(that._canvas);
  18315. if (that._sceneLoadedCallback) {
  18316. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  18317. }
  18318. that._engine.runRenderLoop(function () {
  18319. that.renderFunction();
  18320. });
  18321. });
  18322. }, function (progress) {
  18323. if (_this._progressCallback) {
  18324. _this._progressCallback(progress);
  18325. }
  18326. });
  18327. }
  18328. else {
  18329. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  18330. }
  18331. };
  18332. FilesInput.FilesTextures = new Array();
  18333. FilesInput.FilesToLoad = new Array();
  18334. return FilesInput;
  18335. })();
  18336. BABYLON.FilesInput = FilesInput;
  18337. })(BABYLON || (BABYLON = {}));
  18338. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  18339. (function (BABYLON) {
  18340. var OimoJSPlugin = (function () {
  18341. function OimoJSPlugin() {
  18342. this._registeredMeshes = [];
  18343. /**
  18344. * Update the body position according to the mesh position
  18345. * @param mesh
  18346. */
  18347. this.updateBodyPosition = function (mesh) {
  18348. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18349. var registeredMesh = this._registeredMeshes[index];
  18350. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18351. var body = registeredMesh.body.body;
  18352. mesh.computeWorldMatrix(true);
  18353. var center = mesh.getBoundingInfo().boundingBox.center;
  18354. body.setPosition(center.x, center.y, center.z);
  18355. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  18356. return;
  18357. }
  18358. // Case where the parent has been updated
  18359. if (registeredMesh.mesh.parent === mesh) {
  18360. mesh.computeWorldMatrix(true);
  18361. registeredMesh.mesh.computeWorldMatrix(true);
  18362. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  18363. var absoluteRotation = mesh.rotation;
  18364. body = registeredMesh.body.body;
  18365. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  18366. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  18367. return;
  18368. }
  18369. }
  18370. };
  18371. }
  18372. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  18373. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  18374. };
  18375. OimoJSPlugin.prototype.initialize = function (iterations) {
  18376. this._world = new OIMO.World();
  18377. this._world.clear();
  18378. };
  18379. OimoJSPlugin.prototype.setGravity = function (gravity) {
  18380. this._world.gravity = gravity;
  18381. };
  18382. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  18383. var body = null;
  18384. this.unregisterMesh(mesh);
  18385. mesh.computeWorldMatrix(true);
  18386. var initialRotation = null;
  18387. if (mesh.rotationQuaternion) {
  18388. initialRotation = mesh.rotationQuaternion.clone();
  18389. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18390. mesh.computeWorldMatrix(true);
  18391. }
  18392. var bbox = mesh.getBoundingInfo().boundingBox;
  18393. // The delta between the mesh position and the mesh bounding box center
  18394. var deltaPosition = mesh.position.subtract(bbox.center);
  18395. // Transform delta position with the rotation
  18396. if (initialRotation) {
  18397. var m = new BABYLON.Matrix();
  18398. initialRotation.toRotationMatrix(m);
  18399. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  18400. }
  18401. switch (impostor) {
  18402. case BABYLON.PhysicsEngine.SphereImpostor:
  18403. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18404. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18405. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18406. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  18407. body = new OIMO.Body({
  18408. type: 'sphere',
  18409. size: [size],
  18410. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  18411. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  18412. move: options.mass != 0,
  18413. config: [options.mass, options.friction, options.restitution],
  18414. world: this._world
  18415. });
  18416. break;
  18417. case BABYLON.PhysicsEngine.PlaneImpostor:
  18418. case BABYLON.PhysicsEngine.CylinderImpostor:
  18419. case BABYLON.PhysicsEngine.BoxImpostor:
  18420. var min = bbox.minimumWorld;
  18421. var max = bbox.maximumWorld;
  18422. var box = max.subtract(min);
  18423. var sizeX = this._checkWithEpsilon(box.x);
  18424. var sizeY = this._checkWithEpsilon(box.y);
  18425. var sizeZ = this._checkWithEpsilon(box.z);
  18426. body = new OIMO.Body({
  18427. type: 'box',
  18428. size: [sizeX, sizeY, sizeZ],
  18429. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  18430. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  18431. move: options.mass != 0,
  18432. config: [options.mass, options.friction, options.restitution],
  18433. world: this._world
  18434. });
  18435. break;
  18436. }
  18437. //If quaternion was set as the rotation of the object
  18438. if (initialRotation) {
  18439. //We have to access the rigid body's properties to set the quaternion.
  18440. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  18441. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  18442. //update the internal rotation matrix
  18443. body.body.syncShapes();
  18444. }
  18445. this._registeredMeshes.push({
  18446. mesh: mesh,
  18447. body: body,
  18448. delta: deltaPosition
  18449. });
  18450. return body;
  18451. };
  18452. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  18453. var types = [], sizes = [], positions = [], rotations = [];
  18454. var initialMesh = parts[0].mesh;
  18455. for (var index = 0; index < parts.length; index++) {
  18456. var part = parts[index];
  18457. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  18458. types.push(bodyParameters.type);
  18459. sizes.push.apply(sizes, bodyParameters.size);
  18460. positions.push.apply(positions, bodyParameters.pos);
  18461. rotations.push.apply(rotations, bodyParameters.rot);
  18462. }
  18463. var body = new OIMO.Body({
  18464. type: types,
  18465. size: sizes,
  18466. pos: positions,
  18467. rot: rotations,
  18468. move: options.mass != 0,
  18469. config: [options.mass, options.friction, options.restitution],
  18470. world: this._world
  18471. });
  18472. this._registeredMeshes.push({
  18473. mesh: initialMesh,
  18474. body: body
  18475. });
  18476. return body;
  18477. };
  18478. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  18479. var bodyParameters = null;
  18480. var mesh = part.mesh;
  18481. // We need the bounding box/sphere info to compute the physics body
  18482. mesh.computeWorldMatrix();
  18483. switch (part.impostor) {
  18484. case BABYLON.PhysicsEngine.SphereImpostor:
  18485. var bbox = mesh.getBoundingInfo().boundingBox;
  18486. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18487. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18488. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18489. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  18490. bodyParameters = {
  18491. type: 'sphere',
  18492. /* bug with oimo : sphere needs 3 sizes in this case */
  18493. size: [size, -1, -1],
  18494. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  18495. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  18496. };
  18497. break;
  18498. case BABYLON.PhysicsEngine.PlaneImpostor:
  18499. case BABYLON.PhysicsEngine.BoxImpostor:
  18500. bbox = mesh.getBoundingInfo().boundingBox;
  18501. var min = bbox.minimumWorld;
  18502. var max = bbox.maximumWorld;
  18503. var box = max.subtract(min);
  18504. var sizeX = this._checkWithEpsilon(box.x);
  18505. var sizeY = this._checkWithEpsilon(box.y);
  18506. var sizeZ = this._checkWithEpsilon(box.z);
  18507. var relativePosition = mesh.position;
  18508. bodyParameters = {
  18509. type: 'box',
  18510. size: [sizeX, sizeY, sizeZ],
  18511. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  18512. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  18513. };
  18514. break;
  18515. }
  18516. return bodyParameters;
  18517. };
  18518. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  18519. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18520. var registeredMesh = this._registeredMeshes[index];
  18521. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18522. if (registeredMesh.body) {
  18523. this._world.removeRigidBody(registeredMesh.body.body);
  18524. this._unbindBody(registeredMesh.body);
  18525. }
  18526. this._registeredMeshes.splice(index, 1);
  18527. return;
  18528. }
  18529. }
  18530. };
  18531. OimoJSPlugin.prototype._unbindBody = function (body) {
  18532. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18533. var registeredMesh = this._registeredMeshes[index];
  18534. if (registeredMesh.body === body) {
  18535. registeredMesh.body = null;
  18536. }
  18537. }
  18538. };
  18539. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  18540. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18541. var registeredMesh = this._registeredMeshes[index];
  18542. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18543. // Get object mass to have a behaviour similar to cannon.js
  18544. var mass = registeredMesh.body.body.massInfo.mass;
  18545. // The force is scaled with the mass of object
  18546. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  18547. return;
  18548. }
  18549. }
  18550. };
  18551. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  18552. var body1 = null, body2 = null;
  18553. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18554. var registeredMesh = this._registeredMeshes[index];
  18555. if (registeredMesh.mesh === mesh1) {
  18556. body1 = registeredMesh.body.body;
  18557. }
  18558. else if (registeredMesh.mesh === mesh2) {
  18559. body2 = registeredMesh.body.body;
  18560. }
  18561. }
  18562. if (!body1 || !body2) {
  18563. return false;
  18564. }
  18565. if (!options) {
  18566. options = {};
  18567. }
  18568. new OIMO.Link({
  18569. type: options.type,
  18570. body1: body1,
  18571. body2: body2,
  18572. min: options.min,
  18573. max: options.max,
  18574. axe1: options.axe1,
  18575. axe2: options.axe2,
  18576. pos1: [pivot1.x, pivot1.y, pivot1.z],
  18577. pos2: [pivot2.x, pivot2.y, pivot2.z],
  18578. collision: options.collision,
  18579. spring: options.spring,
  18580. world: this._world
  18581. });
  18582. return true;
  18583. };
  18584. OimoJSPlugin.prototype.dispose = function () {
  18585. this._world.clear();
  18586. while (this._registeredMeshes.length) {
  18587. this.unregisterMesh(this._registeredMeshes[0].mesh);
  18588. }
  18589. };
  18590. OimoJSPlugin.prototype.isSupported = function () {
  18591. return OIMO !== undefined;
  18592. };
  18593. OimoJSPlugin.prototype._getLastShape = function (body) {
  18594. var lastShape = body.shapes;
  18595. while (lastShape.next) {
  18596. lastShape = lastShape.next;
  18597. }
  18598. return lastShape;
  18599. };
  18600. OimoJSPlugin.prototype.runOneStep = function (time) {
  18601. this._world.step();
  18602. // Update the position of all registered meshes
  18603. var i = this._registeredMeshes.length;
  18604. var m;
  18605. while (i--) {
  18606. var body = this._registeredMeshes[i].body.body;
  18607. var mesh = this._registeredMeshes[i].mesh;
  18608. var delta = this._registeredMeshes[i].delta;
  18609. if (!body.sleeping) {
  18610. if (body.shapes.next) {
  18611. var parentShape = this._getLastShape(body);
  18612. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  18613. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  18614. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  18615. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  18616. if (!mesh.rotationQuaternion) {
  18617. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18618. }
  18619. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  18620. mesh.computeWorldMatrix();
  18621. }
  18622. else {
  18623. m = body.getMatrix();
  18624. mtx = BABYLON.Matrix.FromArray(m);
  18625. // Body position
  18626. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  18627. if (!delta) {
  18628. mesh.position.x = bodyX;
  18629. mesh.position.y = bodyY;
  18630. mesh.position.z = bodyZ;
  18631. }
  18632. else {
  18633. mesh.position.x = bodyX + delta.x;
  18634. mesh.position.y = bodyY + delta.y;
  18635. mesh.position.z = bodyZ + delta.z;
  18636. }
  18637. if (!mesh.rotationQuaternion) {
  18638. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18639. }
  18640. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  18641. mesh.computeWorldMatrix();
  18642. }
  18643. }
  18644. }
  18645. };
  18646. return OimoJSPlugin;
  18647. })();
  18648. BABYLON.OimoJSPlugin = OimoJSPlugin;
  18649. })(BABYLON || (BABYLON = {}));
  18650. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  18651. (function (BABYLON) {
  18652. var PhysicsEngine = (function () {
  18653. function PhysicsEngine(plugin) {
  18654. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  18655. }
  18656. PhysicsEngine.prototype._initialize = function (gravity) {
  18657. this._currentPlugin.initialize();
  18658. this._setGravity(gravity);
  18659. };
  18660. PhysicsEngine.prototype._runOneStep = function (delta) {
  18661. if (delta > 0.1) {
  18662. delta = 0.1;
  18663. }
  18664. else if (delta <= 0) {
  18665. delta = 1.0 / 60.0;
  18666. }
  18667. this._currentPlugin.runOneStep(delta);
  18668. };
  18669. PhysicsEngine.prototype._setGravity = function (gravity) {
  18670. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  18671. this._currentPlugin.setGravity(this.gravity);
  18672. };
  18673. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  18674. return this._currentPlugin.registerMesh(mesh, impostor, options);
  18675. };
  18676. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  18677. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  18678. };
  18679. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  18680. this._currentPlugin.unregisterMesh(mesh);
  18681. };
  18682. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  18683. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  18684. };
  18685. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  18686. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  18687. };
  18688. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  18689. this._currentPlugin.updateBodyPosition(mesh);
  18690. };
  18691. PhysicsEngine.prototype.dispose = function () {
  18692. this._currentPlugin.dispose();
  18693. };
  18694. PhysicsEngine.prototype.isSupported = function () {
  18695. return this._currentPlugin.isSupported();
  18696. };
  18697. // Statics
  18698. PhysicsEngine.NoImpostor = 0;
  18699. PhysicsEngine.SphereImpostor = 1;
  18700. PhysicsEngine.BoxImpostor = 2;
  18701. PhysicsEngine.PlaneImpostor = 3;
  18702. PhysicsEngine.MeshImpostor = 4;
  18703. PhysicsEngine.CapsuleImpostor = 5;
  18704. PhysicsEngine.ConeImpostor = 6;
  18705. PhysicsEngine.CylinderImpostor = 7;
  18706. PhysicsEngine.ConvexHullImpostor = 8;
  18707. PhysicsEngine.Epsilon = 0.001;
  18708. return PhysicsEngine;
  18709. })();
  18710. BABYLON.PhysicsEngine = PhysicsEngine;
  18711. })(BABYLON || (BABYLON = {}));
  18712. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  18713. (function (BABYLON) {
  18714. var serializeLight = function (light) {
  18715. var serializationObject = {};
  18716. serializationObject.name = light.name;
  18717. serializationObject.id = light.id;
  18718. serializationObject.tags = BABYLON.Tags.GetTags(light);
  18719. if (light instanceof BABYLON.PointLight) {
  18720. serializationObject.type = 0;
  18721. serializationObject.position = light.position.asArray();
  18722. }
  18723. else if (light instanceof BABYLON.DirectionalLight) {
  18724. serializationObject.type = 1;
  18725. var directionalLight = light;
  18726. serializationObject.position = directionalLight.position.asArray();
  18727. serializationObject.direction = directionalLight.direction.asArray();
  18728. }
  18729. else if (light instanceof BABYLON.SpotLight) {
  18730. serializationObject.type = 2;
  18731. var spotLight = light;
  18732. serializationObject.position = spotLight.position.asArray();
  18733. serializationObject.direction = spotLight.position.asArray();
  18734. serializationObject.angle = spotLight.angle;
  18735. serializationObject.exponent = spotLight.exponent;
  18736. }
  18737. else if (light instanceof BABYLON.HemisphericLight) {
  18738. serializationObject.type = 3;
  18739. var hemisphericLight = light;
  18740. serializationObject.direction = hemisphericLight.direction.asArray();
  18741. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  18742. }
  18743. if (light.intensity) {
  18744. serializationObject.intensity = light.intensity;
  18745. }
  18746. serializationObject.range = light.range;
  18747. serializationObject.diffuse = light.diffuse.asArray();
  18748. serializationObject.specular = light.specular.asArray();
  18749. return serializationObject;
  18750. };
  18751. var serializeFresnelParameter = function (fresnelParameter) {
  18752. var serializationObject = {};
  18753. serializationObject.isEnabled = fresnelParameter.isEnabled;
  18754. serializationObject.leftColor = fresnelParameter.leftColor;
  18755. serializationObject.rightColor = fresnelParameter.rightColor;
  18756. serializationObject.bias = fresnelParameter.bias;
  18757. serializationObject.power = fresnelParameter.power;
  18758. return serializationObject;
  18759. };
  18760. var appendAnimations = function (source, destination) {
  18761. if (source.animations) {
  18762. destination.animations = [];
  18763. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  18764. var animation = source.animations[animationIndex];
  18765. destination.animations.push(serializeAnimation(animation));
  18766. }
  18767. }
  18768. };
  18769. var serializeCamera = function (camera) {
  18770. var serializationObject = {};
  18771. serializationObject.name = camera.name;
  18772. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  18773. serializationObject.id = camera.id;
  18774. serializationObject.position = camera.position.asArray();
  18775. // Parent
  18776. if (camera.parent) {
  18777. serializationObject.parentId = camera.parent.id;
  18778. }
  18779. serializationObject.fov = camera.fov;
  18780. serializationObject.minZ = camera.minZ;
  18781. serializationObject.maxZ = camera.maxZ;
  18782. serializationObject.inertia = camera.inertia;
  18783. //setting the type
  18784. if (camera instanceof BABYLON.FreeCamera) {
  18785. serializationObject.type = "FreeCamera";
  18786. }
  18787. else if (camera instanceof BABYLON.ArcRotateCamera) {
  18788. serializationObject.type = "ArcRotateCamera";
  18789. }
  18790. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18791. serializationObject.type = "AnaglyphArcRotateCamera";
  18792. }
  18793. else if (camera instanceof BABYLON.GamepadCamera) {
  18794. serializationObject.type = "GamepadCamera";
  18795. }
  18796. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  18797. serializationObject.type = "AnaglyphFreeCamera";
  18798. }
  18799. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  18800. serializationObject.type = "DeviceOrientationCamera";
  18801. }
  18802. else if (camera instanceof BABYLON.FollowCamera) {
  18803. serializationObject.type = "FollowCamera";
  18804. }
  18805. else if (camera instanceof BABYLON.OculusCamera) {
  18806. serializationObject.type = "OculusCamera";
  18807. }
  18808. else if (camera instanceof BABYLON.OculusGamepadCamera) {
  18809. serializationObject.type = "OculusGamepadCamera";
  18810. }
  18811. else if (camera instanceof BABYLON.TouchCamera) {
  18812. serializationObject.type = "TouchCamera";
  18813. }
  18814. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  18815. serializationObject.type = "VirtualJoysticksCamera";
  18816. }
  18817. else if (camera instanceof BABYLON.WebVRCamera) {
  18818. serializationObject.type = "WebVRCamera";
  18819. }
  18820. else if (camera instanceof BABYLON.VRDeviceOrientationCamera) {
  18821. serializationObject.type = "VRDeviceOrientationCamera";
  18822. }
  18823. //special properties of specific cameras
  18824. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18825. var arcCamera = camera;
  18826. serializationObject.alpha = arcCamera.alpha;
  18827. serializationObject.beta = arcCamera.beta;
  18828. serializationObject.radius = arcCamera.radius;
  18829. if (arcCamera.target && arcCamera.target.id) {
  18830. serializationObject.lockedTargetId = arcCamera.target.id;
  18831. }
  18832. }
  18833. else if (camera instanceof BABYLON.FollowCamera) {
  18834. var followCam = camera;
  18835. serializationObject.radius = followCam.radius;
  18836. serializationObject.heightOffset = followCam.heightOffset;
  18837. serializationObject.rotationOffset = followCam.rotationOffset;
  18838. }
  18839. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18840. //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.
  18841. if (camera['_eyeSpace'] !== undefined) {
  18842. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  18843. }
  18844. }
  18845. //general properties that not all cameras have. The [] is due to typescript's type safety
  18846. if (camera['speed'] !== undefined) {
  18847. serializationObject.speed = camera['speed'];
  18848. }
  18849. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  18850. serializationObject.target = camera['target'].asArray();
  18851. }
  18852. // Target
  18853. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  18854. serializationObject.rotation = camera['rotation'].asArray();
  18855. }
  18856. // Locked target
  18857. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  18858. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  18859. }
  18860. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  18861. serializationObject.applyGravity = camera['applyGravity'] || false;
  18862. if (camera['ellipsoid']) {
  18863. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  18864. }
  18865. // Animations
  18866. appendAnimations(camera, serializationObject);
  18867. // Layer mask
  18868. serializationObject.layerMask = camera.layerMask;
  18869. return serializationObject;
  18870. };
  18871. var serializeAnimation = function (animation) {
  18872. var serializationObject = {};
  18873. serializationObject.name = animation.name;
  18874. serializationObject.property = animation.targetProperty;
  18875. serializationObject.framePerSecond = animation.framePerSecond;
  18876. serializationObject.dataType = animation.dataType;
  18877. serializationObject.loopBehavior = animation.loopMode;
  18878. var dataType = animation.dataType;
  18879. serializationObject.keys = [];
  18880. var keys = animation.getKeys();
  18881. for (var index = 0; index < keys.length; index++) {
  18882. var animationKey = keys[index];
  18883. var key = {};
  18884. key.frame = animationKey.frame;
  18885. switch (dataType) {
  18886. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18887. key.values = [animationKey.value];
  18888. break;
  18889. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18890. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18891. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18892. key.values = animationKey.value.asArray();
  18893. break;
  18894. }
  18895. serializationObject.keys.push(key);
  18896. }
  18897. return serializationObject;
  18898. };
  18899. var serializeMultiMaterial = function (material) {
  18900. var serializationObject = {};
  18901. serializationObject.name = material.name;
  18902. serializationObject.id = material.id;
  18903. serializationObject.tags = BABYLON.Tags.GetTags(material);
  18904. serializationObject.materials = [];
  18905. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  18906. var subMat = material.subMaterials[matIndex];
  18907. if (subMat) {
  18908. serializationObject.materials.push(subMat.id);
  18909. }
  18910. else {
  18911. serializationObject.materials.push(null);
  18912. }
  18913. }
  18914. return serializationObject;
  18915. };
  18916. var serializeMaterial = function (material) {
  18917. var serializationObject = {};
  18918. serializationObject.name = material.name;
  18919. serializationObject.ambient = material.ambientColor.asArray();
  18920. serializationObject.diffuse = material.diffuseColor.asArray();
  18921. serializationObject.specular = material.specularColor.asArray();
  18922. serializationObject.specularPower = material.specularPower;
  18923. serializationObject.emissive = material.emissiveColor.asArray();
  18924. serializationObject.alpha = material.alpha;
  18925. serializationObject.id = material.id;
  18926. serializationObject.tags = BABYLON.Tags.GetTags(material);
  18927. serializationObject.backFaceCulling = material.backFaceCulling;
  18928. if (material.diffuseTexture) {
  18929. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  18930. }
  18931. if (material.diffuseFresnelParameters) {
  18932. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  18933. }
  18934. if (material.ambientTexture) {
  18935. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  18936. }
  18937. if (material.opacityTexture) {
  18938. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  18939. }
  18940. if (material.opacityFresnelParameters) {
  18941. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  18942. }
  18943. if (material.reflectionTexture) {
  18944. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  18945. }
  18946. if (material.reflectionFresnelParameters) {
  18947. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  18948. }
  18949. if (material.emissiveTexture) {
  18950. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  18951. }
  18952. if (material.emissiveFresnelParameters) {
  18953. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  18954. }
  18955. if (material.specularTexture) {
  18956. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  18957. }
  18958. if (material.bumpTexture) {
  18959. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  18960. }
  18961. return serializationObject;
  18962. };
  18963. var serializeTexture = function (texture) {
  18964. var serializationObject = {};
  18965. if (!texture.name) {
  18966. return null;
  18967. }
  18968. if (texture instanceof BABYLON.CubeTexture) {
  18969. serializationObject.name = texture.name;
  18970. serializationObject.hasAlpha = texture.hasAlpha;
  18971. serializationObject.level = texture.level;
  18972. serializationObject.coordinatesMode = texture.coordinatesMode;
  18973. return serializationObject;
  18974. }
  18975. if (texture instanceof BABYLON.MirrorTexture) {
  18976. var mirrorTexture = texture;
  18977. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  18978. serializationObject.renderList = [];
  18979. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  18980. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  18981. }
  18982. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  18983. }
  18984. else if (texture instanceof BABYLON.RenderTargetTexture) {
  18985. var renderTargetTexture = texture;
  18986. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  18987. serializationObject.renderList = [];
  18988. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  18989. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  18990. }
  18991. }
  18992. var regularTexture = texture;
  18993. serializationObject.name = texture.name;
  18994. serializationObject.hasAlpha = texture.hasAlpha;
  18995. serializationObject.level = texture.level;
  18996. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  18997. serializationObject.coordinatesMode = texture.coordinatesMode;
  18998. serializationObject.uOffset = regularTexture.uOffset;
  18999. serializationObject.vOffset = regularTexture.vOffset;
  19000. serializationObject.uScale = regularTexture.uScale;
  19001. serializationObject.vScale = regularTexture.vScale;
  19002. serializationObject.uAng = regularTexture.uAng;
  19003. serializationObject.vAng = regularTexture.vAng;
  19004. serializationObject.wAng = regularTexture.wAng;
  19005. serializationObject.wrapU = texture.wrapU;
  19006. serializationObject.wrapV = texture.wrapV;
  19007. // Animations
  19008. appendAnimations(texture, serializationObject);
  19009. return serializationObject;
  19010. };
  19011. var serializeSkeleton = function (skeleton) {
  19012. var serializationObject = {};
  19013. serializationObject.name = skeleton.name;
  19014. serializationObject.id = skeleton.id;
  19015. serializationObject.bones = [];
  19016. for (var index = 0; index < skeleton.bones.length; index++) {
  19017. var bone = skeleton.bones[index];
  19018. var serializedBone = {
  19019. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  19020. name: bone.name,
  19021. matrix: bone.getLocalMatrix().toArray()
  19022. };
  19023. serializationObject.bones.push(serializedBone);
  19024. if (bone.animations && bone.animations.length > 0) {
  19025. serializedBone.animation = serializeAnimation(bone.animations[0]);
  19026. }
  19027. }
  19028. return serializationObject;
  19029. };
  19030. var serializeParticleSystem = function (particleSystem) {
  19031. var serializationObject = {};
  19032. serializationObject.emitterId = particleSystem.emitter.id;
  19033. serializationObject.capacity = particleSystem.getCapacity();
  19034. if (particleSystem.particleTexture) {
  19035. serializationObject.textureName = particleSystem.particleTexture.name;
  19036. }
  19037. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  19038. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  19039. serializationObject.minSize = particleSystem.minSize;
  19040. serializationObject.maxSize = particleSystem.maxSize;
  19041. serializationObject.minLifeTime = particleSystem.minLifeTime;
  19042. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  19043. serializationObject.emitRate = particleSystem.emitRate;
  19044. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  19045. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  19046. serializationObject.gravity = particleSystem.gravity.asArray();
  19047. serializationObject.direction1 = particleSystem.direction1.asArray();
  19048. serializationObject.direction2 = particleSystem.direction2.asArray();
  19049. serializationObject.color1 = particleSystem.color1.asArray();
  19050. serializationObject.color2 = particleSystem.color2.asArray();
  19051. serializationObject.colorDead = particleSystem.colorDead.asArray();
  19052. serializationObject.updateSpeed = particleSystem.updateSpeed;
  19053. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  19054. serializationObject.textureMask = particleSystem.textureMask.asArray();
  19055. serializationObject.blendMode = particleSystem.blendMode;
  19056. return serializationObject;
  19057. };
  19058. var serializeLensFlareSystem = function (lensFlareSystem) {
  19059. var serializationObject = {};
  19060. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  19061. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  19062. serializationObject.flares = [];
  19063. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  19064. var flare = lensFlareSystem.lensFlares[index];
  19065. serializationObject.flares.push({
  19066. size: flare.size,
  19067. position: flare.position,
  19068. color: flare.color.asArray(),
  19069. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  19070. });
  19071. }
  19072. return serializationObject;
  19073. };
  19074. var serializeShadowGenerator = function (light) {
  19075. var serializationObject = {};
  19076. var shadowGenerator = light.getShadowGenerator();
  19077. serializationObject.lightId = light.id;
  19078. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  19079. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  19080. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  19081. serializationObject.renderList = [];
  19082. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  19083. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  19084. serializationObject.renderList.push(mesh.id);
  19085. }
  19086. return serializationObject;
  19087. };
  19088. var serializedGeometries = [];
  19089. var serializeGeometry = function (geometry, serializationGeometries) {
  19090. if (serializedGeometries[geometry.id]) {
  19091. return;
  19092. }
  19093. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  19094. serializationGeometries.boxes.push(serializeBox(geometry));
  19095. }
  19096. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  19097. serializationGeometries.spheres.push(serializeSphere(geometry));
  19098. }
  19099. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  19100. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  19101. }
  19102. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  19103. serializationGeometries.toruses.push(serializeTorus(geometry));
  19104. }
  19105. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  19106. serializationGeometries.grounds.push(serializeGround(geometry));
  19107. }
  19108. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  19109. serializationGeometries.planes.push(serializePlane(geometry));
  19110. }
  19111. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  19112. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  19113. }
  19114. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  19115. throw new Error("Unknow primitive type");
  19116. }
  19117. else {
  19118. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  19119. }
  19120. serializedGeometries[geometry.id] = true;
  19121. };
  19122. var serializeGeometryBase = function (geometry) {
  19123. var serializationObject = {};
  19124. serializationObject.id = geometry.id;
  19125. if (BABYLON.Tags.HasTags(geometry)) {
  19126. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  19127. }
  19128. return serializationObject;
  19129. };
  19130. var serializeVertexData = function (vertexData) {
  19131. var serializationObject = serializeGeometryBase(vertexData);
  19132. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19133. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19134. }
  19135. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19136. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19137. }
  19138. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  19139. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19140. }
  19141. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  19142. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  19143. }
  19144. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  19145. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  19146. }
  19147. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  19148. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  19149. serializationObject.matricesIndices._isExpanded = true;
  19150. }
  19151. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  19152. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  19153. }
  19154. serializationObject.indices = vertexData.getIndices();
  19155. return serializationObject;
  19156. };
  19157. var serializePrimitive = function (primitive) {
  19158. var serializationObject = serializeGeometryBase(primitive);
  19159. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  19160. return serializationObject;
  19161. };
  19162. var serializeBox = function (box) {
  19163. var serializationObject = serializePrimitive(box);
  19164. serializationObject.size = box.size;
  19165. return serializationObject;
  19166. };
  19167. var serializeSphere = function (sphere) {
  19168. var serializationObject = serializePrimitive(sphere);
  19169. serializationObject.segments = sphere.segments;
  19170. serializationObject.diameter = sphere.diameter;
  19171. return serializationObject;
  19172. };
  19173. var serializeCylinder = function (cylinder) {
  19174. var serializationObject = serializePrimitive(cylinder);
  19175. serializationObject.height = cylinder.height;
  19176. serializationObject.diameterTop = cylinder.diameterTop;
  19177. serializationObject.diameterBottom = cylinder.diameterBottom;
  19178. serializationObject.tessellation = cylinder.tessellation;
  19179. return serializationObject;
  19180. };
  19181. var serializeTorus = function (torus) {
  19182. var serializationObject = serializePrimitive(torus);
  19183. serializationObject.diameter = torus.diameter;
  19184. serializationObject.thickness = torus.thickness;
  19185. serializationObject.tessellation = torus.tessellation;
  19186. return serializationObject;
  19187. };
  19188. var serializeGround = function (ground) {
  19189. var serializationObject = serializePrimitive(ground);
  19190. serializationObject.width = ground.width;
  19191. serializationObject.height = ground.height;
  19192. serializationObject.subdivisions = ground.subdivisions;
  19193. return serializationObject;
  19194. };
  19195. var serializePlane = function (plane) {
  19196. var serializationObject = serializePrimitive(plane);
  19197. serializationObject.size = plane.size;
  19198. return serializationObject;
  19199. };
  19200. var serializeTorusKnot = function (torusKnot) {
  19201. var serializationObject = serializePrimitive(torusKnot);
  19202. serializationObject.radius = torusKnot.radius;
  19203. serializationObject.tube = torusKnot.tube;
  19204. serializationObject.radialSegments = torusKnot.radialSegments;
  19205. serializationObject.tubularSegments = torusKnot.tubularSegments;
  19206. serializationObject.p = torusKnot.p;
  19207. serializationObject.q = torusKnot.q;
  19208. return serializationObject;
  19209. };
  19210. var serializeMesh = function (mesh, serializationScene) {
  19211. var serializationObject = {};
  19212. serializationObject.name = mesh.name;
  19213. serializationObject.id = mesh.id;
  19214. if (BABYLON.Tags.HasTags(mesh)) {
  19215. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  19216. }
  19217. serializationObject.position = mesh.position.asArray();
  19218. if (mesh.rotationQuaternion) {
  19219. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  19220. }
  19221. else if (mesh.rotation) {
  19222. serializationObject.rotation = mesh.rotation.asArray();
  19223. }
  19224. serializationObject.scaling = mesh.scaling.asArray();
  19225. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  19226. serializationObject.isEnabled = mesh.isEnabled();
  19227. serializationObject.isVisible = mesh.isVisible;
  19228. serializationObject.infiniteDistance = mesh.infiniteDistance;
  19229. serializationObject.pickable = mesh.isPickable;
  19230. serializationObject.receiveShadows = mesh.receiveShadows;
  19231. serializationObject.billboardMode = mesh.billboardMode;
  19232. serializationObject.visibility = mesh.visibility;
  19233. serializationObject.checkCollisions = mesh.checkCollisions;
  19234. // Parent
  19235. if (mesh.parent) {
  19236. serializationObject.parentId = mesh.parent.id;
  19237. }
  19238. // Geometry
  19239. var geometry = mesh._geometry;
  19240. if (geometry) {
  19241. var geometryId = geometry.id;
  19242. serializationObject.geometryId = geometryId;
  19243. if (!mesh.getScene().getGeometryByID(geometryId)) {
  19244. // 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
  19245. serializeGeometry(geometry, serializationScene.geometries);
  19246. }
  19247. // SubMeshes
  19248. serializationObject.subMeshes = [];
  19249. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  19250. var subMesh = mesh.subMeshes[subIndex];
  19251. serializationObject.subMeshes.push({
  19252. materialIndex: subMesh.materialIndex,
  19253. verticesStart: subMesh.verticesStart,
  19254. verticesCount: subMesh.verticesCount,
  19255. indexStart: subMesh.indexStart,
  19256. indexCount: subMesh.indexCount
  19257. });
  19258. }
  19259. }
  19260. // Material
  19261. if (mesh.material) {
  19262. serializationObject.materialId = mesh.material.id;
  19263. }
  19264. else {
  19265. mesh.material = null;
  19266. }
  19267. // Skeleton
  19268. if (mesh.skeleton) {
  19269. serializationObject.skeletonId = mesh.skeleton.id;
  19270. }
  19271. // Physics
  19272. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  19273. serializationObject.physicsMass = mesh.getPhysicsMass();
  19274. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  19275. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  19276. switch (mesh.getPhysicsImpostor()) {
  19277. case BABYLON.PhysicsEngine.BoxImpostor:
  19278. serializationObject.physicsImpostor = 1;
  19279. break;
  19280. case BABYLON.PhysicsEngine.SphereImpostor:
  19281. serializationObject.physicsImpostor = 2;
  19282. break;
  19283. }
  19284. }
  19285. // Instances
  19286. serializationObject.instances = [];
  19287. for (var index = 0; index < mesh.instances.length; index++) {
  19288. var instance = mesh.instances[index];
  19289. var serializationInstance = {
  19290. name: instance.name,
  19291. position: instance.position,
  19292. rotation: instance.rotation,
  19293. rotationQuaternion: instance.rotationQuaternion,
  19294. scaling: instance.scaling
  19295. };
  19296. serializationObject.instances.push(serializationInstance);
  19297. // Animations
  19298. appendAnimations(instance, serializationInstance);
  19299. }
  19300. // Animations
  19301. appendAnimations(mesh, serializationObject);
  19302. // Layer mask
  19303. serializationObject.layerMask = mesh.layerMask;
  19304. return serializationObject;
  19305. };
  19306. var SceneSerializer = (function () {
  19307. function SceneSerializer() {
  19308. }
  19309. SceneSerializer.Serialize = function (scene) {
  19310. var serializationObject = {};
  19311. // Scene
  19312. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  19313. serializationObject.autoClear = scene.autoClear;
  19314. serializationObject.clearColor = scene.clearColor.asArray();
  19315. serializationObject.ambientColor = scene.ambientColor.asArray();
  19316. serializationObject.gravity = scene.gravity.asArray();
  19317. // Fog
  19318. if (scene.fogMode && scene.fogMode !== 0) {
  19319. serializationObject.fogMode = scene.fogMode;
  19320. serializationObject.fogColor = scene.fogColor.asArray();
  19321. serializationObject.fogStart = scene.fogStart;
  19322. serializationObject.fogEnd = scene.fogEnd;
  19323. serializationObject.fogDensity = scene.fogDensity;
  19324. }
  19325. // Lights
  19326. serializationObject.lights = [];
  19327. for (var index = 0; index < scene.lights.length; index++) {
  19328. var light = scene.lights[index];
  19329. serializationObject.lights.push(serializeLight(light));
  19330. }
  19331. // Cameras
  19332. serializationObject.cameras = [];
  19333. for (index = 0; index < scene.cameras.length; index++) {
  19334. var camera = scene.cameras[index];
  19335. serializationObject.cameras.push(serializeCamera(camera));
  19336. }
  19337. if (scene.activeCamera) {
  19338. serializationObject.activeCameraID = scene.activeCamera.id;
  19339. }
  19340. // Materials
  19341. serializationObject.materials = [];
  19342. serializationObject.multiMaterials = [];
  19343. for (index = 0; index < scene.materials.length; index++) {
  19344. var material = scene.materials[index];
  19345. if (material instanceof BABYLON.StandardMaterial) {
  19346. serializationObject.materials.push(serializeMaterial(material));
  19347. }
  19348. else if (material instanceof BABYLON.MultiMaterial) {
  19349. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  19350. }
  19351. }
  19352. // Skeletons
  19353. serializationObject.skeletons = [];
  19354. for (index = 0; index < scene.skeletons.length; index++) {
  19355. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  19356. }
  19357. // Geometries
  19358. serializationObject.geometries = {};
  19359. serializationObject.geometries.boxes = [];
  19360. serializationObject.geometries.spheres = [];
  19361. serializationObject.geometries.cylinders = [];
  19362. serializationObject.geometries.toruses = [];
  19363. serializationObject.geometries.grounds = [];
  19364. serializationObject.geometries.planes = [];
  19365. serializationObject.geometries.torusKnots = [];
  19366. serializationObject.geometries.vertexData = [];
  19367. serializedGeometries = [];
  19368. var geometries = scene.getGeometries();
  19369. for (index = 0; index < geometries.length; index++) {
  19370. var geometry = geometries[index];
  19371. if (geometry.isReady()) {
  19372. serializeGeometry(geometry, serializationObject.geometries);
  19373. }
  19374. }
  19375. // Meshes
  19376. serializationObject.meshes = [];
  19377. for (index = 0; index < scene.meshes.length; index++) {
  19378. var abstractMesh = scene.meshes[index];
  19379. if (abstractMesh instanceof BABYLON.Mesh) {
  19380. var mesh = abstractMesh;
  19381. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  19382. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  19383. }
  19384. }
  19385. }
  19386. // Particles Systems
  19387. serializationObject.particleSystems = [];
  19388. for (index = 0; index < scene.particleSystems.length; index++) {
  19389. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  19390. }
  19391. // Lens flares
  19392. serializationObject.lensFlareSystems = [];
  19393. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  19394. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  19395. }
  19396. // Shadows
  19397. serializationObject.shadowGenerators = [];
  19398. for (index = 0; index < scene.lights.length; index++) {
  19399. light = scene.lights[index];
  19400. if (light.getShadowGenerator()) {
  19401. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  19402. }
  19403. }
  19404. return serializationObject;
  19405. };
  19406. return SceneSerializer;
  19407. })();
  19408. BABYLON.SceneSerializer = SceneSerializer;
  19409. })(BABYLON || (BABYLON = {}));
  19410. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  19411. (function (BABYLON) {
  19412. var SceneLoader = (function () {
  19413. function SceneLoader() {
  19414. }
  19415. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  19416. get: function () {
  19417. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19418. },
  19419. set: function (value) {
  19420. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19421. },
  19422. enumerable: true,
  19423. configurable: true
  19424. });
  19425. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19426. get: function () {
  19427. return SceneLoader._ShowLoadingScreen;
  19428. },
  19429. set: function (value) {
  19430. SceneLoader._ShowLoadingScreen = value;
  19431. },
  19432. enumerable: true,
  19433. configurable: true
  19434. });
  19435. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19436. var dotPosition = sceneFilename.lastIndexOf(".");
  19437. var queryStringPosition = sceneFilename.indexOf("?");
  19438. if (queryStringPosition === -1) {
  19439. queryStringPosition = sceneFilename.length;
  19440. }
  19441. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19442. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19443. var plugin = this._registeredPlugins[index];
  19444. if (plugin.extensions.indexOf(extension) !== -1) {
  19445. return plugin;
  19446. }
  19447. }
  19448. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19449. };
  19450. // Public functions
  19451. SceneLoader.RegisterPlugin = function (plugin) {
  19452. plugin.extensions = plugin.extensions.toLowerCase();
  19453. SceneLoader._registeredPlugins.push(plugin);
  19454. };
  19455. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19456. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19457. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19458. return;
  19459. }
  19460. var manifestChecked = function (success) {
  19461. scene.database = database;
  19462. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19463. var importMeshFromData = function (data) {
  19464. var meshes = [];
  19465. var particleSystems = [];
  19466. var skeletons = [];
  19467. try {
  19468. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19469. if (onerror) {
  19470. onerror(scene, 'unable to load the scene');
  19471. }
  19472. return;
  19473. }
  19474. }
  19475. catch (e) {
  19476. if (onerror) {
  19477. onerror(scene, e);
  19478. }
  19479. return;
  19480. }
  19481. if (onsuccess) {
  19482. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19483. onsuccess(meshes, particleSystems, skeletons);
  19484. }
  19485. };
  19486. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19487. // Direct load
  19488. importMeshFromData(sceneFilename.substr(5));
  19489. return;
  19490. }
  19491. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19492. importMeshFromData(data);
  19493. }, progressCallBack, database);
  19494. };
  19495. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19496. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19497. };
  19498. /**
  19499. * Load a scene
  19500. * @param rootUrl a string that defines the root url for scene and resources
  19501. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19502. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19503. */
  19504. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19505. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19506. };
  19507. /**
  19508. * Append a scene
  19509. * @param rootUrl a string that defines the root url for scene and resources
  19510. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19511. * @param scene is the instance of BABYLON.Scene to append to
  19512. */
  19513. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19514. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19515. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19516. return;
  19517. }
  19518. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19519. var database;
  19520. if (SceneLoader.ShowLoadingScreen) {
  19521. scene.getEngine().displayLoadingUI();
  19522. }
  19523. var loadSceneFromData = function (data) {
  19524. scene.database = database;
  19525. if (!plugin.load(scene, data, rootUrl)) {
  19526. if (onerror) {
  19527. onerror(scene);
  19528. }
  19529. scene.getEngine().hideLoadingUI();
  19530. return;
  19531. }
  19532. if (onsuccess) {
  19533. onsuccess(scene);
  19534. }
  19535. if (SceneLoader.ShowLoadingScreen) {
  19536. scene.executeWhenReady(function () {
  19537. scene.getEngine().hideLoadingUI();
  19538. });
  19539. }
  19540. };
  19541. var manifestChecked = function (success) {
  19542. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19543. };
  19544. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19545. // Direct load
  19546. loadSceneFromData(sceneFilename.substr(5));
  19547. return;
  19548. }
  19549. if (rootUrl.indexOf("file:") === -1) {
  19550. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19551. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19552. }
  19553. else {
  19554. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19555. }
  19556. };
  19557. // Flags
  19558. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19559. SceneLoader._ShowLoadingScreen = true;
  19560. // Members
  19561. SceneLoader._registeredPlugins = new Array();
  19562. return SceneLoader;
  19563. })();
  19564. BABYLON.SceneLoader = SceneLoader;
  19565. ;
  19566. })(BABYLON || (BABYLON = {}));
  19567. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  19568. (function (BABYLON) {
  19569. var Internals;
  19570. (function (Internals) {
  19571. var checkColors4 = function (colors, count) {
  19572. // Check if color3 was used
  19573. if (colors.length === count * 3) {
  19574. var colors4 = [];
  19575. for (var index = 0; index < colors.length; index += 3) {
  19576. var newIndex = (index / 3) * 4;
  19577. colors4[newIndex] = colors[index];
  19578. colors4[newIndex + 1] = colors[index + 1];
  19579. colors4[newIndex + 2] = colors[index + 2];
  19580. colors4[newIndex + 3] = 1.0;
  19581. }
  19582. return colors4;
  19583. }
  19584. return colors;
  19585. };
  19586. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19587. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  19588. texture.name = parsedTexture.name;
  19589. texture.hasAlpha = parsedTexture.hasAlpha;
  19590. texture.level = parsedTexture.level;
  19591. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19592. return texture;
  19593. };
  19594. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19595. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19596. return null;
  19597. }
  19598. if (parsedTexture.isCube) {
  19599. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19600. }
  19601. var texture;
  19602. if (parsedTexture.mirrorPlane) {
  19603. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19604. texture._waitingRenderList = parsedTexture.renderList;
  19605. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19606. }
  19607. else if (parsedTexture.isRenderTarget) {
  19608. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19609. texture._waitingRenderList = parsedTexture.renderList;
  19610. }
  19611. else {
  19612. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19613. }
  19614. texture.name = parsedTexture.name;
  19615. texture.hasAlpha = parsedTexture.hasAlpha;
  19616. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19617. texture.level = parsedTexture.level;
  19618. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19619. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19620. texture.uOffset = parsedTexture.uOffset;
  19621. texture.vOffset = parsedTexture.vOffset;
  19622. texture.uScale = parsedTexture.uScale;
  19623. texture.vScale = parsedTexture.vScale;
  19624. texture.uAng = parsedTexture.uAng;
  19625. texture.vAng = parsedTexture.vAng;
  19626. texture.wAng = parsedTexture.wAng;
  19627. texture.wrapU = parsedTexture.wrapU;
  19628. texture.wrapV = parsedTexture.wrapV;
  19629. // Animations
  19630. if (parsedTexture.animations) {
  19631. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19632. var parsedAnimation = parsedTexture.animations[animationIndex];
  19633. texture.animations.push(parseAnimation(parsedAnimation));
  19634. }
  19635. }
  19636. return texture;
  19637. };
  19638. var parseSkeleton = function (parsedSkeleton, scene) {
  19639. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19640. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19641. var parsedBone = parsedSkeleton.bones[index];
  19642. var parentBone = null;
  19643. if (parsedBone.parentBoneIndex > -1) {
  19644. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19645. }
  19646. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19647. if (parsedBone.animation) {
  19648. bone.animations.push(parseAnimation(parsedBone.animation));
  19649. }
  19650. }
  19651. return skeleton;
  19652. };
  19653. var parseFresnelParameters = function (parsedFresnelParameters) {
  19654. var fresnelParameters = new BABYLON.FresnelParameters();
  19655. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19656. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19657. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19658. fresnelParameters.bias = parsedFresnelParameters.bias;
  19659. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19660. return fresnelParameters;
  19661. };
  19662. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19663. var material;
  19664. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19665. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19666. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19667. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19668. material.specularPower = parsedMaterial.specularPower;
  19669. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19670. material.alpha = parsedMaterial.alpha;
  19671. material.id = parsedMaterial.id;
  19672. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19673. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19674. material.wireframe = parsedMaterial.wireframe;
  19675. if (parsedMaterial.diffuseTexture) {
  19676. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19677. }
  19678. if (parsedMaterial.diffuseFresnelParameters) {
  19679. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19680. }
  19681. if (parsedMaterial.ambientTexture) {
  19682. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19683. }
  19684. if (parsedMaterial.opacityTexture) {
  19685. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19686. }
  19687. if (parsedMaterial.opacityFresnelParameters) {
  19688. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19689. }
  19690. if (parsedMaterial.reflectionTexture) {
  19691. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19692. }
  19693. if (parsedMaterial.reflectionFresnelParameters) {
  19694. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19695. }
  19696. if (parsedMaterial.emissiveTexture) {
  19697. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19698. }
  19699. if (parsedMaterial.emissiveFresnelParameters) {
  19700. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19701. }
  19702. if (parsedMaterial.specularTexture) {
  19703. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19704. }
  19705. if (parsedMaterial.bumpTexture) {
  19706. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19707. }
  19708. return material;
  19709. };
  19710. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19711. for (var index = 0; index < parsedData.materials.length; index++) {
  19712. var parsedMaterial = parsedData.materials[index];
  19713. if (parsedMaterial.id === id) {
  19714. return parseMaterial(parsedMaterial, scene, rootUrl);
  19715. }
  19716. }
  19717. return null;
  19718. };
  19719. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19720. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19721. multiMaterial.id = parsedMultiMaterial.id;
  19722. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19723. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19724. var subMatId = parsedMultiMaterial.materials[matIndex];
  19725. if (subMatId) {
  19726. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19727. }
  19728. else {
  19729. multiMaterial.subMaterials.push(null);
  19730. }
  19731. }
  19732. return multiMaterial;
  19733. };
  19734. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19735. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19736. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19737. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19738. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19739. var parsedFlare = parsedLensFlareSystem.flares[index];
  19740. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19741. }
  19742. return lensFlareSystem;
  19743. };
  19744. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19745. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19746. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19747. if (parsedParticleSystem.textureName) {
  19748. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19749. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19750. }
  19751. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19752. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19753. particleSystem.minSize = parsedParticleSystem.minSize;
  19754. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19755. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19756. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19757. particleSystem.emitter = emitter;
  19758. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19759. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19760. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19761. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19762. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19763. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19764. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19765. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19766. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19767. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19768. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19769. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19770. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19771. particleSystem.start();
  19772. return particleSystem;
  19773. };
  19774. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19775. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19776. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19777. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19778. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19779. shadowGenerator.getShadowMap().renderList.push(mesh);
  19780. }
  19781. if (parsedShadowGenerator.usePoissonSampling) {
  19782. shadowGenerator.usePoissonSampling = true;
  19783. }
  19784. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19785. shadowGenerator.useVarianceShadowMap = true;
  19786. }
  19787. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19788. shadowGenerator.useBlurVarianceShadowMap = true;
  19789. if (parsedShadowGenerator.blurScale) {
  19790. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19791. }
  19792. if (parsedShadowGenerator.blurBoxOffset) {
  19793. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19794. }
  19795. }
  19796. if (parsedShadowGenerator.bias !== undefined) {
  19797. shadowGenerator.bias = parsedShadowGenerator.bias;
  19798. }
  19799. return shadowGenerator;
  19800. };
  19801. var parseAnimation = function (parsedAnimation) {
  19802. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19803. var dataType = parsedAnimation.dataType;
  19804. var keys = [];
  19805. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19806. var key = parsedAnimation.keys[index];
  19807. var data;
  19808. switch (dataType) {
  19809. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19810. data = key.values[0];
  19811. break;
  19812. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19813. data = BABYLON.Quaternion.FromArray(key.values);
  19814. break;
  19815. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19816. data = BABYLON.Matrix.FromArray(key.values);
  19817. break;
  19818. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19819. default:
  19820. data = BABYLON.Vector3.FromArray(key.values);
  19821. break;
  19822. }
  19823. keys.push({
  19824. frame: key.frame,
  19825. value: data
  19826. });
  19827. }
  19828. animation.setKeys(keys);
  19829. return animation;
  19830. };
  19831. var parseLight = function (parsedLight, scene) {
  19832. var light;
  19833. switch (parsedLight.type) {
  19834. case 0:
  19835. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19836. break;
  19837. case 1:
  19838. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19839. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19840. break;
  19841. case 2:
  19842. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19843. break;
  19844. case 3:
  19845. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19846. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19847. break;
  19848. }
  19849. light.id = parsedLight.id;
  19850. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19851. if (parsedLight.intensity !== undefined) {
  19852. light.intensity = parsedLight.intensity;
  19853. }
  19854. if (parsedLight.range) {
  19855. light.range = parsedLight.range;
  19856. }
  19857. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19858. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19859. if (parsedLight.excludedMeshesIds) {
  19860. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19861. }
  19862. // Parent
  19863. if (parsedLight.parentId) {
  19864. light._waitingParentId = parsedLight.parentId;
  19865. }
  19866. if (parsedLight.includedOnlyMeshesIds) {
  19867. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19868. }
  19869. // Animations
  19870. if (parsedLight.animations) {
  19871. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19872. var parsedAnimation = parsedLight.animations[animationIndex];
  19873. light.animations.push(parseAnimation(parsedAnimation));
  19874. }
  19875. }
  19876. if (parsedLight.autoAnimate) {
  19877. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19878. }
  19879. };
  19880. var parseCamera = function (parsedCamera, scene) {
  19881. var camera;
  19882. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19883. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19884. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19885. var alpha = parsedCamera.alpha;
  19886. var beta = parsedCamera.beta;
  19887. var radius = parsedCamera.radius;
  19888. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19889. var eye_space = parsedCamera.eye_space;
  19890. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  19891. }
  19892. else {
  19893. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19894. }
  19895. }
  19896. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19897. eye_space = parsedCamera.eye_space;
  19898. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  19899. }
  19900. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19901. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19902. }
  19903. else if (parsedCamera.type === "FollowCamera") {
  19904. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19905. camera.heightOffset = parsedCamera.heightOffset;
  19906. camera.radius = parsedCamera.radius;
  19907. camera.rotationOffset = parsedCamera.rotationOffset;
  19908. if (lockedTargetMesh)
  19909. camera.target = lockedTargetMesh;
  19910. }
  19911. else if (parsedCamera.type === "GamepadCamera") {
  19912. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19913. }
  19914. else if (parsedCamera.type === "OculusCamera") {
  19915. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  19916. }
  19917. else if (parsedCamera.type === "OculusGamepadCamera") {
  19918. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  19919. }
  19920. else if (parsedCamera.type === "TouchCamera") {
  19921. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19922. }
  19923. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19924. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19925. }
  19926. else if (parsedCamera.type === "WebVRCamera") {
  19927. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  19928. }
  19929. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  19930. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  19931. }
  19932. else {
  19933. // Free Camera is the default value
  19934. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19935. }
  19936. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19937. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19938. camera.lockedTarget = lockedTargetMesh;
  19939. }
  19940. camera.id = parsedCamera.id;
  19941. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19942. // Parent
  19943. if (parsedCamera.parentId) {
  19944. camera._waitingParentId = parsedCamera.parentId;
  19945. }
  19946. // Target
  19947. if (parsedCamera.target) {
  19948. if (camera.setTarget) {
  19949. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19950. }
  19951. else {
  19952. //For ArcRotate
  19953. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19954. }
  19955. }
  19956. else {
  19957. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19958. }
  19959. camera.fov = parsedCamera.fov;
  19960. camera.minZ = parsedCamera.minZ;
  19961. camera.maxZ = parsedCamera.maxZ;
  19962. camera.speed = parsedCamera.speed;
  19963. camera.inertia = parsedCamera.inertia;
  19964. camera.checkCollisions = parsedCamera.checkCollisions;
  19965. camera.applyGravity = parsedCamera.applyGravity;
  19966. if (parsedCamera.ellipsoid) {
  19967. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19968. }
  19969. // Animations
  19970. if (parsedCamera.animations) {
  19971. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19972. var parsedAnimation = parsedCamera.animations[animationIndex];
  19973. camera.animations.push(parseAnimation(parsedAnimation));
  19974. }
  19975. }
  19976. if (parsedCamera.autoAnimate) {
  19977. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19978. }
  19979. // Layer Mask
  19980. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19981. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19982. }
  19983. else {
  19984. camera.layerMask = 0xFFFFFFFF;
  19985. }
  19986. return camera;
  19987. };
  19988. var parseGeometry = function (parsedGeometry, scene) {
  19989. var id = parsedGeometry.id;
  19990. return scene.getGeometryByID(id);
  19991. };
  19992. var parseBox = function (parsedBox, scene) {
  19993. if (parseGeometry(parsedBox, scene)) {
  19994. return null; // null since geometry could be something else than a box...
  19995. }
  19996. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19997. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19998. scene.pushGeometry(box, true);
  19999. return box;
  20000. };
  20001. var parseSphere = function (parsedSphere, scene) {
  20002. if (parseGeometry(parsedSphere, scene)) {
  20003. return null; // null since geometry could be something else than a sphere...
  20004. }
  20005. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  20006. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  20007. scene.pushGeometry(sphere, true);
  20008. return sphere;
  20009. };
  20010. var parseCylinder = function (parsedCylinder, scene) {
  20011. if (parseGeometry(parsedCylinder, scene)) {
  20012. return null; // null since geometry could be something else than a cylinder...
  20013. }
  20014. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  20015. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  20016. scene.pushGeometry(cylinder, true);
  20017. return cylinder;
  20018. };
  20019. var parseTorus = function (parsedTorus, scene) {
  20020. if (parseGeometry(parsedTorus, scene)) {
  20021. return null; // null since geometry could be something else than a torus...
  20022. }
  20023. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  20024. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  20025. scene.pushGeometry(torus, true);
  20026. return torus;
  20027. };
  20028. var parseGround = function (parsedGround, scene) {
  20029. if (parseGeometry(parsedGround, scene)) {
  20030. return null; // null since geometry could be something else than a ground...
  20031. }
  20032. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  20033. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  20034. scene.pushGeometry(ground, true);
  20035. return ground;
  20036. };
  20037. var parsePlane = function (parsedPlane, scene) {
  20038. if (parseGeometry(parsedPlane, scene)) {
  20039. return null; // null since geometry could be something else than a plane...
  20040. }
  20041. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  20042. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  20043. scene.pushGeometry(plane, true);
  20044. return plane;
  20045. };
  20046. var parseTorusKnot = function (parsedTorusKnot, scene) {
  20047. if (parseGeometry(parsedTorusKnot, scene)) {
  20048. return null; // null since geometry could be something else than a torusKnot...
  20049. }
  20050. 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);
  20051. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  20052. scene.pushGeometry(torusKnot, true);
  20053. return torusKnot;
  20054. };
  20055. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  20056. if (parseGeometry(parsedVertexData, scene)) {
  20057. return null; // null since geometry could be a primitive
  20058. }
  20059. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  20060. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  20061. if (parsedVertexData.delayLoadingFile) {
  20062. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20063. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  20064. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  20065. geometry._delayInfo = [];
  20066. if (parsedVertexData.hasUVs) {
  20067. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20068. }
  20069. if (parsedVertexData.hasUVs2) {
  20070. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20071. }
  20072. if (parsedVertexData.hasColors) {
  20073. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20074. }
  20075. if (parsedVertexData.hasMatricesIndices) {
  20076. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20077. }
  20078. if (parsedVertexData.hasMatricesWeights) {
  20079. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20080. }
  20081. geometry._delayLoadingFunction = importVertexData;
  20082. }
  20083. else {
  20084. importVertexData(parsedVertexData, geometry);
  20085. }
  20086. scene.pushGeometry(geometry, true);
  20087. return geometry;
  20088. };
  20089. var parseMesh = function (parsedMesh, scene, rootUrl) {
  20090. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  20091. mesh.id = parsedMesh.id;
  20092. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20093. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20094. if (parsedMesh.rotationQuaternion) {
  20095. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20096. }
  20097. else if (parsedMesh.rotation) {
  20098. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20099. }
  20100. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20101. if (parsedMesh.localMatrix) {
  20102. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20103. }
  20104. else if (parsedMesh.pivotMatrix) {
  20105. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20106. }
  20107. mesh.setEnabled(parsedMesh.isEnabled);
  20108. mesh.isVisible = parsedMesh.isVisible;
  20109. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20110. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20111. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20112. if (parsedMesh.applyFog !== undefined) {
  20113. mesh.applyFog = parsedMesh.applyFog;
  20114. }
  20115. if (parsedMesh.pickable !== undefined) {
  20116. mesh.isPickable = parsedMesh.pickable;
  20117. }
  20118. if (parsedMesh.alphaIndex !== undefined) {
  20119. mesh.alphaIndex = parsedMesh.alphaIndex;
  20120. }
  20121. mesh.receiveShadows = parsedMesh.receiveShadows;
  20122. mesh.billboardMode = parsedMesh.billboardMode;
  20123. if (parsedMesh.visibility !== undefined) {
  20124. mesh.visibility = parsedMesh.visibility;
  20125. }
  20126. mesh.checkCollisions = parsedMesh.checkCollisions;
  20127. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20128. // Parent
  20129. if (parsedMesh.parentId) {
  20130. mesh._waitingParentId = parsedMesh.parentId;
  20131. }
  20132. // Actions
  20133. if (parsedMesh.actions !== undefined) {
  20134. mesh._waitingActions = parsedMesh.actions;
  20135. }
  20136. // Geometry
  20137. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20138. if (parsedMesh.delayLoadingFile) {
  20139. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20140. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20141. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20142. if (parsedMesh._binaryInfo) {
  20143. mesh._binaryInfo = parsedMesh._binaryInfo;
  20144. }
  20145. mesh._delayInfo = [];
  20146. if (parsedMesh.hasUVs) {
  20147. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20148. }
  20149. if (parsedMesh.hasUVs2) {
  20150. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20151. }
  20152. if (parsedMesh.hasColors) {
  20153. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20154. }
  20155. if (parsedMesh.hasMatricesIndices) {
  20156. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20157. }
  20158. if (parsedMesh.hasMatricesWeights) {
  20159. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20160. }
  20161. mesh._delayLoadingFunction = importGeometry;
  20162. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20163. mesh._checkDelayState();
  20164. }
  20165. }
  20166. else {
  20167. importGeometry(parsedMesh, mesh);
  20168. }
  20169. // Material
  20170. if (parsedMesh.materialId) {
  20171. mesh.setMaterialByID(parsedMesh.materialId);
  20172. }
  20173. else {
  20174. mesh.material = null;
  20175. }
  20176. // Skeleton
  20177. if (parsedMesh.skeletonId > -1) {
  20178. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20179. }
  20180. // Physics
  20181. if (parsedMesh.physicsImpostor) {
  20182. if (!scene.isPhysicsEnabled()) {
  20183. scene.enablePhysics();
  20184. }
  20185. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  20186. }
  20187. // Animations
  20188. if (parsedMesh.animations) {
  20189. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20190. var parsedAnimation = parsedMesh.animations[animationIndex];
  20191. mesh.animations.push(parseAnimation(parsedAnimation));
  20192. }
  20193. }
  20194. if (parsedMesh.autoAnimate) {
  20195. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  20196. }
  20197. // Layer Mask
  20198. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20199. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20200. }
  20201. else {
  20202. mesh.layerMask = 0xFFFFFFFF;
  20203. }
  20204. // Instances
  20205. if (parsedMesh.instances) {
  20206. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20207. var parsedInstance = parsedMesh.instances[index];
  20208. var instance = mesh.createInstance(parsedInstance.name);
  20209. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20210. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20211. if (parsedInstance.rotationQuaternion) {
  20212. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20213. }
  20214. else if (parsedInstance.rotation) {
  20215. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20216. }
  20217. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20218. instance.checkCollisions = mesh.checkCollisions;
  20219. if (parsedMesh.animations) {
  20220. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20221. parsedAnimation = parsedMesh.animations[animationIndex];
  20222. instance.animations.push(parseAnimation(parsedAnimation));
  20223. }
  20224. }
  20225. }
  20226. }
  20227. return mesh;
  20228. };
  20229. var parseActions = function (parsedActions, object, scene) {
  20230. var actionManager = new BABYLON.ActionManager(scene);
  20231. if (object === null)
  20232. scene.actionManager = actionManager;
  20233. else
  20234. object.actionManager = actionManager;
  20235. // instanciate a new object
  20236. var instanciate = function (name, params) {
  20237. var newInstance = Object.create(BABYLON[name].prototype);
  20238. newInstance.constructor.apply(newInstance, params);
  20239. return newInstance;
  20240. };
  20241. var parseParameter = function (name, value, target, propertyPath) {
  20242. if (propertyPath === null) {
  20243. // String, boolean or float
  20244. var floatValue = parseFloat(value);
  20245. if (value === "true" || value === "false")
  20246. return value === "true";
  20247. else
  20248. return isNaN(floatValue) ? value : floatValue;
  20249. }
  20250. var effectiveTarget = propertyPath.split(".");
  20251. var values = value.split(",");
  20252. for (var i = 0; i < effectiveTarget.length; i++) {
  20253. target = target[effectiveTarget[i]];
  20254. }
  20255. // Return appropriate value with its type
  20256. if (target instanceof Boolean)
  20257. return values[0] === "true";
  20258. if (target instanceof String)
  20259. return values[0];
  20260. // Parameters with multiple values such as Vector3 etc.
  20261. var split = new Array();
  20262. for (var i = 0; i < values.length; i++)
  20263. split.push(parseFloat(values[i]));
  20264. if (target instanceof BABYLON.Vector3)
  20265. return BABYLON.Vector3.FromArray(split);
  20266. if (target instanceof BABYLON.Vector4)
  20267. return BABYLON.Vector4.FromArray(split);
  20268. if (target instanceof BABYLON.Color3)
  20269. return BABYLON.Color3.FromArray(split);
  20270. if (target instanceof BABYLON.Color4)
  20271. return BABYLON.Color4.FromArray(split);
  20272. return parseFloat(values[0]);
  20273. };
  20274. // traverse graph per trigger
  20275. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  20276. if (combineArray === void 0) { combineArray = null; }
  20277. if (parsedAction.detached)
  20278. return;
  20279. var parameters = new Array();
  20280. var target = null;
  20281. var propertyPath = null;
  20282. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  20283. // Parameters
  20284. if (parsedAction.type === 2)
  20285. parameters.push(actionManager);
  20286. else
  20287. parameters.push(trigger);
  20288. if (combine) {
  20289. var actions = new Array();
  20290. for (var j = 0; j < parsedAction.combine.length; j++) {
  20291. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  20292. }
  20293. parameters.push(actions);
  20294. }
  20295. else {
  20296. for (var i = 0; i < parsedAction.properties.length; i++) {
  20297. var value = parsedAction.properties[i].value;
  20298. var name = parsedAction.properties[i].name;
  20299. if (name === "target")
  20300. value = target = scene.getNodeByName(value);
  20301. else if (name === "parent")
  20302. value = scene.getNodeByName(value);
  20303. else if (name === "sound")
  20304. value = scene.getSoundByName(value);
  20305. else if (name !== "propertyPath") {
  20306. if (parsedAction.type === 2 && name === "operator")
  20307. value = BABYLON.ValueCondition[value];
  20308. else
  20309. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  20310. }
  20311. else {
  20312. propertyPath = value;
  20313. }
  20314. parameters.push(value);
  20315. }
  20316. }
  20317. parameters.push(condition);
  20318. // If interpolate value action
  20319. if (parsedAction.name === "InterpolateValueAction") {
  20320. var param = parameters[parameters.length - 2];
  20321. parameters[parameters.length - 1] = param;
  20322. parameters[parameters.length - 2] = condition;
  20323. }
  20324. // Action or condition(s) and not CombineAction
  20325. var newAction = instanciate(parsedAction.name, parameters);
  20326. if (combineArray === null) {
  20327. if (newAction instanceof BABYLON.Condition) {
  20328. condition = newAction;
  20329. newAction = action;
  20330. }
  20331. else {
  20332. condition = null;
  20333. if (action)
  20334. action.then(newAction);
  20335. else
  20336. actionManager.registerAction(newAction);
  20337. }
  20338. }
  20339. else {
  20340. combineArray.push(newAction);
  20341. }
  20342. for (var i = 0; i < parsedAction.children.length; i++)
  20343. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  20344. };
  20345. for (var i = 0; i < parsedActions.children.length; i++) {
  20346. var triggerParams;
  20347. var trigger = parsedActions.children[i];
  20348. if (trigger.properties.length > 0) {
  20349. var param = trigger.properties[0].value;
  20350. var value = trigger.properties[0].targetType == null ? param : scene.getMeshByName(param);
  20351. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  20352. }
  20353. else
  20354. triggerParams = BABYLON.ActionManager[trigger.name];
  20355. for (var j = 0; j < trigger.children.length; j++) {
  20356. if (!trigger.detached)
  20357. traverse(trigger.children[j], triggerParams, null, null);
  20358. }
  20359. }
  20360. };
  20361. var parseSound = function (parsedSound, scene, rootUrl) {
  20362. var soundName = parsedSound.name;
  20363. var soundUrl = rootUrl + soundName;
  20364. var options = {
  20365. autoplay: parsedSound.autoplay,
  20366. loop: parsedSound.loop,
  20367. volume: parsedSound.volume,
  20368. spatialSound: parsedSound.spatialSound,
  20369. maxDistance: parsedSound.maxDistance,
  20370. rolloffFactor: parsedSound.rolloffFactor,
  20371. refDistance: parsedSound.refDistance,
  20372. distanceModel: parsedSound.distanceModel,
  20373. playbackRate: parsedSound.playbackRate
  20374. };
  20375. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  20376. scene._removePendingData(newSound);
  20377. }, options);
  20378. scene._addPendingData(newSound);
  20379. if (parsedSound.position) {
  20380. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  20381. newSound.setPosition(soundPosition);
  20382. }
  20383. if (parsedSound.isDirectional) {
  20384. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  20385. if (parsedSound.localDirectionToMesh) {
  20386. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  20387. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  20388. }
  20389. }
  20390. if (parsedSound.connectedMeshId) {
  20391. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  20392. if (connectedMesh) {
  20393. newSound.attachToMesh(connectedMesh);
  20394. }
  20395. }
  20396. };
  20397. var isDescendantOf = function (mesh, names, hierarchyIds) {
  20398. names = (names instanceof Array) ? names : [names];
  20399. for (var i in names) {
  20400. if (mesh.name === names[i]) {
  20401. hierarchyIds.push(mesh.id);
  20402. return true;
  20403. }
  20404. }
  20405. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  20406. hierarchyIds.push(mesh.id);
  20407. return true;
  20408. }
  20409. return false;
  20410. };
  20411. var importVertexData = function (parsedVertexData, geometry) {
  20412. var vertexData = new BABYLON.VertexData();
  20413. // positions
  20414. var positions = parsedVertexData.positions;
  20415. if (positions) {
  20416. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  20417. }
  20418. // normals
  20419. var normals = parsedVertexData.normals;
  20420. if (normals) {
  20421. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20422. }
  20423. // uvs
  20424. var uvs = parsedVertexData.uvs;
  20425. if (uvs) {
  20426. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20427. }
  20428. // uv2s
  20429. var uv2s = parsedVertexData.uv2s;
  20430. if (uv2s) {
  20431. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20432. }
  20433. // colors
  20434. var colors = parsedVertexData.colors;
  20435. if (colors) {
  20436. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20437. }
  20438. // matricesIndices
  20439. var matricesIndices = parsedVertexData.matricesIndices;
  20440. if (matricesIndices) {
  20441. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20442. }
  20443. // matricesWeights
  20444. var matricesWeights = parsedVertexData.matricesWeights;
  20445. if (matricesWeights) {
  20446. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20447. }
  20448. // indices
  20449. var indices = parsedVertexData.indices;
  20450. if (indices) {
  20451. vertexData.indices = indices;
  20452. }
  20453. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20454. };
  20455. var importGeometry = function (parsedGeometry, mesh) {
  20456. var scene = mesh.getScene();
  20457. // Geometry
  20458. var geometryId = parsedGeometry.geometryId;
  20459. if (geometryId) {
  20460. var geometry = scene.getGeometryByID(geometryId);
  20461. if (geometry) {
  20462. geometry.applyToMesh(mesh);
  20463. }
  20464. }
  20465. else if (parsedGeometry instanceof ArrayBuffer) {
  20466. var binaryInfo = mesh._binaryInfo;
  20467. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20468. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20469. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20470. }
  20471. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20472. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20473. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20474. }
  20475. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20476. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20477. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20478. }
  20479. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20480. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20481. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20482. }
  20483. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20484. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20485. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  20486. }
  20487. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20488. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20489. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20490. }
  20491. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20492. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20493. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20494. }
  20495. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20496. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20497. mesh.setIndices(indicesData);
  20498. }
  20499. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20500. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20501. mesh.subMeshes = [];
  20502. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20503. var materialIndex = subMeshesData[(i * 5) + 0];
  20504. var verticesStart = subMeshesData[(i * 5) + 1];
  20505. var verticesCount = subMeshesData[(i * 5) + 2];
  20506. var indexStart = subMeshesData[(i * 5) + 3];
  20507. var indexCount = subMeshesData[(i * 5) + 4];
  20508. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20509. }
  20510. }
  20511. }
  20512. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20513. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20514. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20515. if (parsedGeometry.uvs) {
  20516. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20517. }
  20518. if (parsedGeometry.uvs2) {
  20519. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20520. }
  20521. if (parsedGeometry.colors) {
  20522. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20523. }
  20524. if (parsedGeometry.matricesIndices) {
  20525. if (!parsedGeometry.matricesIndices._isExpanded) {
  20526. var floatIndices = [];
  20527. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20528. var matricesIndex = parsedGeometry.matricesIndices[i];
  20529. floatIndices.push(matricesIndex & 0x000000FF);
  20530. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20531. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20532. floatIndices.push(matricesIndex >> 24);
  20533. }
  20534. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20535. }
  20536. else {
  20537. delete parsedGeometry.matricesIndices._isExpanded;
  20538. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20539. }
  20540. }
  20541. if (parsedGeometry.matricesWeights) {
  20542. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20543. }
  20544. mesh.setIndices(parsedGeometry.indices);
  20545. // SubMeshes
  20546. if (parsedGeometry.subMeshes) {
  20547. mesh.subMeshes = [];
  20548. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20549. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20550. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20551. }
  20552. }
  20553. }
  20554. // Flat shading
  20555. if (mesh._shouldGenerateFlatShading) {
  20556. mesh.convertToFlatShadedMesh();
  20557. delete mesh._shouldGenerateFlatShading;
  20558. }
  20559. // Update
  20560. mesh.computeWorldMatrix(true);
  20561. // Octree
  20562. if (scene._selectionOctree) {
  20563. scene._selectionOctree.addMesh(mesh);
  20564. }
  20565. };
  20566. BABYLON.SceneLoader.RegisterPlugin({
  20567. extensions: ".babylon",
  20568. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20569. var parsedData = JSON.parse(data);
  20570. var loadedSkeletonsIds = [];
  20571. var loadedMaterialsIds = [];
  20572. var hierarchyIds = [];
  20573. for (var index = 0; index < parsedData.meshes.length; index++) {
  20574. var parsedMesh = parsedData.meshes[index];
  20575. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20576. if (meshesNames instanceof Array) {
  20577. // Remove found mesh name from list.
  20578. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20579. }
  20580. // Material ?
  20581. if (parsedMesh.materialId) {
  20582. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20583. if (!materialFound) {
  20584. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20585. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20586. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20587. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20588. var subMatId = parsedMultiMaterial.materials[matIndex];
  20589. loadedMaterialsIds.push(subMatId);
  20590. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20591. }
  20592. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20593. parseMultiMaterial(parsedMultiMaterial, scene);
  20594. materialFound = true;
  20595. break;
  20596. }
  20597. }
  20598. }
  20599. if (!materialFound) {
  20600. loadedMaterialsIds.push(parsedMesh.materialId);
  20601. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  20602. }
  20603. }
  20604. // Skeleton ?
  20605. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20606. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20607. if (!skeletonAlreadyLoaded) {
  20608. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20609. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20610. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20611. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20612. loadedSkeletonsIds.push(parsedSkeleton.id);
  20613. }
  20614. }
  20615. }
  20616. }
  20617. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20618. meshes.push(mesh);
  20619. }
  20620. }
  20621. for (index = 0; index < scene.meshes.length; index++) {
  20622. var currentMesh = scene.meshes[index];
  20623. if (currentMesh._waitingParentId) {
  20624. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20625. currentMesh._waitingParentId = undefined;
  20626. }
  20627. }
  20628. // Particles
  20629. if (parsedData.particleSystems) {
  20630. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20631. var parsedParticleSystem = parsedData.particleSystems[index];
  20632. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20633. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20634. }
  20635. }
  20636. }
  20637. return true;
  20638. },
  20639. load: function (scene, data, rootUrl) {
  20640. var parsedData = JSON.parse(data);
  20641. // Scene
  20642. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20643. scene.autoClear = parsedData.autoClear;
  20644. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20645. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20646. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20647. // Fog
  20648. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20649. scene.fogMode = parsedData.fogMode;
  20650. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20651. scene.fogStart = parsedData.fogStart;
  20652. scene.fogEnd = parsedData.fogEnd;
  20653. scene.fogDensity = parsedData.fogDensity;
  20654. }
  20655. for (var index = 0; index < parsedData.lights.length; index++) {
  20656. var parsedLight = parsedData.lights[index];
  20657. parseLight(parsedLight, scene);
  20658. }
  20659. // Materials
  20660. if (parsedData.materials) {
  20661. for (index = 0; index < parsedData.materials.length; index++) {
  20662. var parsedMaterial = parsedData.materials[index];
  20663. parseMaterial(parsedMaterial, scene, rootUrl);
  20664. }
  20665. }
  20666. if (parsedData.multiMaterials) {
  20667. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20668. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20669. parseMultiMaterial(parsedMultiMaterial, scene);
  20670. }
  20671. }
  20672. // Skeletons
  20673. if (parsedData.skeletons) {
  20674. for (index = 0; index < parsedData.skeletons.length; index++) {
  20675. var parsedSkeleton = parsedData.skeletons[index];
  20676. parseSkeleton(parsedSkeleton, scene);
  20677. }
  20678. }
  20679. // Geometries
  20680. var geometries = parsedData.geometries;
  20681. if (geometries) {
  20682. // Boxes
  20683. var boxes = geometries.boxes;
  20684. if (boxes) {
  20685. for (index = 0; index < boxes.length; index++) {
  20686. var parsedBox = boxes[index];
  20687. parseBox(parsedBox, scene);
  20688. }
  20689. }
  20690. // Spheres
  20691. var spheres = geometries.spheres;
  20692. if (spheres) {
  20693. for (index = 0; index < spheres.length; index++) {
  20694. var parsedSphere = spheres[index];
  20695. parseSphere(parsedSphere, scene);
  20696. }
  20697. }
  20698. // Cylinders
  20699. var cylinders = geometries.cylinders;
  20700. if (cylinders) {
  20701. for (index = 0; index < cylinders.length; index++) {
  20702. var parsedCylinder = cylinders[index];
  20703. parseCylinder(parsedCylinder, scene);
  20704. }
  20705. }
  20706. // Toruses
  20707. var toruses = geometries.toruses;
  20708. if (toruses) {
  20709. for (index = 0; index < toruses.length; index++) {
  20710. var parsedTorus = toruses[index];
  20711. parseTorus(parsedTorus, scene);
  20712. }
  20713. }
  20714. // Grounds
  20715. var grounds = geometries.grounds;
  20716. if (grounds) {
  20717. for (index = 0; index < grounds.length; index++) {
  20718. var parsedGround = grounds[index];
  20719. parseGround(parsedGround, scene);
  20720. }
  20721. }
  20722. // Planes
  20723. var planes = geometries.planes;
  20724. if (planes) {
  20725. for (index = 0; index < planes.length; index++) {
  20726. var parsedPlane = planes[index];
  20727. parsePlane(parsedPlane, scene);
  20728. }
  20729. }
  20730. // TorusKnots
  20731. var torusKnots = geometries.torusKnots;
  20732. if (torusKnots) {
  20733. for (index = 0; index < torusKnots.length; index++) {
  20734. var parsedTorusKnot = torusKnots[index];
  20735. parseTorusKnot(parsedTorusKnot, scene);
  20736. }
  20737. }
  20738. // VertexData
  20739. var vertexData = geometries.vertexData;
  20740. if (vertexData) {
  20741. for (index = 0; index < vertexData.length; index++) {
  20742. var parsedVertexData = vertexData[index];
  20743. parseVertexData(parsedVertexData, scene, rootUrl);
  20744. }
  20745. }
  20746. }
  20747. for (index = 0; index < parsedData.meshes.length; index++) {
  20748. var parsedMesh = parsedData.meshes[index];
  20749. parseMesh(parsedMesh, scene, rootUrl);
  20750. }
  20751. for (index = 0; index < parsedData.cameras.length; index++) {
  20752. var parsedCamera = parsedData.cameras[index];
  20753. parseCamera(parsedCamera, scene);
  20754. }
  20755. if (parsedData.activeCameraID) {
  20756. scene.setActiveCameraByID(parsedData.activeCameraID);
  20757. }
  20758. for (index = 0; index < scene.cameras.length; index++) {
  20759. var camera = scene.cameras[index];
  20760. if (camera._waitingParentId) {
  20761. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20762. camera._waitingParentId = undefined;
  20763. }
  20764. }
  20765. for (index = 0; index < scene.lights.length; index++) {
  20766. var light = scene.lights[index];
  20767. if (light._waitingParentId) {
  20768. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20769. light._waitingParentId = undefined;
  20770. }
  20771. }
  20772. // Sounds
  20773. if (parsedData.sounds) {
  20774. for (index = 0; index < parsedData.sounds.length; index++) {
  20775. var parsedSound = parsedData.sounds[index];
  20776. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20777. parseSound(parsedSound, scene, rootUrl);
  20778. }
  20779. else {
  20780. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20781. }
  20782. }
  20783. }
  20784. for (index = 0; index < scene.meshes.length; index++) {
  20785. var mesh = scene.meshes[index];
  20786. if (mesh._waitingParentId) {
  20787. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20788. mesh._waitingParentId = undefined;
  20789. }
  20790. if (mesh._waitingActions) {
  20791. parseActions(mesh._waitingActions, mesh, scene);
  20792. mesh._waitingActions = undefined;
  20793. }
  20794. }
  20795. // Particles Systems
  20796. if (parsedData.particleSystems) {
  20797. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20798. var parsedParticleSystem = parsedData.particleSystems[index];
  20799. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20800. }
  20801. }
  20802. // Lens flares
  20803. if (parsedData.lensFlareSystems) {
  20804. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20805. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20806. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20807. }
  20808. }
  20809. // Shadows
  20810. if (parsedData.shadowGenerators) {
  20811. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20812. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20813. parseShadowGenerator(parsedShadowGenerator, scene);
  20814. }
  20815. }
  20816. // Actions (scene)
  20817. if (parsedData.actions) {
  20818. parseActions(parsedData.actions, null, scene);
  20819. }
  20820. // Finish
  20821. return true;
  20822. }
  20823. });
  20824. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20825. })(BABYLON || (BABYLON = {}));
  20826. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  20827. (function (BABYLON) {
  20828. // Unique ID when we import meshes from Babylon to CSG
  20829. var currentCSGMeshId = 0;
  20830. // # class Vertex
  20831. // Represents a vertex of a polygon. Use your own vertex class instead of this
  20832. // one to provide additional features like texture coordinates and vertex
  20833. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  20834. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  20835. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  20836. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  20837. // is not used anywhere else.
  20838. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  20839. var Vertex = (function () {
  20840. function Vertex(pos, normal, uv) {
  20841. this.pos = pos;
  20842. this.normal = normal;
  20843. this.uv = uv;
  20844. }
  20845. Vertex.prototype.clone = function () {
  20846. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  20847. };
  20848. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  20849. // orientation of a polygon is flipped.
  20850. Vertex.prototype.flip = function () {
  20851. this.normal = this.normal.scale(-1);
  20852. };
  20853. // Create a new vertex between this vertex and `other` by linearly
  20854. // interpolating all properties using a parameter of `t`. Subclasses should
  20855. // override this to interpolate additional properties.
  20856. Vertex.prototype.interpolate = function (other, t) {
  20857. 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));
  20858. };
  20859. return Vertex;
  20860. })();
  20861. // # class Plane
  20862. // Represents a plane in 3D space.
  20863. var Plane = (function () {
  20864. function Plane(normal, w) {
  20865. this.normal = normal;
  20866. this.w = w;
  20867. }
  20868. Plane.FromPoints = function (a, b, c) {
  20869. var v0 = c.subtract(a);
  20870. var v1 = b.subtract(a);
  20871. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  20872. return null;
  20873. }
  20874. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  20875. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  20876. };
  20877. Plane.prototype.clone = function () {
  20878. return new Plane(this.normal.clone(), this.w);
  20879. };
  20880. Plane.prototype.flip = function () {
  20881. this.normal.scaleInPlace(-1);
  20882. this.w = -this.w;
  20883. };
  20884. // Split `polygon` by this plane if needed, then put the polygon or polygon
  20885. // fragments in the appropriate lists. Coplanar polygons go into either
  20886. // `coplanarFront` or `coplanarBack` depending on their orientation with
  20887. // respect to this plane. Polygons in front or in back of this plane go into
  20888. // either `front` or `back`.
  20889. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  20890. var COPLANAR = 0;
  20891. var FRONT = 1;
  20892. var BACK = 2;
  20893. var SPANNING = 3;
  20894. // Classify each point as well as the entire polygon into one of the above
  20895. // four classes.
  20896. var polygonType = 0;
  20897. var types = [];
  20898. for (var i = 0; i < polygon.vertices.length; i++) {
  20899. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  20900. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  20901. polygonType |= type;
  20902. types.push(type);
  20903. }
  20904. switch (polygonType) {
  20905. case COPLANAR:
  20906. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  20907. break;
  20908. case FRONT:
  20909. front.push(polygon);
  20910. break;
  20911. case BACK:
  20912. back.push(polygon);
  20913. break;
  20914. case SPANNING:
  20915. var f = [], b = [];
  20916. for (i = 0; i < polygon.vertices.length; i++) {
  20917. var j = (i + 1) % polygon.vertices.length;
  20918. var ti = types[i], tj = types[j];
  20919. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  20920. if (ti != BACK)
  20921. f.push(vi);
  20922. if (ti != FRONT)
  20923. b.push(ti != BACK ? vi.clone() : vi);
  20924. if ((ti | tj) == SPANNING) {
  20925. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  20926. var v = vi.interpolate(vj, t);
  20927. f.push(v);
  20928. b.push(v.clone());
  20929. }
  20930. }
  20931. if (f.length >= 3) {
  20932. var poly = new Polygon(f, polygon.shared);
  20933. if (poly.plane)
  20934. front.push(poly);
  20935. }
  20936. if (b.length >= 3) {
  20937. poly = new Polygon(b, polygon.shared);
  20938. if (poly.plane)
  20939. back.push(poly);
  20940. }
  20941. break;
  20942. }
  20943. };
  20944. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  20945. // point is on the plane.
  20946. Plane.EPSILON = 1e-5;
  20947. return Plane;
  20948. })();
  20949. // # class Polygon
  20950. // Represents a convex polygon. The vertices used to initialize a polygon must
  20951. // be coplanar and form a convex loop.
  20952. //
  20953. // Each convex polygon has a `shared` property, which is shared between all
  20954. // polygons that are clones of each other or were split from the same polygon.
  20955. // This can be used to define per-polygon properties (such as surface color).
  20956. var Polygon = (function () {
  20957. function Polygon(vertices, shared) {
  20958. this.vertices = vertices;
  20959. this.shared = shared;
  20960. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  20961. }
  20962. Polygon.prototype.clone = function () {
  20963. var vertices = this.vertices.map(function (v) { return v.clone(); });
  20964. return new Polygon(vertices, this.shared);
  20965. };
  20966. Polygon.prototype.flip = function () {
  20967. this.vertices.reverse().map(function (v) {
  20968. v.flip();
  20969. });
  20970. this.plane.flip();
  20971. };
  20972. return Polygon;
  20973. })();
  20974. // # class Node
  20975. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  20976. // by picking a polygon to split along. That polygon (and all other coplanar
  20977. // polygons) are added directly to that node and the other polygons are added to
  20978. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  20979. // no distinction between internal and leaf nodes.
  20980. var Node = (function () {
  20981. function Node(polygons) {
  20982. this.plane = null;
  20983. this.front = null;
  20984. this.back = null;
  20985. this.polygons = [];
  20986. if (polygons) {
  20987. this.build(polygons);
  20988. }
  20989. }
  20990. Node.prototype.clone = function () {
  20991. var node = new Node();
  20992. node.plane = this.plane && this.plane.clone();
  20993. node.front = this.front && this.front.clone();
  20994. node.back = this.back && this.back.clone();
  20995. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  20996. return node;
  20997. };
  20998. // Convert solid space to empty space and empty space to solid space.
  20999. Node.prototype.invert = function () {
  21000. for (var i = 0; i < this.polygons.length; i++) {
  21001. this.polygons[i].flip();
  21002. }
  21003. if (this.plane) {
  21004. this.plane.flip();
  21005. }
  21006. if (this.front) {
  21007. this.front.invert();
  21008. }
  21009. if (this.back) {
  21010. this.back.invert();
  21011. }
  21012. var temp = this.front;
  21013. this.front = this.back;
  21014. this.back = temp;
  21015. };
  21016. // Recursively remove all polygons in `polygons` that are inside this BSP
  21017. // tree.
  21018. Node.prototype.clipPolygons = function (polygons) {
  21019. if (!this.plane)
  21020. return polygons.slice();
  21021. var front = [], back = [];
  21022. for (var i = 0; i < polygons.length; i++) {
  21023. this.plane.splitPolygon(polygons[i], front, back, front, back);
  21024. }
  21025. if (this.front) {
  21026. front = this.front.clipPolygons(front);
  21027. }
  21028. if (this.back) {
  21029. back = this.back.clipPolygons(back);
  21030. }
  21031. else {
  21032. back = [];
  21033. }
  21034. return front.concat(back);
  21035. };
  21036. // Remove all polygons in this BSP tree that are inside the other BSP tree
  21037. // `bsp`.
  21038. Node.prototype.clipTo = function (bsp) {
  21039. this.polygons = bsp.clipPolygons(this.polygons);
  21040. if (this.front)
  21041. this.front.clipTo(bsp);
  21042. if (this.back)
  21043. this.back.clipTo(bsp);
  21044. };
  21045. // Return a list of all polygons in this BSP tree.
  21046. Node.prototype.allPolygons = function () {
  21047. var polygons = this.polygons.slice();
  21048. if (this.front)
  21049. polygons = polygons.concat(this.front.allPolygons());
  21050. if (this.back)
  21051. polygons = polygons.concat(this.back.allPolygons());
  21052. return polygons;
  21053. };
  21054. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  21055. // new polygons are filtered down to the bottom of the tree and become new
  21056. // nodes there. Each set of polygons is partitioned using the first polygon
  21057. // (no heuristic is used to pick a good split).
  21058. Node.prototype.build = function (polygons) {
  21059. if (!polygons.length)
  21060. return;
  21061. if (!this.plane)
  21062. this.plane = polygons[0].plane.clone();
  21063. var front = [], back = [];
  21064. for (var i = 0; i < polygons.length; i++) {
  21065. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  21066. }
  21067. if (front.length) {
  21068. if (!this.front)
  21069. this.front = new Node();
  21070. this.front.build(front);
  21071. }
  21072. if (back.length) {
  21073. if (!this.back)
  21074. this.back = new Node();
  21075. this.back.build(back);
  21076. }
  21077. };
  21078. return Node;
  21079. })();
  21080. var CSG = (function () {
  21081. function CSG() {
  21082. this.polygons = new Array();
  21083. }
  21084. // Convert BABYLON.Mesh to BABYLON.CSG
  21085. CSG.FromMesh = function (mesh) {
  21086. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  21087. if (mesh instanceof BABYLON.Mesh) {
  21088. mesh.computeWorldMatrix(true);
  21089. var matrix = mesh.getWorldMatrix();
  21090. var meshPosition = mesh.position.clone();
  21091. var meshRotation = mesh.rotation.clone();
  21092. var meshScaling = mesh.scaling.clone();
  21093. }
  21094. else {
  21095. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  21096. }
  21097. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21098. var subMeshes = mesh.subMeshes;
  21099. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  21100. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  21101. vertices = [];
  21102. for (var j = 0; j < 3; j++) {
  21103. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  21104. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  21105. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  21106. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  21107. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  21108. vertex = new Vertex(position, normal, uv);
  21109. vertices.push(vertex);
  21110. }
  21111. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  21112. // To handle the case of degenerated triangle
  21113. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  21114. if (polygon.plane)
  21115. polygons.push(polygon);
  21116. }
  21117. }
  21118. var csg = CSG.FromPolygons(polygons);
  21119. csg.matrix = matrix;
  21120. csg.position = meshPosition;
  21121. csg.rotation = meshRotation;
  21122. csg.scaling = meshScaling;
  21123. currentCSGMeshId++;
  21124. return csg;
  21125. };
  21126. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  21127. CSG.FromPolygons = function (polygons) {
  21128. var csg = new BABYLON.CSG();
  21129. csg.polygons = polygons;
  21130. return csg;
  21131. };
  21132. CSG.prototype.clone = function () {
  21133. var csg = new BABYLON.CSG();
  21134. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  21135. csg.copyTransformAttributes(this);
  21136. return csg;
  21137. };
  21138. CSG.prototype.toPolygons = function () {
  21139. return this.polygons;
  21140. };
  21141. CSG.prototype.union = function (csg) {
  21142. var a = new Node(this.clone().polygons);
  21143. var b = new Node(csg.clone().polygons);
  21144. a.clipTo(b);
  21145. b.clipTo(a);
  21146. b.invert();
  21147. b.clipTo(a);
  21148. b.invert();
  21149. a.build(b.allPolygons());
  21150. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  21151. };
  21152. CSG.prototype.unionInPlace = function (csg) {
  21153. var a = new Node(this.polygons);
  21154. var b = new Node(csg.polygons);
  21155. a.clipTo(b);
  21156. b.clipTo(a);
  21157. b.invert();
  21158. b.clipTo(a);
  21159. b.invert();
  21160. a.build(b.allPolygons());
  21161. this.polygons = a.allPolygons();
  21162. };
  21163. CSG.prototype.subtract = function (csg) {
  21164. var a = new Node(this.clone().polygons);
  21165. var b = new Node(csg.clone().polygons);
  21166. a.invert();
  21167. a.clipTo(b);
  21168. b.clipTo(a);
  21169. b.invert();
  21170. b.clipTo(a);
  21171. b.invert();
  21172. a.build(b.allPolygons());
  21173. a.invert();
  21174. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  21175. };
  21176. CSG.prototype.subtractInPlace = function (csg) {
  21177. var a = new Node(this.polygons);
  21178. var b = new Node(csg.polygons);
  21179. a.invert();
  21180. a.clipTo(b);
  21181. b.clipTo(a);
  21182. b.invert();
  21183. b.clipTo(a);
  21184. b.invert();
  21185. a.build(b.allPolygons());
  21186. a.invert();
  21187. this.polygons = a.allPolygons();
  21188. };
  21189. CSG.prototype.intersect = function (csg) {
  21190. var a = new Node(this.clone().polygons);
  21191. var b = new Node(csg.clone().polygons);
  21192. a.invert();
  21193. b.clipTo(a);
  21194. b.invert();
  21195. a.clipTo(b);
  21196. b.clipTo(a);
  21197. a.build(b.allPolygons());
  21198. a.invert();
  21199. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  21200. };
  21201. CSG.prototype.intersectInPlace = function (csg) {
  21202. var a = new Node(this.polygons);
  21203. var b = new Node(csg.polygons);
  21204. a.invert();
  21205. b.clipTo(a);
  21206. b.invert();
  21207. a.clipTo(b);
  21208. b.clipTo(a);
  21209. a.build(b.allPolygons());
  21210. a.invert();
  21211. this.polygons = a.allPolygons();
  21212. };
  21213. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  21214. // not modified.
  21215. CSG.prototype.inverse = function () {
  21216. var csg = this.clone();
  21217. csg.inverseInPlace();
  21218. return csg;
  21219. };
  21220. CSG.prototype.inverseInPlace = function () {
  21221. this.polygons.map(function (p) {
  21222. p.flip();
  21223. });
  21224. };
  21225. // This is used to keep meshes transformations so they can be restored
  21226. // when we build back a Babylon Mesh
  21227. // NB : All CSG operations are performed in world coordinates
  21228. CSG.prototype.copyTransformAttributes = function (csg) {
  21229. this.matrix = csg.matrix;
  21230. this.position = csg.position;
  21231. this.rotation = csg.rotation;
  21232. this.scaling = csg.scaling;
  21233. return this;
  21234. };
  21235. // Build Raw mesh from CSG
  21236. // Coordinates here are in world space
  21237. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  21238. var matrix = this.matrix.clone();
  21239. matrix.invert();
  21240. 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;
  21241. if (keepSubMeshes) {
  21242. // Sort Polygons, since subMeshes are indices range
  21243. polygons.sort(function (a, b) {
  21244. if (a.shared.meshId === b.shared.meshId) {
  21245. return a.shared.subMeshId - b.shared.subMeshId;
  21246. }
  21247. else {
  21248. return a.shared.meshId - b.shared.meshId;
  21249. }
  21250. });
  21251. }
  21252. for (var i = 0, il = polygons.length; i < il; i++) {
  21253. polygon = polygons[i];
  21254. // Building SubMeshes
  21255. if (!subMesh_dict[polygon.shared.meshId]) {
  21256. subMesh_dict[polygon.shared.meshId] = {};
  21257. }
  21258. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  21259. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  21260. indexStart: +Infinity,
  21261. indexEnd: -Infinity,
  21262. materialIndex: polygon.shared.materialIndex
  21263. };
  21264. }
  21265. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  21266. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  21267. polygonIndices[0] = 0;
  21268. polygonIndices[1] = j - 1;
  21269. polygonIndices[2] = j;
  21270. for (var k = 0; k < 3; k++) {
  21271. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  21272. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  21273. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  21274. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  21275. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  21276. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  21277. // Check if 2 points can be merged
  21278. 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)) {
  21279. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  21280. uvs.push(uv.x, uv.y);
  21281. normals.push(normal.x, normal.y, normal.z);
  21282. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  21283. }
  21284. indices.push(vertex_idx);
  21285. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  21286. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  21287. currentIndex++;
  21288. }
  21289. }
  21290. }
  21291. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  21292. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  21293. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  21294. mesh.setIndices(indices);
  21295. if (keepSubMeshes) {
  21296. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  21297. var materialIndexOffset = 0, materialMaxIndex;
  21298. mesh.subMeshes.length = 0;
  21299. for (var m in subMesh_dict) {
  21300. materialMaxIndex = -1;
  21301. for (var sm in subMesh_dict[m]) {
  21302. subMesh_obj = subMesh_dict[m][sm];
  21303. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  21304. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  21305. }
  21306. materialIndexOffset += ++materialMaxIndex;
  21307. }
  21308. }
  21309. return mesh;
  21310. };
  21311. // Build Mesh from CSG taking material and transforms into account
  21312. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  21313. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  21314. mesh.material = material;
  21315. mesh.position.copyFrom(this.position);
  21316. mesh.rotation.copyFrom(this.rotation);
  21317. mesh.scaling.copyFrom(this.scaling);
  21318. mesh.computeWorldMatrix(true);
  21319. return mesh;
  21320. };
  21321. return CSG;
  21322. })();
  21323. BABYLON.CSG = CSG;
  21324. })(BABYLON || (BABYLON = {}));
  21325. //# sourceMappingURL=babylon.csg.js.map
  21326. var BABYLON;
  21327. (function (BABYLON) {
  21328. var OculusDistortionCorrectionPostProcess = (function (_super) {
  21329. __extends(OculusDistortionCorrectionPostProcess, _super);
  21330. //ANY
  21331. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  21332. var _this = this;
  21333. _super.call(this, name, "oculusDistortionCorrection", [
  21334. 'LensCenter',
  21335. 'Scale',
  21336. 'ScaleIn',
  21337. 'HmdWarpParam'
  21338. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  21339. this._isRightEye = isRightEye;
  21340. this._distortionFactors = cameraSettings.DistortionK;
  21341. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  21342. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  21343. this.onSizeChanged = function () {
  21344. _this.aspectRatio = _this.width * .5 / _this.height;
  21345. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  21346. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  21347. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  21348. };
  21349. this.onApply = function (effect) {
  21350. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  21351. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  21352. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  21353. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  21354. };
  21355. }
  21356. return OculusDistortionCorrectionPostProcess;
  21357. })(BABYLON.PostProcess);
  21358. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  21359. })(BABYLON || (BABYLON = {}));
  21360. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  21361. // 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
  21362. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  21363. var BABYLON;
  21364. (function (BABYLON) {
  21365. (function (JoystickAxis) {
  21366. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  21367. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  21368. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  21369. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  21370. var JoystickAxis = BABYLON.JoystickAxis;
  21371. var VirtualJoystick = (function () {
  21372. function VirtualJoystick(leftJoystick) {
  21373. var _this = this;
  21374. if (leftJoystick) {
  21375. this._leftJoystick = true;
  21376. }
  21377. else {
  21378. this._leftJoystick = false;
  21379. }
  21380. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  21381. VirtualJoystick._globalJoystickIndex++;
  21382. // By default left & right arrow keys are moving the X
  21383. // and up & down keys are moving the Y
  21384. this._axisTargetedByLeftAndRight = 0 /* X */;
  21385. this._axisTargetedByUpAndDown = 1 /* Y */;
  21386. this.reverseLeftRight = false;
  21387. this.reverseUpDown = false;
  21388. // collections of pointers
  21389. this._touches = new BABYLON.SmartCollection();
  21390. this.deltaPosition = BABYLON.Vector3.Zero();
  21391. this._joystickSensibility = 25;
  21392. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  21393. this._rotationSpeed = 25;
  21394. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  21395. this._rotateOnAxisRelativeToMesh = false;
  21396. // injecting a canvas element on top of the canvas 3D game
  21397. if (!VirtualJoystick.vjCanvas) {
  21398. window.addEventListener("resize", function () {
  21399. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  21400. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  21401. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  21402. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  21403. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  21404. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  21405. }, false);
  21406. VirtualJoystick.vjCanvas = document.createElement("canvas");
  21407. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  21408. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  21409. VirtualJoystick.vjCanvas.width = window.innerWidth;
  21410. VirtualJoystick.vjCanvas.height = window.innerHeight;
  21411. VirtualJoystick.vjCanvas.style.width = "100%";
  21412. VirtualJoystick.vjCanvas.style.height = "100%";
  21413. VirtualJoystick.vjCanvas.style.position = "absolute";
  21414. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  21415. VirtualJoystick.vjCanvas.style.top = "0px";
  21416. VirtualJoystick.vjCanvas.style.left = "0px";
  21417. VirtualJoystick.vjCanvas.style.zIndex = "5";
  21418. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  21419. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  21420. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  21421. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  21422. document.body.appendChild(VirtualJoystick.vjCanvas);
  21423. }
  21424. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  21425. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  21426. this.pressed = false;
  21427. // default joystick color
  21428. this._joystickColor = "cyan";
  21429. this._joystickPointerID = -1;
  21430. // current joystick position
  21431. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  21432. // origin joystick position
  21433. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  21434. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  21435. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  21436. _this._onPointerDown(evt);
  21437. }, false);
  21438. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  21439. _this._onPointerMove(evt);
  21440. }, false);
  21441. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  21442. _this._onPointerUp(evt);
  21443. }, false);
  21444. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  21445. _this._onPointerUp(evt);
  21446. }, false);
  21447. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  21448. evt.preventDefault(); // Disables system menu
  21449. }, false);
  21450. requestAnimationFrame(function () {
  21451. _this._drawVirtualJoystick();
  21452. });
  21453. }
  21454. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  21455. this._joystickSensibility = newJoystickSensibility;
  21456. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  21457. };
  21458. VirtualJoystick.prototype._onPointerDown = function (e) {
  21459. var positionOnScreenCondition;
  21460. e.preventDefault();
  21461. if (this._leftJoystick === true) {
  21462. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  21463. }
  21464. else {
  21465. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  21466. }
  21467. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  21468. // First contact will be dedicated to the virtual joystick
  21469. this._joystickPointerID = e.pointerId;
  21470. this._joystickPointerStartPos.x = e.clientX;
  21471. this._joystickPointerStartPos.y = e.clientY;
  21472. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  21473. this._deltaJoystickVector.x = 0;
  21474. this._deltaJoystickVector.y = 0;
  21475. this.pressed = true;
  21476. this._touches.add(e.pointerId.toString(), e);
  21477. }
  21478. else {
  21479. // You can only trigger the action buttons with a joystick declared
  21480. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  21481. this._action();
  21482. this._touches.add(e.pointerId.toString(), e);
  21483. }
  21484. }
  21485. };
  21486. VirtualJoystick.prototype._onPointerMove = function (e) {
  21487. // If the current pointer is the one associated to the joystick (first touch contact)
  21488. if (this._joystickPointerID == e.pointerId) {
  21489. this._joystickPointerPos.x = e.clientX;
  21490. this._joystickPointerPos.y = e.clientY;
  21491. this._deltaJoystickVector = this._joystickPointerPos.clone();
  21492. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  21493. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  21494. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  21495. switch (this._axisTargetedByLeftAndRight) {
  21496. case 0 /* X */:
  21497. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  21498. break;
  21499. case 1 /* Y */:
  21500. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  21501. break;
  21502. case 2 /* Z */:
  21503. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  21504. break;
  21505. }
  21506. var directionUpDown = this.reverseUpDown ? 1 : -1;
  21507. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  21508. switch (this._axisTargetedByUpAndDown) {
  21509. case 0 /* X */:
  21510. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  21511. break;
  21512. case 1 /* Y */:
  21513. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  21514. break;
  21515. case 2 /* Z */:
  21516. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  21517. break;
  21518. }
  21519. }
  21520. else {
  21521. if (this._touches.item(e.pointerId.toString())) {
  21522. this._touches.item(e.pointerId.toString()).x = e.clientX;
  21523. this._touches.item(e.pointerId.toString()).y = e.clientY;
  21524. }
  21525. }
  21526. };
  21527. VirtualJoystick.prototype._onPointerUp = function (e) {
  21528. this._clearCanvas();
  21529. if (this._joystickPointerID == e.pointerId) {
  21530. this._joystickPointerID = -1;
  21531. this.pressed = false;
  21532. }
  21533. this._deltaJoystickVector.x = 0;
  21534. this._deltaJoystickVector.y = 0;
  21535. this._touches.remove(e.pointerId.toString());
  21536. };
  21537. /**
  21538. * Change the color of the virtual joystick
  21539. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  21540. */
  21541. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  21542. this._joystickColor = newColor;
  21543. };
  21544. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  21545. this._action = action;
  21546. };
  21547. // Define which axis you'd like to control for left & right
  21548. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  21549. switch (axis) {
  21550. case 0 /* X */:
  21551. case 1 /* Y */:
  21552. case 2 /* Z */:
  21553. this._axisTargetedByLeftAndRight = axis;
  21554. break;
  21555. default:
  21556. this._axisTargetedByLeftAndRight = 0 /* X */;
  21557. break;
  21558. }
  21559. };
  21560. // Define which axis you'd like to control for up & down
  21561. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  21562. switch (axis) {
  21563. case 0 /* X */:
  21564. case 1 /* Y */:
  21565. case 2 /* Z */:
  21566. this._axisTargetedByUpAndDown = axis;
  21567. break;
  21568. default:
  21569. this._axisTargetedByUpAndDown = 1 /* Y */;
  21570. break;
  21571. }
  21572. };
  21573. VirtualJoystick.prototype._clearCanvas = function () {
  21574. if (this._leftJoystick) {
  21575. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  21576. }
  21577. else {
  21578. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  21579. }
  21580. };
  21581. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  21582. var _this = this;
  21583. if (this.pressed) {
  21584. this._clearCanvas();
  21585. this._touches.forEach(function (touch) {
  21586. if (touch.pointerId === _this._joystickPointerID) {
  21587. VirtualJoystick.vjCanvasContext.beginPath();
  21588. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21589. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  21590. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  21591. VirtualJoystick.vjCanvasContext.stroke();
  21592. VirtualJoystick.vjCanvasContext.beginPath();
  21593. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21594. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  21595. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  21596. VirtualJoystick.vjCanvasContext.stroke();
  21597. VirtualJoystick.vjCanvasContext.beginPath();
  21598. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21599. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  21600. VirtualJoystick.vjCanvasContext.stroke();
  21601. }
  21602. else {
  21603. VirtualJoystick.vjCanvasContext.beginPath();
  21604. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  21605. VirtualJoystick.vjCanvasContext.beginPath();
  21606. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  21607. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  21608. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  21609. VirtualJoystick.vjCanvasContext.stroke();
  21610. }
  21611. ;
  21612. });
  21613. }
  21614. requestAnimationFrame(function () {
  21615. _this._drawVirtualJoystick();
  21616. });
  21617. };
  21618. VirtualJoystick.prototype.releaseCanvas = function () {
  21619. if (VirtualJoystick.vjCanvas) {
  21620. document.body.removeChild(VirtualJoystick.vjCanvas);
  21621. VirtualJoystick.vjCanvas = null;
  21622. }
  21623. };
  21624. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  21625. VirtualJoystick._globalJoystickIndex = 0;
  21626. return VirtualJoystick;
  21627. })();
  21628. BABYLON.VirtualJoystick = VirtualJoystick;
  21629. })(BABYLON || (BABYLON = {}));
  21630. //# sourceMappingURL=babylon.virtualJoystick.js.map
  21631. var BABYLON;
  21632. (function (BABYLON) {
  21633. var OculusRiftDevKit2013_Metric = {
  21634. HResolution: 1280,
  21635. VResolution: 800,
  21636. HScreenSize: 0.149759993,
  21637. VScreenSize: 0.0935999975,
  21638. VScreenCenter: 0.0467999987,
  21639. EyeToScreenDistance: 0.0410000011,
  21640. LensSeparationDistance: 0.0635000020,
  21641. InterpupillaryDistance: 0.0640000030,
  21642. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21643. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21644. PostProcessScaleFactor: 1.714605507808412,
  21645. LensCenterOffset: 0.151976421
  21646. };
  21647. var _OculusInnerCamera = (function (_super) {
  21648. __extends(_OculusInnerCamera, _super);
  21649. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  21650. _super.call(this, name, position, scene);
  21651. this._workMatrix = new BABYLON.Matrix();
  21652. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21653. // Constants
  21654. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21655. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21656. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21657. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21658. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21659. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21660. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21661. // Postprocess
  21662. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21663. }
  21664. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  21665. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21666. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21667. return this._projectionMatrix;
  21668. };
  21669. _OculusInnerCamera.prototype._getViewMatrix = function () {
  21670. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21671. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21672. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21673. // Computing target and final matrix
  21674. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21675. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21676. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21677. return this._viewMatrix;
  21678. };
  21679. return _OculusInnerCamera;
  21680. })(BABYLON.FreeCamera);
  21681. var OculusCamera = (function (_super) {
  21682. __extends(OculusCamera, _super);
  21683. function OculusCamera(name, position, scene) {
  21684. _super.call(this, name, position, scene);
  21685. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  21686. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  21687. this.subCameras.push(this._leftCamera);
  21688. this.subCameras.push(this._rightCamera);
  21689. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21690. }
  21691. OculusCamera.prototype._update = function () {
  21692. this._leftCamera.position.copyFrom(this.position);
  21693. this._rightCamera.position.copyFrom(this.position);
  21694. this._updateCamera(this._leftCamera);
  21695. this._updateCamera(this._rightCamera);
  21696. _super.prototype._update.call(this);
  21697. };
  21698. OculusCamera.prototype._updateCamera = function (camera) {
  21699. camera.minZ = this.minZ;
  21700. camera.maxZ = this.maxZ;
  21701. camera.rotation.x = this.rotation.x;
  21702. camera.rotation.y = this.rotation.y;
  21703. camera.rotation.z = this.rotation.z;
  21704. };
  21705. // Oculus events
  21706. OculusCamera.prototype._onOrientationEvent = function (evt) {
  21707. var yaw = evt.alpha / 180 * Math.PI;
  21708. var pitch = evt.beta / 180 * Math.PI;
  21709. var roll = evt.gamma / 180 * Math.PI;
  21710. if (!this._offsetOrientation) {
  21711. this._offsetOrientation = {
  21712. yaw: yaw,
  21713. pitch: pitch,
  21714. roll: roll
  21715. };
  21716. return;
  21717. }
  21718. else {
  21719. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21720. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21721. this.rotation.z += this._offsetOrientation.roll - roll;
  21722. this._offsetOrientation.yaw = yaw;
  21723. this._offsetOrientation.pitch = pitch;
  21724. this._offsetOrientation.roll = roll;
  21725. }
  21726. };
  21727. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  21728. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21729. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21730. };
  21731. OculusCamera.prototype.detachControl = function (element) {
  21732. _super.prototype.detachControl.call(this, element);
  21733. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21734. };
  21735. return OculusCamera;
  21736. })(BABYLON.FreeCamera);
  21737. BABYLON.OculusCamera = OculusCamera;
  21738. })(BABYLON || (BABYLON = {}));
  21739. //# sourceMappingURL=babylon.oculusCamera.js.map
  21740. var BABYLON;
  21741. (function (BABYLON) {
  21742. var OculusRiftDevKit2013_Metric = {
  21743. HResolution: 1280,
  21744. VResolution: 800,
  21745. HScreenSize: 0.149759993,
  21746. VScreenSize: 0.0935999975,
  21747. VScreenCenter: 0.0467999987,
  21748. EyeToScreenDistance: 0.0410000011,
  21749. LensSeparationDistance: 0.0635000020,
  21750. InterpupillaryDistance: 0.0640000030,
  21751. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21752. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21753. PostProcessScaleFactor: 1.714605507808412,
  21754. LensCenterOffset: 0.151976421
  21755. };
  21756. var _OculusInnerGamepadCamera = (function (_super) {
  21757. __extends(_OculusInnerGamepadCamera, _super);
  21758. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  21759. _super.call(this, name, position, scene);
  21760. this._workMatrix = new BABYLON.Matrix();
  21761. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21762. // Constants
  21763. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21764. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21765. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21766. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21767. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21768. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21769. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21770. // Postprocess
  21771. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21772. }
  21773. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  21774. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21775. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21776. return this._projectionMatrix;
  21777. };
  21778. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  21779. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21780. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21781. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21782. // Computing target and final matrix
  21783. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21784. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21785. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21786. return this._viewMatrix;
  21787. };
  21788. return _OculusInnerGamepadCamera;
  21789. })(BABYLON.FreeCamera);
  21790. var OculusGamepadCamera = (function (_super) {
  21791. __extends(OculusGamepadCamera, _super);
  21792. function OculusGamepadCamera(name, position, scene) {
  21793. var _this = this;
  21794. _super.call(this, name, position, scene);
  21795. this.angularSensibility = 200;
  21796. this.moveSensibility = 75;
  21797. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  21798. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  21799. this.subCameras.push(this._leftCamera);
  21800. this.subCameras.push(this._rightCamera);
  21801. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21802. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  21803. _this._onNewGameConnected(gamepad);
  21804. });
  21805. }
  21806. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  21807. // Only the first gamepad can control the camera
  21808. if (gamepad.index === 0) {
  21809. this._gamepad = gamepad;
  21810. }
  21811. };
  21812. OculusGamepadCamera.prototype._update = function () {
  21813. this._leftCamera.position.copyFrom(this.position);
  21814. this._rightCamera.position.copyFrom(this.position);
  21815. this._updateCamera(this._leftCamera);
  21816. this._updateCamera(this._rightCamera);
  21817. _super.prototype._update.call(this);
  21818. };
  21819. OculusGamepadCamera.prototype._checkInputs = function () {
  21820. if (!this._gamepad) {
  21821. return;
  21822. }
  21823. var LSValues = this._gamepad.leftStick;
  21824. var normalizedLX = LSValues.x / this.moveSensibility;
  21825. var normalizedLY = LSValues.y / this.moveSensibility;
  21826. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  21827. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  21828. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21829. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  21830. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21831. };
  21832. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  21833. camera.minZ = this.minZ;
  21834. camera.maxZ = this.maxZ;
  21835. camera.rotation.x = this.rotation.x;
  21836. camera.rotation.y = this.rotation.y;
  21837. camera.rotation.z = this.rotation.z;
  21838. };
  21839. // Oculus events
  21840. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  21841. var yaw = evt.alpha / 180 * Math.PI;
  21842. var pitch = evt.beta / 180 * Math.PI;
  21843. var roll = evt.gamma / 180 * Math.PI;
  21844. if (!this._offsetOrientation) {
  21845. this._offsetOrientation = {
  21846. yaw: yaw,
  21847. pitch: pitch,
  21848. roll: roll
  21849. };
  21850. return;
  21851. }
  21852. else {
  21853. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21854. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21855. this.rotation.z += this._offsetOrientation.roll - roll;
  21856. this._offsetOrientation.yaw = yaw;
  21857. this._offsetOrientation.pitch = pitch;
  21858. this._offsetOrientation.roll = roll;
  21859. }
  21860. };
  21861. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  21862. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21863. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21864. };
  21865. OculusGamepadCamera.prototype.detachControl = function (element) {
  21866. _super.prototype.detachControl.call(this, element);
  21867. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21868. };
  21869. OculusGamepadCamera.prototype.dispose = function () {
  21870. this._gamepads.dispose();
  21871. _super.prototype.dispose.call(this);
  21872. };
  21873. return OculusGamepadCamera;
  21874. })(BABYLON.FreeCamera);
  21875. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  21876. })(BABYLON || (BABYLON = {}));
  21877. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  21878. var BABYLON;
  21879. (function (BABYLON) {
  21880. // We're mainly based on the logic defined into the FreeCamera code
  21881. var VirtualJoysticksCamera = (function (_super) {
  21882. __extends(VirtualJoysticksCamera, _super);
  21883. function VirtualJoysticksCamera(name, position, scene) {
  21884. _super.call(this, name, position, scene);
  21885. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  21886. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  21887. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  21888. this._leftjoystick.setJoystickSensibility(0.15);
  21889. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  21890. this._rightjoystick.setAxisForUpDown(0 /* X */);
  21891. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  21892. this._rightjoystick.reverseUpDown = true;
  21893. this._rightjoystick.setJoystickSensibility(0.05);
  21894. this._rightjoystick.setJoystickColor("yellow");
  21895. }
  21896. VirtualJoysticksCamera.prototype._checkInputs = function () {
  21897. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21898. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  21899. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21900. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  21901. if (!this._leftjoystick.pressed) {
  21902. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  21903. }
  21904. if (!this._rightjoystick.pressed) {
  21905. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  21906. }
  21907. };
  21908. VirtualJoysticksCamera.prototype.dispose = function () {
  21909. this._leftjoystick.releaseCanvas();
  21910. _super.prototype.dispose.call(this);
  21911. };
  21912. return VirtualJoysticksCamera;
  21913. })(BABYLON.FreeCamera);
  21914. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  21915. })(BABYLON || (BABYLON = {}));
  21916. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  21917. var BABYLON;
  21918. (function (BABYLON) {
  21919. var ShaderMaterial = (function (_super) {
  21920. __extends(ShaderMaterial, _super);
  21921. function ShaderMaterial(name, scene, shaderPath, options) {
  21922. _super.call(this, name, scene);
  21923. this._textures = new Array();
  21924. this._floats = new Array();
  21925. this._floatsArrays = {};
  21926. this._colors3 = new Array();
  21927. this._colors4 = new Array();
  21928. this._vectors2 = new Array();
  21929. this._vectors3 = new Array();
  21930. this._matrices = new Array();
  21931. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  21932. this._shaderPath = shaderPath;
  21933. options.needAlphaBlending = options.needAlphaBlending || false;
  21934. options.needAlphaTesting = options.needAlphaTesting || false;
  21935. options.attributes = options.attributes || ["position", "normal", "uv"];
  21936. options.uniforms = options.uniforms || ["worldViewProjection"];
  21937. options.samplers = options.samplers || [];
  21938. this._options = options;
  21939. }
  21940. ShaderMaterial.prototype.needAlphaBlending = function () {
  21941. return this._options.needAlphaBlending;
  21942. };
  21943. ShaderMaterial.prototype.needAlphaTesting = function () {
  21944. return this._options.needAlphaTesting;
  21945. };
  21946. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  21947. if (this._options.uniforms.indexOf(uniformName) === -1) {
  21948. this._options.uniforms.push(uniformName);
  21949. }
  21950. };
  21951. ShaderMaterial.prototype.setTexture = function (name, texture) {
  21952. if (this._options.samplers.indexOf(name) === -1) {
  21953. this._options.samplers.push(name);
  21954. }
  21955. this._textures[name] = texture;
  21956. return this;
  21957. };
  21958. ShaderMaterial.prototype.setFloat = function (name, value) {
  21959. this._checkUniform(name);
  21960. this._floats[name] = value;
  21961. return this;
  21962. };
  21963. ShaderMaterial.prototype.setFloats = function (name, value) {
  21964. this._checkUniform(name);
  21965. this._floatsArrays[name] = value;
  21966. return this;
  21967. };
  21968. ShaderMaterial.prototype.setColor3 = function (name, value) {
  21969. this._checkUniform(name);
  21970. this._colors3[name] = value;
  21971. return this;
  21972. };
  21973. ShaderMaterial.prototype.setColor4 = function (name, value) {
  21974. this._checkUniform(name);
  21975. this._colors4[name] = value;
  21976. return this;
  21977. };
  21978. ShaderMaterial.prototype.setVector2 = function (name, value) {
  21979. this._checkUniform(name);
  21980. this._vectors2[name] = value;
  21981. return this;
  21982. };
  21983. ShaderMaterial.prototype.setVector3 = function (name, value) {
  21984. this._checkUniform(name);
  21985. this._vectors3[name] = value;
  21986. return this;
  21987. };
  21988. ShaderMaterial.prototype.setMatrix = function (name, value) {
  21989. this._checkUniform(name);
  21990. this._matrices[name] = value;
  21991. return this;
  21992. };
  21993. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  21994. var scene = this.getScene();
  21995. var engine = scene.getEngine();
  21996. if (!this.checkReadyOnEveryCall) {
  21997. if (this._renderId === scene.getRenderId()) {
  21998. return true;
  21999. }
  22000. }
  22001. // Instances
  22002. var defines = [];
  22003. var fallbacks = new BABYLON.EffectFallbacks();
  22004. if (useInstances) {
  22005. defines.push("#define INSTANCES");
  22006. }
  22007. // Bones
  22008. if (mesh && mesh.useBones) {
  22009. defines.push("#define BONES");
  22010. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  22011. defines.push("#define BONES4");
  22012. fallbacks.addFallback(0, "BONES4");
  22013. }
  22014. // Alpha test
  22015. if (engine.getAlphaTesting()) {
  22016. defines.push("#define ALPHATEST");
  22017. }
  22018. var previousEffect = this._effect;
  22019. var join = defines.join("\n");
  22020. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  22021. if (!this._effect.isReady()) {
  22022. return false;
  22023. }
  22024. if (previousEffect !== this._effect) {
  22025. scene.resetCachedMaterial();
  22026. }
  22027. this._renderId = scene.getRenderId();
  22028. return true;
  22029. };
  22030. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  22031. var scene = this.getScene();
  22032. if (this._options.uniforms.indexOf("world") !== -1) {
  22033. this._effect.setMatrix("world", world);
  22034. }
  22035. if (this._options.uniforms.indexOf("worldView") !== -1) {
  22036. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  22037. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  22038. }
  22039. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  22040. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  22041. }
  22042. };
  22043. ShaderMaterial.prototype.bind = function (world, mesh) {
  22044. // Std values
  22045. this.bindOnlyWorldMatrix(world);
  22046. if (this.getScene().getCachedMaterial() !== this) {
  22047. if (this._options.uniforms.indexOf("view") !== -1) {
  22048. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  22049. }
  22050. if (this._options.uniforms.indexOf("projection") !== -1) {
  22051. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  22052. }
  22053. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  22054. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  22055. }
  22056. // Bones
  22057. if (mesh && mesh.useBones) {
  22058. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  22059. }
  22060. for (var name in this._textures) {
  22061. this._effect.setTexture(name, this._textures[name]);
  22062. }
  22063. for (name in this._floats) {
  22064. this._effect.setFloat(name, this._floats[name]);
  22065. }
  22066. for (name in this._floatsArrays) {
  22067. this._effect.setArray(name, this._floatsArrays[name]);
  22068. }
  22069. for (name in this._colors3) {
  22070. this._effect.setColor3(name, this._colors3[name]);
  22071. }
  22072. for (name in this._colors4) {
  22073. var color = this._colors4[name];
  22074. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  22075. }
  22076. for (name in this._vectors2) {
  22077. this._effect.setVector2(name, this._vectors2[name]);
  22078. }
  22079. for (name in this._vectors3) {
  22080. this._effect.setVector3(name, this._vectors3[name]);
  22081. }
  22082. for (name in this._matrices) {
  22083. this._effect.setMatrix(name, this._matrices[name]);
  22084. }
  22085. }
  22086. _super.prototype.bind.call(this, world, mesh);
  22087. };
  22088. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  22089. for (var name in this._textures) {
  22090. this._textures[name].dispose();
  22091. }
  22092. this._textures = [];
  22093. _super.prototype.dispose.call(this, forceDisposeEffect);
  22094. };
  22095. return ShaderMaterial;
  22096. })(BABYLON.Material);
  22097. BABYLON.ShaderMaterial = ShaderMaterial;
  22098. })(BABYLON || (BABYLON = {}));
  22099. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  22100. (function (BABYLON) {
  22101. var VertexData = (function () {
  22102. function VertexData() {
  22103. }
  22104. VertexData.prototype.set = function (data, kind) {
  22105. switch (kind) {
  22106. case BABYLON.VertexBuffer.PositionKind:
  22107. this.positions = data;
  22108. break;
  22109. case BABYLON.VertexBuffer.NormalKind:
  22110. this.normals = data;
  22111. break;
  22112. case BABYLON.VertexBuffer.UVKind:
  22113. this.uvs = data;
  22114. break;
  22115. case BABYLON.VertexBuffer.UV2Kind:
  22116. this.uv2s = data;
  22117. break;
  22118. case BABYLON.VertexBuffer.ColorKind:
  22119. this.colors = data;
  22120. break;
  22121. case BABYLON.VertexBuffer.MatricesIndicesKind:
  22122. this.matricesIndices = data;
  22123. break;
  22124. case BABYLON.VertexBuffer.MatricesWeightsKind:
  22125. this.matricesWeights = data;
  22126. break;
  22127. }
  22128. };
  22129. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  22130. this._applyTo(mesh, updatable);
  22131. };
  22132. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  22133. this._applyTo(geometry, updatable);
  22134. };
  22135. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  22136. this._update(mesh);
  22137. };
  22138. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  22139. this._update(geometry);
  22140. };
  22141. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  22142. if (this.positions) {
  22143. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  22144. }
  22145. if (this.normals) {
  22146. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  22147. }
  22148. if (this.uvs) {
  22149. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  22150. }
  22151. if (this.uv2s) {
  22152. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  22153. }
  22154. if (this.colors) {
  22155. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  22156. }
  22157. if (this.matricesIndices) {
  22158. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  22159. }
  22160. if (this.matricesWeights) {
  22161. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  22162. }
  22163. if (this.indices) {
  22164. meshOrGeometry.setIndices(this.indices);
  22165. }
  22166. };
  22167. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  22168. if (this.positions) {
  22169. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  22170. }
  22171. if (this.normals) {
  22172. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  22173. }
  22174. if (this.uvs) {
  22175. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  22176. }
  22177. if (this.uv2s) {
  22178. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  22179. }
  22180. if (this.colors) {
  22181. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  22182. }
  22183. if (this.matricesIndices) {
  22184. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  22185. }
  22186. if (this.matricesWeights) {
  22187. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  22188. }
  22189. if (this.indices) {
  22190. meshOrGeometry.setIndices(this.indices);
  22191. }
  22192. };
  22193. VertexData.prototype.transform = function (matrix) {
  22194. var transformed = BABYLON.Vector3.Zero();
  22195. if (this.positions) {
  22196. var position = BABYLON.Vector3.Zero();
  22197. for (var index = 0; index < this.positions.length; index += 3) {
  22198. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  22199. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  22200. this.positions[index] = transformed.x;
  22201. this.positions[index + 1] = transformed.y;
  22202. this.positions[index + 2] = transformed.z;
  22203. }
  22204. }
  22205. if (this.normals) {
  22206. var normal = BABYLON.Vector3.Zero();
  22207. for (index = 0; index < this.normals.length; index += 3) {
  22208. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  22209. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  22210. this.normals[index] = transformed.x;
  22211. this.normals[index + 1] = transformed.y;
  22212. this.normals[index + 2] = transformed.z;
  22213. }
  22214. }
  22215. };
  22216. VertexData.prototype.merge = function (other) {
  22217. if (other.indices) {
  22218. if (!this.indices) {
  22219. this.indices = [];
  22220. }
  22221. var offset = this.positions ? this.positions.length / 3 : 0;
  22222. for (var index = 0; index < other.indices.length; index++) {
  22223. this.indices.push(other.indices[index] + offset);
  22224. }
  22225. }
  22226. if (other.positions) {
  22227. if (!this.positions) {
  22228. this.positions = [];
  22229. }
  22230. for (index = 0; index < other.positions.length; index++) {
  22231. this.positions.push(other.positions[index]);
  22232. }
  22233. }
  22234. if (other.normals) {
  22235. if (!this.normals) {
  22236. this.normals = [];
  22237. }
  22238. for (index = 0; index < other.normals.length; index++) {
  22239. this.normals.push(other.normals[index]);
  22240. }
  22241. }
  22242. if (other.uvs) {
  22243. if (!this.uvs) {
  22244. this.uvs = [];
  22245. }
  22246. for (index = 0; index < other.uvs.length; index++) {
  22247. this.uvs.push(other.uvs[index]);
  22248. }
  22249. }
  22250. if (other.uv2s) {
  22251. if (!this.uv2s) {
  22252. this.uv2s = [];
  22253. }
  22254. for (index = 0; index < other.uv2s.length; index++) {
  22255. this.uv2s.push(other.uv2s[index]);
  22256. }
  22257. }
  22258. if (other.matricesIndices) {
  22259. if (!this.matricesIndices) {
  22260. this.matricesIndices = [];
  22261. }
  22262. for (index = 0; index < other.matricesIndices.length; index++) {
  22263. this.matricesIndices.push(other.matricesIndices[index]);
  22264. }
  22265. }
  22266. if (other.matricesWeights) {
  22267. if (!this.matricesWeights) {
  22268. this.matricesWeights = [];
  22269. }
  22270. for (index = 0; index < other.matricesWeights.length; index++) {
  22271. this.matricesWeights.push(other.matricesWeights[index]);
  22272. }
  22273. }
  22274. if (other.colors) {
  22275. if (!this.colors) {
  22276. this.colors = [];
  22277. }
  22278. for (index = 0; index < other.colors.length; index++) {
  22279. this.colors.push(other.colors[index]);
  22280. }
  22281. }
  22282. };
  22283. // Statics
  22284. VertexData.ExtractFromMesh = function (mesh) {
  22285. return VertexData._ExtractFrom(mesh);
  22286. };
  22287. VertexData.ExtractFromGeometry = function (geometry) {
  22288. return VertexData._ExtractFrom(geometry);
  22289. };
  22290. VertexData._ExtractFrom = function (meshOrGeometry) {
  22291. var result = new VertexData();
  22292. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22293. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22294. }
  22295. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22296. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22297. }
  22298. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22299. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22300. }
  22301. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  22302. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  22303. }
  22304. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  22305. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  22306. }
  22307. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22308. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22309. }
  22310. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22311. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22312. }
  22313. result.indices = meshOrGeometry.getIndices();
  22314. return result;
  22315. };
  22316. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  22317. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22318. closeArray = closeArray || false;
  22319. closePath = closePath || false;
  22320. var defaultOffset = Math.floor(pathArray[0].length / 2);
  22321. offset = offset || defaultOffset;
  22322. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  22323. var positions = [];
  22324. var indices = [];
  22325. var normals = [];
  22326. var uvs = [];
  22327. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  22328. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  22329. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  22330. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  22331. var minlg; // minimal length among all paths from pathArray
  22332. var lg = []; // array of path lengths : nb of vertex per path
  22333. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  22334. var p; // path iterator
  22335. var i; // point iterator
  22336. var j; // point iterator
  22337. // if single path in pathArray
  22338. if (pathArray.length < 2) {
  22339. var ar1 = [];
  22340. var ar2 = [];
  22341. for (i = 0; i < pathArray[0].length - offset; i++) {
  22342. ar1.push(pathArray[0][i]);
  22343. ar2.push(pathArray[0][i + offset]);
  22344. }
  22345. pathArray = [ar1, ar2];
  22346. }
  22347. // positions and horizontal distances (u)
  22348. var idc = 0;
  22349. minlg = pathArray[0].length;
  22350. for (p = 0; p < pathArray.length; p++) {
  22351. uTotalDistance[p] = 0;
  22352. us[p] = [0];
  22353. var path = pathArray[p];
  22354. var l = path.length;
  22355. minlg = (minlg < l) ? minlg : l;
  22356. lg[p] = l;
  22357. idx[p] = idc;
  22358. j = 0;
  22359. while (j < l) {
  22360. positions.push(path[j].x, path[j].y, path[j].z);
  22361. if (j > 0) {
  22362. var vectlg = path[j].subtract(path[j - 1]).length();
  22363. var dist = vectlg + uTotalDistance[p];
  22364. us[p].push(dist);
  22365. uTotalDistance[p] = dist;
  22366. }
  22367. j++;
  22368. }
  22369. if (closePath) {
  22370. vectlg = path[0].subtract(path[j - 1]).length();
  22371. dist = vectlg + uTotalDistance[p];
  22372. uTotalDistance[p] = dist;
  22373. }
  22374. idc += l;
  22375. }
  22376. for (i = 0; i < minlg; i++) {
  22377. vTotalDistance[i] = 0;
  22378. vs[i] = [0];
  22379. var path1;
  22380. var path2;
  22381. for (p = 0; p < pathArray.length - 1; p++) {
  22382. path1 = pathArray[p];
  22383. path2 = pathArray[p + 1];
  22384. vectlg = path2[i].subtract(path1[i]).length();
  22385. dist = vectlg + vTotalDistance[i];
  22386. vs[i].push(dist);
  22387. vTotalDistance[i] = dist;
  22388. }
  22389. if (closeArray) {
  22390. path1 = pathArray[p];
  22391. path2 = pathArray[0];
  22392. vectlg = path2[i].subtract(path1[i]).length();
  22393. dist = vectlg + vTotalDistance[i];
  22394. vTotalDistance[i] = dist;
  22395. }
  22396. }
  22397. // uvs
  22398. var u;
  22399. var v;
  22400. for (p = 0; p < pathArray.length; p++) {
  22401. for (i = 0; i < minlg; i++) {
  22402. u = us[p][i] / uTotalDistance[p];
  22403. v = vs[i][p] / vTotalDistance[i];
  22404. uvs.push(u, v);
  22405. }
  22406. }
  22407. // indices
  22408. p = 0; // path index
  22409. var pi = 0; // positions array index
  22410. var l1 = lg[p] - 1; // path1 length
  22411. var l2 = lg[p + 1] - 1; // path2 length
  22412. var min = (l1 < l2) ? l1 : l2; // current path stop index
  22413. var shft = idx[1] - idx[0]; // shift
  22414. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  22415. var t1; // two consecutive triangles, so 4 points : point1
  22416. var t2; // point2
  22417. var t3; // point3
  22418. var t4; // point4
  22419. while (pi <= min && p < path1nb) {
  22420. // 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
  22421. t1 = pi;
  22422. t2 = pi + shft;
  22423. t3 = pi + 1;
  22424. t4 = pi + shft + 1;
  22425. indices.push(pi, pi + shft, pi + 1);
  22426. indices.push(pi + shft + 1, pi + 1, pi + shft);
  22427. pi += 1;
  22428. if (pi === min) {
  22429. if (closePath) {
  22430. indices.push(pi, pi + shft, idx[p]);
  22431. indices.push(idx[p] + shft, idx[p], pi + shft);
  22432. t3 = idx[p];
  22433. t4 = idx[p] + shft;
  22434. }
  22435. p++;
  22436. if (p === lg.length - 1) {
  22437. shft = idx[0] - idx[p];
  22438. l1 = lg[p] - 1;
  22439. l2 = lg[0] - 1;
  22440. }
  22441. else {
  22442. shft = idx[p + 1] - idx[p];
  22443. l1 = lg[p] - 1;
  22444. l2 = lg[p + 1] - 1;
  22445. }
  22446. pi = idx[p];
  22447. min = (l1 < l2) ? l1 + pi : l2 + pi;
  22448. }
  22449. }
  22450. // normals
  22451. VertexData.ComputeNormals(positions, indices, normals);
  22452. // sides
  22453. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22454. // Result
  22455. var vertexData = new VertexData();
  22456. vertexData.indices = indices;
  22457. vertexData.positions = positions;
  22458. vertexData.normals = normals;
  22459. vertexData.uvs = uvs;
  22460. return vertexData;
  22461. };
  22462. VertexData.CreateBox = function (size, sideOrientation) {
  22463. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22464. var normalsSource = [
  22465. new BABYLON.Vector3(0, 0, 1),
  22466. new BABYLON.Vector3(0, 0, -1),
  22467. new BABYLON.Vector3(1, 0, 0),
  22468. new BABYLON.Vector3(-1, 0, 0),
  22469. new BABYLON.Vector3(0, 1, 0),
  22470. new BABYLON.Vector3(0, -1, 0)
  22471. ];
  22472. var indices = [];
  22473. var positions = [];
  22474. var normals = [];
  22475. var uvs = [];
  22476. size = size || 1;
  22477. for (var index = 0; index < normalsSource.length; index++) {
  22478. var normal = normalsSource[index];
  22479. // Get two vectors perpendicular to the face normal and to each other.
  22480. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  22481. var side2 = BABYLON.Vector3.Cross(normal, side1);
  22482. // Six indices (two triangles) per face.
  22483. var verticesLength = positions.length / 3;
  22484. indices.push(verticesLength);
  22485. indices.push(verticesLength + 1);
  22486. indices.push(verticesLength + 2);
  22487. indices.push(verticesLength);
  22488. indices.push(verticesLength + 2);
  22489. indices.push(verticesLength + 3);
  22490. // Four vertices per face.
  22491. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  22492. positions.push(vertex.x, vertex.y, vertex.z);
  22493. normals.push(normal.x, normal.y, normal.z);
  22494. uvs.push(1.0, 1.0);
  22495. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  22496. positions.push(vertex.x, vertex.y, vertex.z);
  22497. normals.push(normal.x, normal.y, normal.z);
  22498. uvs.push(0.0, 1.0);
  22499. vertex = normal.add(side1).add(side2).scale(size / 2);
  22500. positions.push(vertex.x, vertex.y, vertex.z);
  22501. normals.push(normal.x, normal.y, normal.z);
  22502. uvs.push(0.0, 0.0);
  22503. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  22504. positions.push(vertex.x, vertex.y, vertex.z);
  22505. normals.push(normal.x, normal.y, normal.z);
  22506. uvs.push(1.0, 0.0);
  22507. }
  22508. // sides
  22509. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22510. // Result
  22511. var vertexData = new VertexData();
  22512. vertexData.indices = indices;
  22513. vertexData.positions = positions;
  22514. vertexData.normals = normals;
  22515. vertexData.uvs = uvs;
  22516. return vertexData;
  22517. };
  22518. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  22519. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22520. segments = segments || 32;
  22521. diameter = diameter || 1;
  22522. var radius = diameter / 2;
  22523. var totalZRotationSteps = 2 + segments;
  22524. var totalYRotationSteps = 2 * totalZRotationSteps;
  22525. var indices = [];
  22526. var positions = [];
  22527. var normals = [];
  22528. var uvs = [];
  22529. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  22530. var normalizedZ = zRotationStep / totalZRotationSteps;
  22531. var angleZ = (normalizedZ * Math.PI);
  22532. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  22533. var normalizedY = yRotationStep / totalYRotationSteps;
  22534. var angleY = normalizedY * Math.PI * 2;
  22535. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  22536. var rotationY = BABYLON.Matrix.RotationY(angleY);
  22537. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  22538. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  22539. var vertex = complete.scale(radius);
  22540. var normal = BABYLON.Vector3.Normalize(vertex);
  22541. positions.push(vertex.x, vertex.y, vertex.z);
  22542. normals.push(normal.x, normal.y, normal.z);
  22543. uvs.push(normalizedZ, normalizedY);
  22544. }
  22545. if (zRotationStep > 0) {
  22546. var verticesCount = positions.length / 3;
  22547. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  22548. indices.push((firstIndex));
  22549. indices.push((firstIndex + 1));
  22550. indices.push(firstIndex + totalYRotationSteps + 1);
  22551. indices.push((firstIndex + totalYRotationSteps + 1));
  22552. indices.push((firstIndex + 1));
  22553. indices.push((firstIndex + totalYRotationSteps + 2));
  22554. }
  22555. }
  22556. }
  22557. // Sides
  22558. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22559. // Result
  22560. var vertexData = new VertexData();
  22561. vertexData.indices = indices;
  22562. vertexData.positions = positions;
  22563. vertexData.normals = normals;
  22564. vertexData.uvs = uvs;
  22565. return vertexData;
  22566. };
  22567. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  22568. if (subdivisions === void 0) { subdivisions = 1; }
  22569. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22570. var radiusTop = diameterTop / 2;
  22571. var radiusBottom = diameterBottom / 2;
  22572. var indices = [];
  22573. var positions = [];
  22574. var normals = [];
  22575. var uvs = [];
  22576. height = height || 1;
  22577. diameterTop = diameterTop || 0.5;
  22578. diameterBottom = diameterBottom || 1;
  22579. tessellation = tessellation || 16;
  22580. subdivisions = subdivisions || 1;
  22581. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  22582. var getCircleVector = function (i) {
  22583. var angle = (i * 2.0 * Math.PI / tessellation);
  22584. var dx = Math.cos(angle);
  22585. var dz = Math.sin(angle);
  22586. return new BABYLON.Vector3(dx, 0, dz);
  22587. };
  22588. var createCylinderCap = function (isTop) {
  22589. var radius = isTop ? radiusTop : radiusBottom;
  22590. if (radius === 0) {
  22591. return;
  22592. }
  22593. var vbase = positions.length / 3;
  22594. var offset = new BABYLON.Vector3(0, height / 2, 0);
  22595. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  22596. if (!isTop) {
  22597. offset.scaleInPlace(-1);
  22598. textureScale.x = -textureScale.x;
  22599. }
  22600. for (var i = 0; i < tessellation; i++) {
  22601. var circleVector = getCircleVector(i);
  22602. var position = circleVector.scale(radius).add(offset);
  22603. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  22604. positions.push(position.x, position.y, position.z);
  22605. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22606. }
  22607. for (i = 0; i < tessellation - 2; i++) {
  22608. if (!isTop) {
  22609. indices.push(vbase);
  22610. indices.push(vbase + (i + 2) % tessellation);
  22611. indices.push(vbase + (i + 1) % tessellation);
  22612. }
  22613. else {
  22614. indices.push(vbase);
  22615. indices.push(vbase + (i + 1) % tessellation);
  22616. indices.push(vbase + (i + 2) % tessellation);
  22617. }
  22618. }
  22619. };
  22620. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  22621. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  22622. var stride = tessellation + 1;
  22623. for (var i = 0; i <= tessellation; i++) {
  22624. var circleVector = getCircleVector(i);
  22625. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  22626. var position, radius = radiusBottom;
  22627. for (var s = 0; s <= subdivisions; s++) {
  22628. // Update variables
  22629. position = circleVector.scale(radius);
  22630. position.addInPlace(base.add(offset.scale(s)));
  22631. textureCoordinate.y += 1 / subdivisions;
  22632. radius += (radiusTop - radiusBottom) / subdivisions;
  22633. // Push in arrays
  22634. positions.push(position.x, position.y, position.z);
  22635. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22636. }
  22637. }
  22638. subdivisions += 1;
  22639. for (s = 0; s < subdivisions - 1; s++) {
  22640. for (i = 0; i <= tessellation; i++) {
  22641. indices.push(i * subdivisions + s);
  22642. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  22643. indices.push(i * subdivisions + (s + 1));
  22644. indices.push(i * subdivisions + (s + 1));
  22645. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  22646. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  22647. }
  22648. }
  22649. // Create flat triangle fan caps to seal the top and bottom.
  22650. createCylinderCap(true);
  22651. createCylinderCap(false);
  22652. // Normals
  22653. VertexData.ComputeNormals(positions, indices, normals);
  22654. // Sides
  22655. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22656. // Result
  22657. var vertexData = new VertexData();
  22658. vertexData.indices = indices;
  22659. vertexData.positions = positions;
  22660. vertexData.normals = normals;
  22661. vertexData.uvs = uvs;
  22662. return vertexData;
  22663. };
  22664. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  22665. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22666. var indices = [];
  22667. var positions = [];
  22668. var normals = [];
  22669. var uvs = [];
  22670. diameter = diameter || 1;
  22671. thickness = thickness || 0.5;
  22672. tessellation = tessellation || 16;
  22673. var stride = tessellation + 1;
  22674. for (var i = 0; i <= tessellation; i++) {
  22675. var u = i / tessellation;
  22676. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  22677. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  22678. for (var j = 0; j <= tessellation; j++) {
  22679. var v = 1 - j / tessellation;
  22680. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  22681. var dx = Math.cos(innerAngle);
  22682. var dy = Math.sin(innerAngle);
  22683. // Create a vertex.
  22684. var normal = new BABYLON.Vector3(dx, dy, 0);
  22685. var position = normal.scale(thickness / 2);
  22686. var textureCoordinate = new BABYLON.Vector2(u, v);
  22687. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  22688. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  22689. positions.push(position.x, position.y, position.z);
  22690. normals.push(normal.x, normal.y, normal.z);
  22691. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22692. // And create indices for two triangles.
  22693. var nextI = (i + 1) % stride;
  22694. var nextJ = (j + 1) % stride;
  22695. indices.push(i * stride + j);
  22696. indices.push(i * stride + nextJ);
  22697. indices.push(nextI * stride + j);
  22698. indices.push(i * stride + nextJ);
  22699. indices.push(nextI * stride + nextJ);
  22700. indices.push(nextI * stride + j);
  22701. }
  22702. }
  22703. // Sides
  22704. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22705. // Result
  22706. var vertexData = new VertexData();
  22707. vertexData.indices = indices;
  22708. vertexData.positions = positions;
  22709. vertexData.normals = normals;
  22710. vertexData.uvs = uvs;
  22711. return vertexData;
  22712. };
  22713. VertexData.CreateLines = function (points) {
  22714. var indices = [];
  22715. var positions = [];
  22716. for (var index = 0; index < points.length; index++) {
  22717. positions.push(points[index].x, points[index].y, points[index].z);
  22718. if (index > 0) {
  22719. indices.push(index - 1);
  22720. indices.push(index);
  22721. }
  22722. }
  22723. // Result
  22724. var vertexData = new VertexData();
  22725. vertexData.indices = indices;
  22726. vertexData.positions = positions;
  22727. return vertexData;
  22728. };
  22729. VertexData.CreateGround = function (width, height, subdivisions) {
  22730. var indices = [];
  22731. var positions = [];
  22732. var normals = [];
  22733. var uvs = [];
  22734. var row, col;
  22735. width = width || 1;
  22736. height = height || 1;
  22737. subdivisions = subdivisions || 1;
  22738. for (row = 0; row <= subdivisions; row++) {
  22739. for (col = 0; col <= subdivisions; col++) {
  22740. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22741. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22742. positions.push(position.x, position.y, position.z);
  22743. normals.push(normal.x, normal.y, normal.z);
  22744. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22745. }
  22746. }
  22747. for (row = 0; row < subdivisions; row++) {
  22748. for (col = 0; col < subdivisions; col++) {
  22749. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22750. indices.push(col + 1 + row * (subdivisions + 1));
  22751. indices.push(col + row * (subdivisions + 1));
  22752. indices.push(col + (row + 1) * (subdivisions + 1));
  22753. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22754. indices.push(col + row * (subdivisions + 1));
  22755. }
  22756. }
  22757. // Result
  22758. var vertexData = new VertexData();
  22759. vertexData.indices = indices;
  22760. vertexData.positions = positions;
  22761. vertexData.normals = normals;
  22762. vertexData.uvs = uvs;
  22763. return vertexData;
  22764. };
  22765. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  22766. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  22767. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  22768. var indices = [];
  22769. var positions = [];
  22770. var normals = [];
  22771. var uvs = [];
  22772. var row, col, tileRow, tileCol;
  22773. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  22774. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  22775. precision.w = (precision.w < 1) ? 1 : precision.w;
  22776. precision.h = (precision.h < 1) ? 1 : precision.h;
  22777. var tileSize = {
  22778. 'w': (xmax - xmin) / subdivisions.w,
  22779. 'h': (zmax - zmin) / subdivisions.h
  22780. };
  22781. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  22782. // Indices
  22783. var base = positions.length / 3;
  22784. var rowLength = precision.w + 1;
  22785. for (row = 0; row < precision.h; row++) {
  22786. for (col = 0; col < precision.w; col++) {
  22787. var square = [
  22788. base + col + row * rowLength,
  22789. base + (col + 1) + row * rowLength,
  22790. base + (col + 1) + (row + 1) * rowLength,
  22791. base + col + (row + 1) * rowLength
  22792. ];
  22793. indices.push(square[1]);
  22794. indices.push(square[2]);
  22795. indices.push(square[3]);
  22796. indices.push(square[0]);
  22797. indices.push(square[1]);
  22798. indices.push(square[3]);
  22799. }
  22800. }
  22801. // Position, normals and uvs
  22802. var position = BABYLON.Vector3.Zero();
  22803. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22804. for (row = 0; row <= precision.h; row++) {
  22805. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  22806. for (col = 0; col <= precision.w; col++) {
  22807. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  22808. position.y = 0;
  22809. positions.push(position.x, position.y, position.z);
  22810. normals.push(normal.x, normal.y, normal.z);
  22811. uvs.push(col / precision.w, row / precision.h);
  22812. }
  22813. }
  22814. }
  22815. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  22816. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  22817. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  22818. }
  22819. }
  22820. // Result
  22821. var vertexData = new VertexData();
  22822. vertexData.indices = indices;
  22823. vertexData.positions = positions;
  22824. vertexData.normals = normals;
  22825. vertexData.uvs = uvs;
  22826. return vertexData;
  22827. };
  22828. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  22829. var indices = [];
  22830. var positions = [];
  22831. var normals = [];
  22832. var uvs = [];
  22833. var row, col;
  22834. for (row = 0; row <= subdivisions; row++) {
  22835. for (col = 0; col <= subdivisions; col++) {
  22836. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22837. // Compute height
  22838. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  22839. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  22840. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  22841. var r = buffer[pos] / 255.0;
  22842. var g = buffer[pos + 1] / 255.0;
  22843. var b = buffer[pos + 2] / 255.0;
  22844. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22845. position.y = minHeight + (maxHeight - minHeight) * gradient;
  22846. // Add vertex
  22847. positions.push(position.x, position.y, position.z);
  22848. normals.push(0, 0, 0);
  22849. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22850. }
  22851. }
  22852. for (row = 0; row < subdivisions; row++) {
  22853. for (col = 0; col < subdivisions; col++) {
  22854. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22855. indices.push(col + 1 + row * (subdivisions + 1));
  22856. indices.push(col + row * (subdivisions + 1));
  22857. indices.push(col + (row + 1) * (subdivisions + 1));
  22858. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22859. indices.push(col + row * (subdivisions + 1));
  22860. }
  22861. }
  22862. // Normals
  22863. VertexData.ComputeNormals(positions, indices, normals);
  22864. // Result
  22865. var vertexData = new VertexData();
  22866. vertexData.indices = indices;
  22867. vertexData.positions = positions;
  22868. vertexData.normals = normals;
  22869. vertexData.uvs = uvs;
  22870. return vertexData;
  22871. };
  22872. VertexData.CreatePlane = function (size, sideOrientation) {
  22873. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22874. var indices = [];
  22875. var positions = [];
  22876. var normals = [];
  22877. var uvs = [];
  22878. size = size || 1;
  22879. // Vertices
  22880. var halfSize = size / 2.0;
  22881. positions.push(-halfSize, -halfSize, 0);
  22882. normals.push(0, 0, -1.0);
  22883. uvs.push(0.0, 0.0);
  22884. positions.push(halfSize, -halfSize, 0);
  22885. normals.push(0, 0, -1.0);
  22886. uvs.push(1.0, 0.0);
  22887. positions.push(halfSize, halfSize, 0);
  22888. normals.push(0, 0, -1.0);
  22889. uvs.push(1.0, 1.0);
  22890. positions.push(-halfSize, halfSize, 0);
  22891. normals.push(0, 0, -1.0);
  22892. uvs.push(0.0, 1.0);
  22893. // Indices
  22894. indices.push(0);
  22895. indices.push(1);
  22896. indices.push(2);
  22897. indices.push(0);
  22898. indices.push(2);
  22899. indices.push(3);
  22900. // Sides
  22901. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22902. // Result
  22903. var vertexData = new VertexData();
  22904. vertexData.indices = indices;
  22905. vertexData.positions = positions;
  22906. vertexData.normals = normals;
  22907. vertexData.uvs = uvs;
  22908. return vertexData;
  22909. };
  22910. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  22911. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  22912. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22913. var indices = [];
  22914. var positions = [];
  22915. var normals = [];
  22916. var uvs = [];
  22917. radius = radius || 2;
  22918. tube = tube || 0.5;
  22919. radialSegments = radialSegments || 32;
  22920. tubularSegments = tubularSegments || 32;
  22921. p = p || 2;
  22922. q = q || 3;
  22923. // Helper
  22924. var getPos = function (angle) {
  22925. var cu = Math.cos(angle);
  22926. var su = Math.sin(angle);
  22927. var quOverP = q / p * angle;
  22928. var cs = Math.cos(quOverP);
  22929. var tx = radius * (2 + cs) * 0.5 * cu;
  22930. var ty = radius * (2 + cs) * su * 0.5;
  22931. var tz = radius * Math.sin(quOverP) * 0.5;
  22932. return new BABYLON.Vector3(tx, ty, tz);
  22933. };
  22934. for (var i = 0; i <= radialSegments; i++) {
  22935. var modI = i % radialSegments;
  22936. var u = modI / radialSegments * 2 * p * Math.PI;
  22937. var p1 = getPos(u);
  22938. var p2 = getPos(u + 0.01);
  22939. var tang = p2.subtract(p1);
  22940. var n = p2.add(p1);
  22941. var bitan = BABYLON.Vector3.Cross(tang, n);
  22942. n = BABYLON.Vector3.Cross(bitan, tang);
  22943. bitan.normalize();
  22944. n.normalize();
  22945. for (var j = 0; j < tubularSegments; j++) {
  22946. var modJ = j % tubularSegments;
  22947. var v = modJ / tubularSegments * 2 * Math.PI;
  22948. var cx = -tube * Math.cos(v);
  22949. var cy = tube * Math.sin(v);
  22950. positions.push(p1.x + cx * n.x + cy * bitan.x);
  22951. positions.push(p1.y + cx * n.y + cy * bitan.y);
  22952. positions.push(p1.z + cx * n.z + cy * bitan.z);
  22953. uvs.push(i / radialSegments);
  22954. uvs.push(j / tubularSegments);
  22955. }
  22956. }
  22957. for (i = 0; i < radialSegments; i++) {
  22958. for (j = 0; j < tubularSegments; j++) {
  22959. var jNext = (j + 1) % tubularSegments;
  22960. var a = i * tubularSegments + j;
  22961. var b = (i + 1) * tubularSegments + j;
  22962. var c = (i + 1) * tubularSegments + jNext;
  22963. var d = i * tubularSegments + jNext;
  22964. indices.push(d);
  22965. indices.push(b);
  22966. indices.push(a);
  22967. indices.push(d);
  22968. indices.push(c);
  22969. indices.push(b);
  22970. }
  22971. }
  22972. // Normals
  22973. VertexData.ComputeNormals(positions, indices, normals);
  22974. // Sides
  22975. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22976. // Result
  22977. var vertexData = new VertexData();
  22978. vertexData.indices = indices;
  22979. vertexData.positions = positions;
  22980. vertexData.normals = normals;
  22981. vertexData.uvs = uvs;
  22982. return vertexData;
  22983. };
  22984. // Tools
  22985. /**
  22986. * @param {any} - positions (number[] or Float32Array)
  22987. * @param {any} - indices (number[] or Uint16Array)
  22988. * @param {any} - normals (number[] or Float32Array)
  22989. */
  22990. VertexData.ComputeNormals = function (positions, indices, normals) {
  22991. var positionVectors = [];
  22992. var facesOfVertices = [];
  22993. var index;
  22994. for (index = 0; index < positions.length; index += 3) {
  22995. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  22996. positionVectors.push(vector3);
  22997. facesOfVertices.push([]);
  22998. }
  22999. // Compute normals
  23000. var facesNormals = [];
  23001. for (index = 0; index < indices.length / 3; index++) {
  23002. var i1 = indices[index * 3];
  23003. var i2 = indices[index * 3 + 1];
  23004. var i3 = indices[index * 3 + 2];
  23005. var p1 = positionVectors[i1];
  23006. var p2 = positionVectors[i2];
  23007. var p3 = positionVectors[i3];
  23008. var p1p2 = p1.subtract(p2);
  23009. var p3p2 = p3.subtract(p2);
  23010. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  23011. facesOfVertices[i1].push(index);
  23012. facesOfVertices[i2].push(index);
  23013. facesOfVertices[i3].push(index);
  23014. }
  23015. for (index = 0; index < positionVectors.length; index++) {
  23016. var faces = facesOfVertices[index];
  23017. var normal = BABYLON.Vector3.Zero();
  23018. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  23019. normal.addInPlace(facesNormals[faces[faceIndex]]);
  23020. }
  23021. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  23022. normals[index * 3] = normal.x;
  23023. normals[index * 3 + 1] = normal.y;
  23024. normals[index * 3 + 2] = normal.z;
  23025. }
  23026. };
  23027. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  23028. var li = indices.length;
  23029. var ln = normals.length;
  23030. var i;
  23031. var n;
  23032. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  23033. switch (sideOrientation) {
  23034. case BABYLON.Mesh.FRONTSIDE:
  23035. break;
  23036. case BABYLON.Mesh.BACKSIDE:
  23037. var tmp;
  23038. for (i = 0; i < li; i += 3) {
  23039. tmp = indices[i];
  23040. indices[i] = indices[i + 2];
  23041. indices[i + 2] = tmp;
  23042. }
  23043. for (n = 0; n < ln; n++) {
  23044. normals[n] = -normals[n];
  23045. }
  23046. break;
  23047. case BABYLON.Mesh.DOUBLESIDE:
  23048. // positions
  23049. var lp = positions.length;
  23050. var l = lp / 3;
  23051. for (var p = 0; p < lp; p++) {
  23052. positions[lp + p] = positions[p];
  23053. }
  23054. for (i = 0; i < li; i += 3) {
  23055. indices[i + li] = indices[i + 2] + l;
  23056. indices[i + 1 + li] = indices[i + 1] + l;
  23057. indices[i + 2 + li] = indices[i] + l;
  23058. }
  23059. for (n = 0; n < ln; n++) {
  23060. normals[ln + n] = -normals[n];
  23061. }
  23062. // uvs
  23063. var lu = uvs.length;
  23064. for (var u = 0; u < lu; u++) {
  23065. uvs[u + lu] = uvs[u];
  23066. }
  23067. break;
  23068. }
  23069. };
  23070. return VertexData;
  23071. })();
  23072. BABYLON.VertexData = VertexData;
  23073. })(BABYLON || (BABYLON = {}));
  23074. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  23075. var BABYLON;
  23076. (function (BABYLON) {
  23077. var buildCamera = function (that, name) {
  23078. that._leftCamera.isIntermediate = true;
  23079. that.subCameras.push(that._leftCamera);
  23080. that.subCameras.push(that._rightCamera);
  23081. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  23082. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  23083. that._anaglyphPostProcess.onApply = function (effect) {
  23084. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  23085. };
  23086. that._update();
  23087. };
  23088. var AnaglyphArcRotateCamera = (function (_super) {
  23089. __extends(AnaglyphArcRotateCamera, _super);
  23090. // ANY
  23091. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  23092. _super.call(this, name, alpha, beta, radius, target, scene);
  23093. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  23094. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  23095. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  23096. buildCamera(this, name);
  23097. }
  23098. AnaglyphArcRotateCamera.prototype._update = function () {
  23099. this._updateCamera(this._leftCamera);
  23100. this._updateCamera(this._rightCamera);
  23101. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  23102. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  23103. _super.prototype._update.call(this);
  23104. };
  23105. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  23106. camera.beta = this.beta;
  23107. camera.radius = this.radius;
  23108. camera.minZ = this.minZ;
  23109. camera.maxZ = this.maxZ;
  23110. camera.fov = this.fov;
  23111. camera.target = this.target;
  23112. };
  23113. return AnaglyphArcRotateCamera;
  23114. })(BABYLON.ArcRotateCamera);
  23115. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  23116. var AnaglyphFreeCamera = (function (_super) {
  23117. __extends(AnaglyphFreeCamera, _super);
  23118. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  23119. _super.call(this, name, position, scene);
  23120. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  23121. this._transformMatrix = new BABYLON.Matrix();
  23122. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  23123. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  23124. buildCamera(this, name);
  23125. }
  23126. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  23127. var target = this.getTarget();
  23128. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  23129. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  23130. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  23131. };
  23132. AnaglyphFreeCamera.prototype._update = function () {
  23133. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  23134. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  23135. this._updateCamera(this._leftCamera);
  23136. this._updateCamera(this._rightCamera);
  23137. _super.prototype._update.call(this);
  23138. };
  23139. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  23140. camera.minZ = this.minZ;
  23141. camera.maxZ = this.maxZ;
  23142. camera.fov = this.fov;
  23143. camera.viewport = this.viewport;
  23144. camera.setTarget(this.getTarget());
  23145. };
  23146. return AnaglyphFreeCamera;
  23147. })(BABYLON.FreeCamera);
  23148. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  23149. })(BABYLON || (BABYLON = {}));
  23150. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  23151. var BABYLON;
  23152. (function (BABYLON) {
  23153. var AnaglyphPostProcess = (function (_super) {
  23154. __extends(AnaglyphPostProcess, _super);
  23155. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23156. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  23157. }
  23158. return AnaglyphPostProcess;
  23159. })(BABYLON.PostProcess);
  23160. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  23161. })(BABYLON || (BABYLON = {}));
  23162. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  23163. (function (BABYLON) {
  23164. var Tags = (function () {
  23165. function Tags() {
  23166. }
  23167. Tags.EnableFor = function (obj) {
  23168. obj._tags = obj._tags || {};
  23169. obj.hasTags = function () {
  23170. return Tags.HasTags(obj);
  23171. };
  23172. obj.addTags = function (tagsString) {
  23173. return Tags.AddTagsTo(obj, tagsString);
  23174. };
  23175. obj.removeTags = function (tagsString) {
  23176. return Tags.RemoveTagsFrom(obj, tagsString);
  23177. };
  23178. obj.matchesTagsQuery = function (tagsQuery) {
  23179. return Tags.MatchesQuery(obj, tagsQuery);
  23180. };
  23181. };
  23182. Tags.DisableFor = function (obj) {
  23183. delete obj._tags;
  23184. delete obj.hasTags;
  23185. delete obj.addTags;
  23186. delete obj.removeTags;
  23187. delete obj.matchesTagsQuery;
  23188. };
  23189. Tags.HasTags = function (obj) {
  23190. if (!obj._tags) {
  23191. return false;
  23192. }
  23193. return !BABYLON.Tools.IsEmpty(obj._tags);
  23194. };
  23195. Tags.GetTags = function (obj) {
  23196. if (!obj._tags) {
  23197. return null;
  23198. }
  23199. return obj._tags;
  23200. };
  23201. // the tags 'true' and 'false' are reserved and cannot be used as tags
  23202. // a tag cannot start with '||', '&&', and '!'
  23203. // it cannot contain whitespaces
  23204. Tags.AddTagsTo = function (obj, tagsString) {
  23205. if (!tagsString) {
  23206. return;
  23207. }
  23208. var tags = tagsString.split(" ");
  23209. for (var t in tags) {
  23210. Tags._AddTagTo(obj, tags[t]);
  23211. }
  23212. };
  23213. Tags._AddTagTo = function (obj, tag) {
  23214. tag = tag.trim();
  23215. if (tag === "" || tag === "true" || tag === "false") {
  23216. return;
  23217. }
  23218. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  23219. return;
  23220. }
  23221. Tags.EnableFor(obj);
  23222. obj._tags[tag] = true;
  23223. };
  23224. Tags.RemoveTagsFrom = function (obj, tagsString) {
  23225. if (!Tags.HasTags(obj)) {
  23226. return;
  23227. }
  23228. var tags = tagsString.split(" ");
  23229. for (var t in tags) {
  23230. Tags._RemoveTagFrom(obj, tags[t]);
  23231. }
  23232. };
  23233. Tags._RemoveTagFrom = function (obj, tag) {
  23234. delete obj._tags[tag];
  23235. };
  23236. Tags.MatchesQuery = function (obj, tagsQuery) {
  23237. if (tagsQuery === undefined) {
  23238. return true;
  23239. }
  23240. if (tagsQuery === "") {
  23241. return Tags.HasTags(obj);
  23242. }
  23243. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  23244. };
  23245. return Tags;
  23246. })();
  23247. BABYLON.Tags = Tags;
  23248. })(BABYLON || (BABYLON = {}));
  23249. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  23250. (function (BABYLON) {
  23251. var Internals;
  23252. (function (Internals) {
  23253. var AndOrNotEvaluator = (function () {
  23254. function AndOrNotEvaluator() {
  23255. }
  23256. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  23257. if (!query.match(/\([^\(\)]*\)/g)) {
  23258. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  23259. }
  23260. else {
  23261. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  23262. // remove parenthesis
  23263. r = r.slice(1, r.length - 1);
  23264. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  23265. });
  23266. }
  23267. if (query === "true") {
  23268. return true;
  23269. }
  23270. if (query === "false") {
  23271. return false;
  23272. }
  23273. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  23274. };
  23275. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  23276. evaluateCallback = evaluateCallback || (function (r) {
  23277. return r === "true" ? true : false;
  23278. });
  23279. var result;
  23280. var or = parenthesisContent.split("||");
  23281. for (var i in or) {
  23282. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  23283. var and = ori.split("&&");
  23284. if (and.length > 1) {
  23285. for (var j = 0; j < and.length; ++j) {
  23286. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  23287. if (andj !== "true" && andj !== "false") {
  23288. if (andj[0] === "!") {
  23289. result = !evaluateCallback(andj.substring(1));
  23290. }
  23291. else {
  23292. result = evaluateCallback(andj);
  23293. }
  23294. }
  23295. else {
  23296. result = andj === "true" ? true : false;
  23297. }
  23298. if (!result) {
  23299. ori = "false";
  23300. break;
  23301. }
  23302. }
  23303. }
  23304. if (result || ori === "true") {
  23305. result = true;
  23306. break;
  23307. }
  23308. // result equals false (or undefined)
  23309. if (ori !== "true" && ori !== "false") {
  23310. if (ori[0] === "!") {
  23311. result = !evaluateCallback(ori.substring(1));
  23312. }
  23313. else {
  23314. result = evaluateCallback(ori);
  23315. }
  23316. }
  23317. else {
  23318. result = ori === "true" ? true : false;
  23319. }
  23320. }
  23321. // the whole parenthesis scope is replaced by 'true' or 'false'
  23322. return result ? "true" : "false";
  23323. };
  23324. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  23325. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  23326. // remove whitespaces
  23327. r = r.replace(/[\s]/g, function () { return ""; });
  23328. return r.length % 2 ? "!" : "";
  23329. });
  23330. booleanString = booleanString.trim();
  23331. if (booleanString === "!true") {
  23332. booleanString = "false";
  23333. }
  23334. else if (booleanString === "!false") {
  23335. booleanString = "true";
  23336. }
  23337. return booleanString;
  23338. };
  23339. return AndOrNotEvaluator;
  23340. })();
  23341. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  23342. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23343. })(BABYLON || (BABYLON = {}));
  23344. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  23345. (function (BABYLON) {
  23346. var PostProcessRenderPass = (function () {
  23347. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  23348. this._enabled = true;
  23349. this._refCount = 0;
  23350. this._name = name;
  23351. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  23352. this.setRenderList(renderList);
  23353. this._renderTexture.onBeforeRender = beforeRender;
  23354. this._renderTexture.onAfterRender = afterRender;
  23355. this._scene = scene;
  23356. this._renderList = renderList;
  23357. }
  23358. // private
  23359. PostProcessRenderPass.prototype._incRefCount = function () {
  23360. if (this._refCount === 0) {
  23361. this._scene.customRenderTargets.push(this._renderTexture);
  23362. }
  23363. return ++this._refCount;
  23364. };
  23365. PostProcessRenderPass.prototype._decRefCount = function () {
  23366. this._refCount--;
  23367. if (this._refCount <= 0) {
  23368. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  23369. }
  23370. return this._refCount;
  23371. };
  23372. PostProcessRenderPass.prototype._update = function () {
  23373. this.setRenderList(this._renderList);
  23374. };
  23375. // public
  23376. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  23377. this._renderTexture.renderList = renderList;
  23378. };
  23379. PostProcessRenderPass.prototype.getRenderTexture = function () {
  23380. return this._renderTexture;
  23381. };
  23382. return PostProcessRenderPass;
  23383. })();
  23384. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  23385. })(BABYLON || (BABYLON = {}));
  23386. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  23387. (function (BABYLON) {
  23388. var PostProcessRenderEffect = (function () {
  23389. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  23390. this._engine = engine;
  23391. this._name = name;
  23392. this._singleInstance = singleInstance || true;
  23393. this._getPostProcess = getPostProcess;
  23394. this._cameras = [];
  23395. this._indicesForCamera = [];
  23396. this._postProcesses = {};
  23397. this._renderPasses = {};
  23398. this._renderEffectAsPasses = {};
  23399. }
  23400. PostProcessRenderEffect.prototype._update = function () {
  23401. for (var renderPassName in this._renderPasses) {
  23402. this._renderPasses[renderPassName]._update();
  23403. }
  23404. };
  23405. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  23406. this._renderPasses[renderPass._name] = renderPass;
  23407. this._linkParameters();
  23408. };
  23409. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  23410. delete this._renderPasses[renderPass._name];
  23411. this._linkParameters();
  23412. };
  23413. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  23414. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  23415. this._linkParameters();
  23416. };
  23417. PostProcessRenderEffect.prototype.getPass = function (passName) {
  23418. for (var renderPassName in this._renderPasses) {
  23419. if (renderPassName === passName) {
  23420. return this._renderPasses[passName];
  23421. }
  23422. }
  23423. };
  23424. PostProcessRenderEffect.prototype.emptyPasses = function () {
  23425. this._renderPasses = {};
  23426. this._linkParameters();
  23427. };
  23428. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  23429. var cameraKey;
  23430. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23431. for (var i = 0; i < _cam.length; i++) {
  23432. var camera = _cam[i];
  23433. var cameraName = camera.name;
  23434. if (this._singleInstance) {
  23435. cameraKey = 0;
  23436. }
  23437. else {
  23438. cameraKey = cameraName;
  23439. }
  23440. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  23441. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  23442. if (!this._indicesForCamera[cameraName]) {
  23443. this._indicesForCamera[cameraName] = [];
  23444. }
  23445. this._indicesForCamera[cameraName].push(index);
  23446. if (this._cameras.indexOf(camera) === -1) {
  23447. this._cameras[cameraName] = camera;
  23448. }
  23449. for (var passName in this._renderPasses) {
  23450. this._renderPasses[passName]._incRefCount();
  23451. }
  23452. }
  23453. this._linkParameters();
  23454. };
  23455. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  23456. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23457. for (var i = 0; i < _cam.length; i++) {
  23458. var camera = _cam[i];
  23459. var cameraName = camera.name;
  23460. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  23461. var index = this._cameras.indexOf(cameraName);
  23462. this._indicesForCamera.splice(index, 1);
  23463. this._cameras.splice(index, 1);
  23464. for (var passName in this._renderPasses) {
  23465. this._renderPasses[passName]._decRefCount();
  23466. }
  23467. }
  23468. };
  23469. PostProcessRenderEffect.prototype._enable = function (cameras) {
  23470. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23471. for (var i = 0; i < _cam.length; i++) {
  23472. var camera = _cam[i];
  23473. var cameraName = camera.name;
  23474. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  23475. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  23476. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  23477. }
  23478. }
  23479. for (var passName in this._renderPasses) {
  23480. this._renderPasses[passName]._incRefCount();
  23481. }
  23482. }
  23483. };
  23484. PostProcessRenderEffect.prototype._disable = function (cameras) {
  23485. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23486. for (var i = 0; i < _cam.length; i++) {
  23487. var camera = _cam[i];
  23488. var cameraName = camera.Name;
  23489. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  23490. for (var passName in this._renderPasses) {
  23491. this._renderPasses[passName]._decRefCount();
  23492. }
  23493. }
  23494. };
  23495. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  23496. if (this._singleInstance) {
  23497. return this._postProcesses[0];
  23498. }
  23499. else {
  23500. return this._postProcesses[camera.name];
  23501. }
  23502. };
  23503. PostProcessRenderEffect.prototype._linkParameters = function () {
  23504. var _this = this;
  23505. for (var index in this._postProcesses) {
  23506. if (this.applyParameters) {
  23507. this.applyParameters(this._postProcesses[index]);
  23508. }
  23509. this._postProcesses[index].onBeforeRender = function (effect) {
  23510. _this._linkTextures(effect);
  23511. };
  23512. }
  23513. };
  23514. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  23515. for (var renderPassName in this._renderPasses) {
  23516. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  23517. }
  23518. for (var renderEffectName in this._renderEffectAsPasses) {
  23519. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  23520. }
  23521. };
  23522. return PostProcessRenderEffect;
  23523. })();
  23524. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  23525. })(BABYLON || (BABYLON = {}));
  23526. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  23527. (function (BABYLON) {
  23528. var PostProcessRenderPipeline = (function () {
  23529. function PostProcessRenderPipeline(engine, name) {
  23530. this._engine = engine;
  23531. this._name = name;
  23532. this._renderEffects = {};
  23533. this._renderEffectsForIsolatedPass = {};
  23534. this._cameras = [];
  23535. }
  23536. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  23537. this._renderEffects[renderEffect._name] = renderEffect;
  23538. };
  23539. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  23540. var renderEffects = this._renderEffects[renderEffectName];
  23541. if (!renderEffects) {
  23542. return;
  23543. }
  23544. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  23545. };
  23546. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  23547. var renderEffects = this._renderEffects[renderEffectName];
  23548. if (!renderEffects) {
  23549. return;
  23550. }
  23551. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  23552. };
  23553. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  23554. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23555. var indicesToDelete = [];
  23556. for (var i = 0; i < _cam.length; i++) {
  23557. var camera = _cam[i];
  23558. var cameraName = camera.name;
  23559. if (this._cameras.indexOf(camera) === -1) {
  23560. this._cameras[cameraName] = camera;
  23561. }
  23562. else if (unique) {
  23563. indicesToDelete.push(i);
  23564. }
  23565. }
  23566. for (var i = 0; i < indicesToDelete.length; i++) {
  23567. cameras.splice(indicesToDelete[i], 1);
  23568. }
  23569. for (var renderEffectName in this._renderEffects) {
  23570. this._renderEffects[renderEffectName]._attachCameras(_cam);
  23571. }
  23572. };
  23573. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  23574. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23575. for (var renderEffectName in this._renderEffects) {
  23576. this._renderEffects[renderEffectName]._detachCameras(_cam);
  23577. }
  23578. for (var i = 0; i < _cam.length; i++) {
  23579. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  23580. }
  23581. };
  23582. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  23583. var _this = this;
  23584. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23585. var pass = null;
  23586. for (var renderEffectName in this._renderEffects) {
  23587. pass = this._renderEffects[renderEffectName].getPass(passName);
  23588. if (pass != null) {
  23589. break;
  23590. }
  23591. }
  23592. if (pass === null) {
  23593. return;
  23594. }
  23595. for (var renderEffectName in this._renderEffects) {
  23596. this._renderEffects[renderEffectName]._disable(_cam);
  23597. }
  23598. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  23599. for (var i = 0; i < _cam.length; i++) {
  23600. var camera = _cam[i];
  23601. var cameraName = camera.name;
  23602. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  23603. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  23604. });
  23605. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  23606. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  23607. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  23608. }
  23609. };
  23610. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  23611. var _this = this;
  23612. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23613. for (var i = 0; i < _cam.length; i++) {
  23614. var camera = _cam[i];
  23615. var cameraName = camera.name;
  23616. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  23617. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  23618. });
  23619. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  23620. }
  23621. for (var renderEffectName in this._renderEffects) {
  23622. this._renderEffects[renderEffectName]._enable(_cam);
  23623. }
  23624. };
  23625. PostProcessRenderPipeline.prototype._update = function () {
  23626. for (var renderEffectName in this._renderEffects) {
  23627. this._renderEffects[renderEffectName]._update();
  23628. }
  23629. for (var i = 0; i < this._cameras.length; i++) {
  23630. var cameraName = this._cameras[i].name;
  23631. if (this._renderEffectsForIsolatedPass[cameraName]) {
  23632. this._renderEffectsForIsolatedPass[cameraName]._update();
  23633. }
  23634. }
  23635. };
  23636. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  23637. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  23638. return PostProcessRenderPipeline;
  23639. })();
  23640. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  23641. })(BABYLON || (BABYLON = {}));
  23642. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  23643. (function (BABYLON) {
  23644. var PostProcessRenderPipelineManager = (function () {
  23645. function PostProcessRenderPipelineManager() {
  23646. this._renderPipelines = {};
  23647. }
  23648. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  23649. this._renderPipelines[renderPipeline._name] = renderPipeline;
  23650. };
  23651. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  23652. var renderPipeline = this._renderPipelines[renderPipelineName];
  23653. if (!renderPipeline) {
  23654. return;
  23655. }
  23656. renderPipeline._attachCameras(cameras, unique);
  23657. };
  23658. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  23659. var renderPipeline = this._renderPipelines[renderPipelineName];
  23660. if (!renderPipeline) {
  23661. return;
  23662. }
  23663. renderPipeline._detachCameras(cameras);
  23664. };
  23665. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  23666. var renderPipeline = this._renderPipelines[renderPipelineName];
  23667. if (!renderPipeline) {
  23668. return;
  23669. }
  23670. renderPipeline._enableEffect(renderEffectName, cameras);
  23671. };
  23672. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  23673. var renderPipeline = this._renderPipelines[renderPipelineName];
  23674. if (!renderPipeline) {
  23675. return;
  23676. }
  23677. renderPipeline._disableEffect(renderEffectName, cameras);
  23678. };
  23679. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  23680. var renderPipeline = this._renderPipelines[renderPipelineName];
  23681. if (!renderPipeline) {
  23682. return;
  23683. }
  23684. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  23685. };
  23686. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  23687. var renderPipeline = this._renderPipelines[renderPipelineName];
  23688. if (!renderPipeline) {
  23689. return;
  23690. }
  23691. renderPipeline._disableDisplayOnlyPass(cameras);
  23692. };
  23693. PostProcessRenderPipelineManager.prototype.update = function () {
  23694. for (var renderPipelineName in this._renderPipelines) {
  23695. this._renderPipelines[renderPipelineName]._update();
  23696. }
  23697. };
  23698. return PostProcessRenderPipelineManager;
  23699. })();
  23700. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  23701. })(BABYLON || (BABYLON = {}));
  23702. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  23703. var BABYLON;
  23704. (function (BABYLON) {
  23705. var DisplayPassPostProcess = (function (_super) {
  23706. __extends(DisplayPassPostProcess, _super);
  23707. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23708. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  23709. }
  23710. return DisplayPassPostProcess;
  23711. })(BABYLON.PostProcess);
  23712. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  23713. })(BABYLON || (BABYLON = {}));
  23714. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  23715. (function (BABYLON) {
  23716. var BoundingBoxRenderer = (function () {
  23717. function BoundingBoxRenderer(scene) {
  23718. this.frontColor = new BABYLON.Color3(1, 1, 1);
  23719. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  23720. this.showBackLines = true;
  23721. this.renderList = new BABYLON.SmartArray(32);
  23722. this._scene = scene;
  23723. }
  23724. BoundingBoxRenderer.prototype._prepareRessources = function () {
  23725. if (this._colorShader) {
  23726. return;
  23727. }
  23728. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  23729. attributes: ["position"],
  23730. uniforms: ["worldViewProjection", "color"]
  23731. });
  23732. var engine = this._scene.getEngine();
  23733. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  23734. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  23735. 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]);
  23736. };
  23737. BoundingBoxRenderer.prototype.reset = function () {
  23738. this.renderList.reset();
  23739. };
  23740. BoundingBoxRenderer.prototype.render = function () {
  23741. if (this.renderList.length === 0) {
  23742. return;
  23743. }
  23744. this._prepareRessources();
  23745. if (!this._colorShader.isReady()) {
  23746. return;
  23747. }
  23748. var engine = this._scene.getEngine();
  23749. engine.setDepthWrite(false);
  23750. this._colorShader._preBind();
  23751. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  23752. var boundingBox = this.renderList.data[boundingBoxIndex];
  23753. var min = boundingBox.minimum;
  23754. var max = boundingBox.maximum;
  23755. var diff = max.subtract(min);
  23756. var median = min.add(diff.scale(0.5));
  23757. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  23758. // VBOs
  23759. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  23760. if (this.showBackLines) {
  23761. // Back
  23762. engine.setDepthFunctionToGreaterOrEqual();
  23763. this._scene.resetCachedMaterial();
  23764. this._colorShader.setColor4("color", this.backColor.toColor4());
  23765. this._colorShader.bind(worldMatrix);
  23766. // Draw order
  23767. engine.draw(false, 0, 24);
  23768. }
  23769. // Front
  23770. engine.setDepthFunctionToLess();
  23771. this._scene.resetCachedMaterial();
  23772. this._colorShader.setColor4("color", this.frontColor.toColor4());
  23773. this._colorShader.bind(worldMatrix);
  23774. // Draw order
  23775. engine.draw(false, 0, 24);
  23776. }
  23777. this._colorShader.unbind();
  23778. engine.setDepthFunctionToLessOrEqual();
  23779. engine.setDepthWrite(true);
  23780. };
  23781. BoundingBoxRenderer.prototype.dispose = function () {
  23782. if (!this._colorShader) {
  23783. return;
  23784. }
  23785. this._colorShader.dispose();
  23786. this._vb.dispose();
  23787. this._scene.getEngine()._releaseBuffer(this._ib);
  23788. };
  23789. return BoundingBoxRenderer;
  23790. })();
  23791. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  23792. })(BABYLON || (BABYLON = {}));
  23793. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  23794. (function (BABYLON) {
  23795. var Internals;
  23796. (function (Internals) {
  23797. /*
  23798. * Based on jsTGALoader - Javascript loader for TGA file
  23799. * By Vincent Thibault
  23800. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  23801. */
  23802. var TGATools = (function () {
  23803. function TGATools() {
  23804. }
  23805. TGATools.GetTGAHeader = function (data) {
  23806. var offset = 0;
  23807. var header = {
  23808. id_length: data[offset++],
  23809. colormap_type: data[offset++],
  23810. image_type: data[offset++],
  23811. colormap_index: data[offset++] | data[offset++] << 8,
  23812. colormap_length: data[offset++] | data[offset++] << 8,
  23813. colormap_size: data[offset++],
  23814. origin: [
  23815. data[offset++] | data[offset++] << 8,
  23816. data[offset++] | data[offset++] << 8
  23817. ],
  23818. width: data[offset++] | data[offset++] << 8,
  23819. height: data[offset++] | data[offset++] << 8,
  23820. pixel_size: data[offset++],
  23821. flags: data[offset++]
  23822. };
  23823. return header;
  23824. };
  23825. TGATools.UploadContent = function (gl, data) {
  23826. // Not enough data to contain header ?
  23827. if (data.length < 19) {
  23828. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  23829. return;
  23830. }
  23831. // Read Header
  23832. var offset = 18;
  23833. var header = TGATools.GetTGAHeader(data);
  23834. // Assume it's a valid Targa file.
  23835. if (header.id_length + offset > data.length) {
  23836. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  23837. return;
  23838. }
  23839. // Skip not needed data
  23840. offset += header.id_length;
  23841. var use_rle = false;
  23842. var use_pal = false;
  23843. var use_rgb = false;
  23844. var use_grey = false;
  23845. switch (header.image_type) {
  23846. case TGATools._TYPE_RLE_INDEXED:
  23847. use_rle = true;
  23848. case TGATools._TYPE_INDEXED:
  23849. use_pal = true;
  23850. break;
  23851. case TGATools._TYPE_RLE_RGB:
  23852. use_rle = true;
  23853. case TGATools._TYPE_RGB:
  23854. use_rgb = true;
  23855. break;
  23856. case TGATools._TYPE_RLE_GREY:
  23857. use_rle = true;
  23858. case TGATools._TYPE_GREY:
  23859. use_grey = true;
  23860. break;
  23861. }
  23862. var pixel_data;
  23863. var numAlphaBits = header.flags & 0xf;
  23864. var pixel_size = header.pixel_size >> 3;
  23865. var pixel_total = header.width * header.height * pixel_size;
  23866. // Read palettes
  23867. var palettes;
  23868. if (use_pal) {
  23869. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  23870. }
  23871. // Read LRE
  23872. if (use_rle) {
  23873. pixel_data = new Uint8Array(pixel_total);
  23874. var c, count, i;
  23875. var localOffset = 0;
  23876. var pixels = new Uint8Array(pixel_size);
  23877. while (offset < pixel_total && localOffset < pixel_total) {
  23878. c = data[offset++];
  23879. count = (c & 0x7f) + 1;
  23880. // RLE pixels
  23881. if (c & 0x80) {
  23882. for (i = 0; i < pixel_size; ++i) {
  23883. pixels[i] = data[offset++];
  23884. }
  23885. for (i = 0; i < count; ++i) {
  23886. pixel_data.set(pixels, localOffset + i * pixel_size);
  23887. }
  23888. localOffset += pixel_size * count;
  23889. }
  23890. else {
  23891. count *= pixel_size;
  23892. for (i = 0; i < count; ++i) {
  23893. pixel_data[localOffset + i] = data[offset++];
  23894. }
  23895. localOffset += count;
  23896. }
  23897. }
  23898. }
  23899. else {
  23900. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  23901. }
  23902. // Load to texture
  23903. var x_start, y_start, x_step, y_step, y_end, x_end;
  23904. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  23905. default:
  23906. case TGATools._ORIGIN_UL:
  23907. x_start = 0;
  23908. x_step = 1;
  23909. x_end = header.width;
  23910. y_start = 0;
  23911. y_step = 1;
  23912. y_end = header.height;
  23913. break;
  23914. case TGATools._ORIGIN_BL:
  23915. x_start = 0;
  23916. x_step = 1;
  23917. x_end = header.width;
  23918. y_start = header.height - 1;
  23919. y_step = -1;
  23920. y_end = -1;
  23921. break;
  23922. case TGATools._ORIGIN_UR:
  23923. x_start = header.width - 1;
  23924. x_step = -1;
  23925. x_end = -1;
  23926. y_start = 0;
  23927. y_step = 1;
  23928. y_end = header.height;
  23929. break;
  23930. case TGATools._ORIGIN_BR:
  23931. x_start = header.width - 1;
  23932. x_step = -1;
  23933. x_end = -1;
  23934. y_start = header.height - 1;
  23935. y_step = -1;
  23936. y_end = -1;
  23937. break;
  23938. }
  23939. // Load the specify method
  23940. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  23941. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  23942. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  23943. };
  23944. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23945. var image = pixel_data, colormap = palettes;
  23946. var width = header.width, height = header.height;
  23947. var color, i = 0, x, y;
  23948. var imageData = new Uint8Array(width * height * 4);
  23949. for (y = y_start; y !== y_end; y += y_step) {
  23950. for (x = x_start; x !== x_end; x += x_step, i++) {
  23951. color = image[i];
  23952. imageData[(x + width * y) * 4 + 3] = 255;
  23953. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  23954. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  23955. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  23956. }
  23957. }
  23958. return imageData;
  23959. };
  23960. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23961. var image = pixel_data;
  23962. var width = header.width, height = header.height;
  23963. var color, i = 0, x, y;
  23964. var imageData = new Uint8Array(width * height * 4);
  23965. for (y = y_start; y !== y_end; y += y_step) {
  23966. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  23967. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  23968. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  23969. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  23970. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  23971. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  23972. }
  23973. }
  23974. return imageData;
  23975. };
  23976. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23977. var image = pixel_data;
  23978. var width = header.width, height = header.height;
  23979. var i = 0, x, y;
  23980. var imageData = new Uint8Array(width * height * 4);
  23981. for (y = y_start; y !== y_end; y += y_step) {
  23982. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  23983. imageData[(x + width * y) * 4 + 3] = 255;
  23984. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23985. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  23986. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  23987. }
  23988. }
  23989. return imageData;
  23990. };
  23991. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23992. var image = pixel_data;
  23993. var width = header.width, height = header.height;
  23994. var i = 0, x, y;
  23995. var imageData = new Uint8Array(width * height * 4);
  23996. for (y = y_start; y !== y_end; y += y_step) {
  23997. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  23998. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23999. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  24000. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  24001. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  24002. }
  24003. }
  24004. return imageData;
  24005. };
  24006. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24007. var image = pixel_data;
  24008. var width = header.width, height = header.height;
  24009. var color, i = 0, x, y;
  24010. var imageData = new Uint8Array(width * height * 4);
  24011. for (y = y_start; y !== y_end; y += y_step) {
  24012. for (x = x_start; x !== x_end; x += x_step, i++) {
  24013. color = image[i];
  24014. imageData[(x + width * y) * 4 + 0] = color;
  24015. imageData[(x + width * y) * 4 + 1] = color;
  24016. imageData[(x + width * y) * 4 + 2] = color;
  24017. imageData[(x + width * y) * 4 + 3] = 255;
  24018. }
  24019. }
  24020. return imageData;
  24021. };
  24022. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  24023. var image = pixel_data;
  24024. var width = header.width, height = header.height;
  24025. var i = 0, x, y;
  24026. var imageData = new Uint8Array(width * height * 4);
  24027. for (y = y_start; y !== y_end; y += y_step) {
  24028. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  24029. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  24030. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  24031. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  24032. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  24033. }
  24034. }
  24035. return imageData;
  24036. };
  24037. TGATools._TYPE_NO_DATA = 0;
  24038. TGATools._TYPE_INDEXED = 1;
  24039. TGATools._TYPE_RGB = 2;
  24040. TGATools._TYPE_GREY = 3;
  24041. TGATools._TYPE_RLE_INDEXED = 9;
  24042. TGATools._TYPE_RLE_RGB = 10;
  24043. TGATools._TYPE_RLE_GREY = 11;
  24044. TGATools._ORIGIN_MASK = 0x30;
  24045. TGATools._ORIGIN_SHIFT = 0x04;
  24046. TGATools._ORIGIN_BL = 0x00;
  24047. TGATools._ORIGIN_BR = 0x01;
  24048. TGATools._ORIGIN_UL = 0x02;
  24049. TGATools._ORIGIN_UR = 0x03;
  24050. return TGATools;
  24051. })();
  24052. Internals.TGATools = TGATools;
  24053. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24054. })(BABYLON || (BABYLON = {}));
  24055. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  24056. (function (BABYLON) {
  24057. var Internals;
  24058. (function (Internals) {
  24059. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  24060. // All values and structures referenced from:
  24061. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  24062. var DDS_MAGIC = 0x20534444;
  24063. 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;
  24064. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  24065. 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;
  24066. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  24067. function FourCCToInt32(value) {
  24068. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  24069. }
  24070. function Int32ToFourCC(value) {
  24071. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  24072. }
  24073. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  24074. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  24075. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  24076. var headerLengthInt = 31; // The header length in 32 bit ints
  24077. // Offsets into the header array
  24078. var off_magic = 0;
  24079. var off_size = 1;
  24080. var off_flags = 2;
  24081. var off_height = 3;
  24082. var off_width = 4;
  24083. var off_mipmapCount = 7;
  24084. var off_pfFlags = 20;
  24085. var off_pfFourCC = 21;
  24086. var off_RGBbpp = 22;
  24087. var off_RMask = 23;
  24088. var off_GMask = 24;
  24089. var off_BMask = 25;
  24090. var off_AMask = 26;
  24091. var off_caps1 = 27;
  24092. var off_caps2 = 28;
  24093. ;
  24094. var DDSTools = (function () {
  24095. function DDSTools() {
  24096. }
  24097. DDSTools.GetDDSInfo = function (arrayBuffer) {
  24098. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  24099. var mipmapCount = 1;
  24100. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  24101. mipmapCount = Math.max(1, header[off_mipmapCount]);
  24102. }
  24103. return {
  24104. width: header[off_width],
  24105. height: header[off_height],
  24106. mipmapCount: mipmapCount,
  24107. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  24108. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  24109. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  24110. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  24111. };
  24112. };
  24113. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  24114. var byteArray = new Uint8Array(dataLength);
  24115. var srcData = new Uint8Array(arrayBuffer);
  24116. var index = 0;
  24117. for (var y = height - 1; y >= 0; y--) {
  24118. for (var x = 0; x < width; x++) {
  24119. var srcPos = dataOffset + (x + y * width) * 4;
  24120. byteArray[index + 2] = srcData[srcPos];
  24121. byteArray[index + 1] = srcData[srcPos + 1];
  24122. byteArray[index] = srcData[srcPos + 2];
  24123. byteArray[index + 3] = srcData[srcPos + 3];
  24124. index += 4;
  24125. }
  24126. }
  24127. return byteArray;
  24128. };
  24129. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  24130. var byteArray = new Uint8Array(dataLength);
  24131. var srcData = new Uint8Array(arrayBuffer);
  24132. var index = 0;
  24133. for (var y = height - 1; y >= 0; y--) {
  24134. for (var x = 0; x < width; x++) {
  24135. var srcPos = dataOffset + (x + y * width) * 3;
  24136. byteArray[index + 2] = srcData[srcPos];
  24137. byteArray[index + 1] = srcData[srcPos + 1];
  24138. byteArray[index] = srcData[srcPos + 2];
  24139. index += 3;
  24140. }
  24141. }
  24142. return byteArray;
  24143. };
  24144. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  24145. var byteArray = new Uint8Array(dataLength);
  24146. var srcData = new Uint8Array(arrayBuffer);
  24147. var index = 0;
  24148. for (var y = height - 1; y >= 0; y--) {
  24149. for (var x = 0; x < width; x++) {
  24150. var srcPos = dataOffset + (x + y * width);
  24151. byteArray[index] = srcData[srcPos];
  24152. index++;
  24153. }
  24154. }
  24155. return byteArray;
  24156. };
  24157. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  24158. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  24159. if (header[off_magic] != DDS_MAGIC) {
  24160. BABYLON.Tools.Error("Invalid magic number in DDS header");
  24161. return;
  24162. }
  24163. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  24164. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  24165. return;
  24166. }
  24167. if (info.isFourCC) {
  24168. fourCC = header[off_pfFourCC];
  24169. switch (fourCC) {
  24170. case FOURCC_DXT1:
  24171. blockBytes = 8;
  24172. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  24173. break;
  24174. case FOURCC_DXT3:
  24175. blockBytes = 16;
  24176. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  24177. break;
  24178. case FOURCC_DXT5:
  24179. blockBytes = 16;
  24180. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  24181. break;
  24182. default:
  24183. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  24184. return;
  24185. }
  24186. }
  24187. mipmapCount = 1;
  24188. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  24189. mipmapCount = Math.max(1, header[off_mipmapCount]);
  24190. }
  24191. var bpp = header[off_RGBbpp];
  24192. for (var face = 0; face < faces; face++) {
  24193. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  24194. width = header[off_width];
  24195. height = header[off_height];
  24196. dataOffset = header[off_size] + 4;
  24197. for (i = 0; i < mipmapCount; ++i) {
  24198. if (info.isRGB) {
  24199. if (bpp == 24) {
  24200. dataLength = width * height * 3;
  24201. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  24202. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  24203. }
  24204. else {
  24205. dataLength = width * height * 4;
  24206. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  24207. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  24208. }
  24209. }
  24210. else if (info.isLuminance) {
  24211. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  24212. var unpaddedRowSize = width;
  24213. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  24214. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  24215. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  24216. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  24217. }
  24218. else {
  24219. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  24220. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  24221. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  24222. }
  24223. dataOffset += dataLength;
  24224. width *= 0.5;
  24225. height *= 0.5;
  24226. width = Math.max(1.0, width);
  24227. height = Math.max(1.0, height);
  24228. }
  24229. }
  24230. };
  24231. return DDSTools;
  24232. })();
  24233. Internals.DDSTools = DDSTools;
  24234. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24235. })(BABYLON || (BABYLON = {}));
  24236. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  24237. (function (BABYLON) {
  24238. var SmartArray = (function () {
  24239. function SmartArray(capacity) {
  24240. this.length = 0;
  24241. this._duplicateId = 0;
  24242. this.data = new Array(capacity);
  24243. this._id = SmartArray._GlobalId++;
  24244. }
  24245. SmartArray.prototype.push = function (value) {
  24246. this.data[this.length++] = value;
  24247. if (this.length > this.data.length) {
  24248. this.data.length *= 2;
  24249. }
  24250. if (!value.__smartArrayFlags) {
  24251. value.__smartArrayFlags = {};
  24252. }
  24253. value.__smartArrayFlags[this._id] = this._duplicateId;
  24254. };
  24255. SmartArray.prototype.pushNoDuplicate = function (value) {
  24256. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  24257. return;
  24258. }
  24259. this.push(value);
  24260. };
  24261. SmartArray.prototype.sort = function (compareFn) {
  24262. this.data.sort(compareFn);
  24263. };
  24264. SmartArray.prototype.reset = function () {
  24265. this.length = 0;
  24266. this._duplicateId++;
  24267. };
  24268. SmartArray.prototype.concat = function (array) {
  24269. if (array.length === 0) {
  24270. return;
  24271. }
  24272. if (this.length + array.length > this.data.length) {
  24273. this.data.length = (this.length + array.length) * 2;
  24274. }
  24275. for (var index = 0; index < array.length; index++) {
  24276. this.data[this.length++] = (array.data || array)[index];
  24277. }
  24278. };
  24279. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  24280. if (array.length === 0) {
  24281. return;
  24282. }
  24283. if (this.length + array.length > this.data.length) {
  24284. this.data.length = (this.length + array.length) * 2;
  24285. }
  24286. for (var index = 0; index < array.length; index++) {
  24287. var item = (array.data || array)[index];
  24288. this.pushNoDuplicate(item);
  24289. }
  24290. };
  24291. SmartArray.prototype.indexOf = function (value) {
  24292. var position = this.data.indexOf(value);
  24293. if (position >= this.length) {
  24294. return -1;
  24295. }
  24296. return position;
  24297. };
  24298. // Statics
  24299. SmartArray._GlobalId = 0;
  24300. return SmartArray;
  24301. })();
  24302. BABYLON.SmartArray = SmartArray;
  24303. })(BABYLON || (BABYLON = {}));
  24304. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  24305. (function (BABYLON) {
  24306. var CannonJSPlugin = (function () {
  24307. function CannonJSPlugin() {
  24308. this._registeredMeshes = [];
  24309. this._physicsMaterials = [];
  24310. this.updateBodyPosition = function (mesh) {
  24311. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24312. var registeredMesh = this._registeredMeshes[index];
  24313. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  24314. var body = registeredMesh.body;
  24315. var center = mesh.getBoundingInfo().boundingBox.center;
  24316. body.position.set(center.x, center.z, center.y);
  24317. body.quaternion.x = mesh.rotationQuaternion.x;
  24318. body.quaternion.z = mesh.rotationQuaternion.y;
  24319. body.quaternion.y = mesh.rotationQuaternion.z;
  24320. body.quaternion.w = -mesh.rotationQuaternion.w;
  24321. return;
  24322. }
  24323. }
  24324. };
  24325. }
  24326. CannonJSPlugin.prototype.initialize = function (iterations) {
  24327. if (iterations === void 0) { iterations = 10; }
  24328. this._world = new CANNON.World();
  24329. this._world.broadphase = new CANNON.NaiveBroadphase();
  24330. this._world.solver.iterations = iterations;
  24331. };
  24332. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  24333. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  24334. };
  24335. CannonJSPlugin.prototype.runOneStep = function (delta) {
  24336. this._world.step(delta);
  24337. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24338. var registeredMesh = this._registeredMeshes[index];
  24339. if (registeredMesh.isChild) {
  24340. continue;
  24341. }
  24342. // Body position
  24343. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  24344. var deltaPos = registeredMesh.delta;
  24345. if (deltaPos) {
  24346. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  24347. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  24348. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  24349. }
  24350. else {
  24351. registeredMesh.mesh.position.x = bodyX;
  24352. registeredMesh.mesh.position.y = bodyZ;
  24353. registeredMesh.mesh.position.z = bodyY;
  24354. }
  24355. if (!registeredMesh.mesh.rotationQuaternion) {
  24356. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24357. }
  24358. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  24359. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  24360. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  24361. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  24362. }
  24363. };
  24364. CannonJSPlugin.prototype.setGravity = function (gravity) {
  24365. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  24366. };
  24367. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  24368. this.unregisterMesh(mesh);
  24369. mesh.computeWorldMatrix(true);
  24370. switch (impostor) {
  24371. case BABYLON.PhysicsEngine.SphereImpostor:
  24372. var bbox = mesh.getBoundingInfo().boundingBox;
  24373. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  24374. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  24375. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  24376. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  24377. case BABYLON.PhysicsEngine.BoxImpostor:
  24378. bbox = mesh.getBoundingInfo().boundingBox;
  24379. var min = bbox.minimumWorld;
  24380. var max = bbox.maximumWorld;
  24381. var box = max.subtract(min).scale(0.5);
  24382. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  24383. case BABYLON.PhysicsEngine.PlaneImpostor:
  24384. return this._createPlane(mesh, options);
  24385. case BABYLON.PhysicsEngine.MeshImpostor:
  24386. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  24387. var rawFaces = mesh.getIndices();
  24388. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  24389. }
  24390. return null;
  24391. };
  24392. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  24393. var shape = new CANNON.Sphere(radius);
  24394. if (!options) {
  24395. return shape;
  24396. }
  24397. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24398. };
  24399. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  24400. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  24401. if (!options) {
  24402. return shape;
  24403. }
  24404. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24405. };
  24406. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  24407. var shape = new CANNON.Plane();
  24408. if (!options) {
  24409. return shape;
  24410. }
  24411. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24412. };
  24413. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  24414. var verts = [], faces = [];
  24415. mesh.computeWorldMatrix(true);
  24416. for (var i = 0; i < rawVerts.length; i += 3) {
  24417. var transformed = BABYLON.Vector3.Zero();
  24418. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  24419. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  24420. }
  24421. for (var j = 0; j < rawFaces.length; j += 3) {
  24422. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  24423. }
  24424. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  24425. if (!options) {
  24426. return shape;
  24427. }
  24428. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24429. };
  24430. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  24431. var index;
  24432. var mat;
  24433. for (index = 0; index < this._physicsMaterials.length; index++) {
  24434. mat = this._physicsMaterials[index];
  24435. if (mat.friction === friction && mat.restitution === restitution) {
  24436. return mat;
  24437. }
  24438. }
  24439. var currentMat = new CANNON.Material();
  24440. currentMat.friction = friction;
  24441. currentMat.restitution = restitution;
  24442. this._physicsMaterials.push(currentMat);
  24443. for (index = 0; index < this._physicsMaterials.length; index++) {
  24444. mat = this._physicsMaterials[index];
  24445. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  24446. contactMaterial.contactEquationStiffness = 1e10;
  24447. contactMaterial.contactEquationRegularizationTime = 10;
  24448. this._world.addContactMaterial(contactMaterial);
  24449. }
  24450. return currentMat;
  24451. };
  24452. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  24453. var initialRotation = null;
  24454. if (mesh.rotationQuaternion) {
  24455. initialRotation = mesh.rotationQuaternion.clone();
  24456. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24457. }
  24458. // The delta between the mesh position and the mesh bounding box center
  24459. var bbox = mesh.getBoundingInfo().boundingBox;
  24460. var deltaPosition = mesh.position.subtract(bbox.center);
  24461. var material = this._addMaterial(friction, restitution);
  24462. var body = new CANNON.RigidBody(mass, shape, material);
  24463. if (initialRotation) {
  24464. body.quaternion.x = initialRotation.x;
  24465. body.quaternion.z = initialRotation.y;
  24466. body.quaternion.y = initialRotation.z;
  24467. body.quaternion.w = -initialRotation.w;
  24468. }
  24469. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  24470. this._world.add(body);
  24471. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  24472. return body;
  24473. };
  24474. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  24475. var compoundShape = new CANNON.Compound();
  24476. for (var index = 0; index < parts.length; index++) {
  24477. var mesh = parts[index].mesh;
  24478. var shape = this.registerMesh(mesh, parts[index].impostor);
  24479. if (index == 0) {
  24480. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  24481. }
  24482. else {
  24483. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  24484. }
  24485. }
  24486. var initialMesh = parts[0].mesh;
  24487. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  24488. body.parts = parts;
  24489. return body;
  24490. };
  24491. CannonJSPlugin.prototype._unbindBody = function (body) {
  24492. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24493. var registeredMesh = this._registeredMeshes[index];
  24494. if (registeredMesh.body === body) {
  24495. registeredMesh.body = null;
  24496. registeredMesh.delta = 0;
  24497. }
  24498. }
  24499. };
  24500. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  24501. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24502. var registeredMesh = this._registeredMeshes[index];
  24503. if (registeredMesh.mesh === mesh) {
  24504. // Remove body
  24505. if (registeredMesh.body) {
  24506. this._world.remove(registeredMesh.body);
  24507. this._unbindBody(registeredMesh.body);
  24508. }
  24509. this._registeredMeshes.splice(index, 1);
  24510. return;
  24511. }
  24512. }
  24513. };
  24514. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  24515. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  24516. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  24517. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24518. var registeredMesh = this._registeredMeshes[index];
  24519. if (registeredMesh.mesh === mesh) {
  24520. registeredMesh.body.applyImpulse(impulse, worldPoint);
  24521. return;
  24522. }
  24523. }
  24524. };
  24525. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  24526. var body1 = null, body2 = null;
  24527. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24528. var registeredMesh = this._registeredMeshes[index];
  24529. if (registeredMesh.mesh === mesh1) {
  24530. body1 = registeredMesh.body;
  24531. }
  24532. else if (registeredMesh.mesh === mesh2) {
  24533. body2 = registeredMesh.body;
  24534. }
  24535. }
  24536. if (!body1 || !body2) {
  24537. return false;
  24538. }
  24539. 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));
  24540. this._world.addConstraint(constraint);
  24541. return true;
  24542. };
  24543. CannonJSPlugin.prototype.dispose = function () {
  24544. while (this._registeredMeshes.length) {
  24545. this.unregisterMesh(this._registeredMeshes[0].mesh);
  24546. }
  24547. };
  24548. CannonJSPlugin.prototype.isSupported = function () {
  24549. return window.CANNON !== undefined;
  24550. };
  24551. return CannonJSPlugin;
  24552. })();
  24553. BABYLON.CannonJSPlugin = CannonJSPlugin;
  24554. })(BABYLON || (BABYLON = {}));
  24555. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  24556. var BABYLON;
  24557. (function (BABYLON) {
  24558. var Condition = (function () {
  24559. function Condition(actionManager) {
  24560. this._actionManager = actionManager;
  24561. }
  24562. Condition.prototype.isValid = function () {
  24563. return true;
  24564. };
  24565. Condition.prototype._getProperty = function (propertyPath) {
  24566. return this._actionManager._getProperty(propertyPath);
  24567. };
  24568. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  24569. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24570. };
  24571. return Condition;
  24572. })();
  24573. BABYLON.Condition = Condition;
  24574. var ValueCondition = (function (_super) {
  24575. __extends(ValueCondition, _super);
  24576. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  24577. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  24578. _super.call(this, actionManager);
  24579. this.propertyPath = propertyPath;
  24580. this.value = value;
  24581. this.operator = operator;
  24582. this._target = this._getEffectiveTarget(target, this.propertyPath);
  24583. this._property = this._getProperty(this.propertyPath);
  24584. }
  24585. Object.defineProperty(ValueCondition, "IsEqual", {
  24586. get: function () {
  24587. return ValueCondition._IsEqual;
  24588. },
  24589. enumerable: true,
  24590. configurable: true
  24591. });
  24592. Object.defineProperty(ValueCondition, "IsDifferent", {
  24593. get: function () {
  24594. return ValueCondition._IsDifferent;
  24595. },
  24596. enumerable: true,
  24597. configurable: true
  24598. });
  24599. Object.defineProperty(ValueCondition, "IsGreater", {
  24600. get: function () {
  24601. return ValueCondition._IsGreater;
  24602. },
  24603. enumerable: true,
  24604. configurable: true
  24605. });
  24606. Object.defineProperty(ValueCondition, "IsLesser", {
  24607. get: function () {
  24608. return ValueCondition._IsLesser;
  24609. },
  24610. enumerable: true,
  24611. configurable: true
  24612. });
  24613. // Methods
  24614. ValueCondition.prototype.isValid = function () {
  24615. switch (this.operator) {
  24616. case ValueCondition.IsGreater:
  24617. return this._target[this._property] > this.value;
  24618. case ValueCondition.IsLesser:
  24619. return this._target[this._property] < this.value;
  24620. case ValueCondition.IsEqual:
  24621. case ValueCondition.IsDifferent:
  24622. var check;
  24623. if (this.value.equals) {
  24624. check = this.value.equals(this._target[this._property]);
  24625. }
  24626. else {
  24627. check = this.value === this._target[this._property];
  24628. }
  24629. return this.operator === ValueCondition.IsEqual ? check : !check;
  24630. }
  24631. return false;
  24632. };
  24633. // Statics
  24634. ValueCondition._IsEqual = 0;
  24635. ValueCondition._IsDifferent = 1;
  24636. ValueCondition._IsGreater = 2;
  24637. ValueCondition._IsLesser = 3;
  24638. return ValueCondition;
  24639. })(Condition);
  24640. BABYLON.ValueCondition = ValueCondition;
  24641. var PredicateCondition = (function (_super) {
  24642. __extends(PredicateCondition, _super);
  24643. function PredicateCondition(actionManager, predicate) {
  24644. _super.call(this, actionManager);
  24645. this.predicate = predicate;
  24646. }
  24647. PredicateCondition.prototype.isValid = function () {
  24648. return this.predicate();
  24649. };
  24650. return PredicateCondition;
  24651. })(Condition);
  24652. BABYLON.PredicateCondition = PredicateCondition;
  24653. var StateCondition = (function (_super) {
  24654. __extends(StateCondition, _super);
  24655. function StateCondition(actionManager, target, value) {
  24656. _super.call(this, actionManager);
  24657. this.value = value;
  24658. this._target = target;
  24659. }
  24660. // Methods
  24661. StateCondition.prototype.isValid = function () {
  24662. return this._target.state === this.value;
  24663. };
  24664. return StateCondition;
  24665. })(Condition);
  24666. BABYLON.StateCondition = StateCondition;
  24667. })(BABYLON || (BABYLON = {}));
  24668. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  24669. (function (BABYLON) {
  24670. var Action = (function () {
  24671. function Action(triggerOptions, condition) {
  24672. this.triggerOptions = triggerOptions;
  24673. if (triggerOptions.parameter) {
  24674. this.trigger = triggerOptions.trigger;
  24675. this._triggerParameter = triggerOptions.parameter;
  24676. }
  24677. else {
  24678. this.trigger = triggerOptions;
  24679. }
  24680. this._nextActiveAction = this;
  24681. this._condition = condition;
  24682. }
  24683. // Methods
  24684. Action.prototype._prepare = function () {
  24685. };
  24686. Action.prototype.getTriggerParameter = function () {
  24687. return this._triggerParameter;
  24688. };
  24689. Action.prototype._executeCurrent = function (evt) {
  24690. if (this._nextActiveAction._condition) {
  24691. var condition = this._nextActiveAction._condition;
  24692. var currentRenderId = this._actionManager.getScene().getRenderId();
  24693. // We cache the current evaluation for the current frame
  24694. if (condition._evaluationId === currentRenderId) {
  24695. if (!condition._currentResult) {
  24696. return;
  24697. }
  24698. }
  24699. else {
  24700. condition._evaluationId = currentRenderId;
  24701. if (!condition.isValid()) {
  24702. condition._currentResult = false;
  24703. return;
  24704. }
  24705. condition._currentResult = true;
  24706. }
  24707. }
  24708. this._nextActiveAction.execute(evt);
  24709. if (this._nextActiveAction._child) {
  24710. if (!this._nextActiveAction._child._actionManager) {
  24711. this._nextActiveAction._child._actionManager = this._actionManager;
  24712. }
  24713. this._nextActiveAction = this._nextActiveAction._child;
  24714. }
  24715. else {
  24716. this._nextActiveAction = this;
  24717. }
  24718. };
  24719. Action.prototype.execute = function (evt) {
  24720. };
  24721. Action.prototype.then = function (action) {
  24722. this._child = action;
  24723. action._actionManager = this._actionManager;
  24724. action._prepare();
  24725. return action;
  24726. };
  24727. Action.prototype._getProperty = function (propertyPath) {
  24728. return this._actionManager._getProperty(propertyPath);
  24729. };
  24730. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  24731. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24732. };
  24733. return Action;
  24734. })();
  24735. BABYLON.Action = Action;
  24736. })(BABYLON || (BABYLON = {}));
  24737. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  24738. (function (BABYLON) {
  24739. /**
  24740. * ActionEvent is the event beint sent when an action is triggered.
  24741. */
  24742. var ActionEvent = (function () {
  24743. /**
  24744. * @constructor
  24745. * @param source The mesh that triggered the action.
  24746. * @param pointerX the X mouse cursor position at the time of the event
  24747. * @param pointerY the Y mouse cursor position at the time of the event
  24748. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  24749. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  24750. */
  24751. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  24752. this.source = source;
  24753. this.pointerX = pointerX;
  24754. this.pointerY = pointerY;
  24755. this.meshUnderPointer = meshUnderPointer;
  24756. this.sourceEvent = sourceEvent;
  24757. }
  24758. /**
  24759. * Helper function to auto-create an ActionEvent from a source mesh.
  24760. * @param source the source mesh that triggered the event
  24761. * @param evt {Event} The original (browser) event
  24762. */
  24763. ActionEvent.CreateNew = function (source, evt) {
  24764. var scene = source.getScene();
  24765. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24766. };
  24767. /**
  24768. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  24769. * @param scene the scene where the event occurred
  24770. * @param evt {Event} The original (browser) event
  24771. */
  24772. ActionEvent.CreateNewFromScene = function (scene, evt) {
  24773. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24774. };
  24775. return ActionEvent;
  24776. })();
  24777. BABYLON.ActionEvent = ActionEvent;
  24778. /**
  24779. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  24780. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  24781. */
  24782. var ActionManager = (function () {
  24783. function ActionManager(scene) {
  24784. // Members
  24785. this.actions = new Array();
  24786. this._scene = scene;
  24787. scene._actionManagers.push(this);
  24788. }
  24789. Object.defineProperty(ActionManager, "NothingTrigger", {
  24790. get: function () {
  24791. return ActionManager._NothingTrigger;
  24792. },
  24793. enumerable: true,
  24794. configurable: true
  24795. });
  24796. Object.defineProperty(ActionManager, "OnPickTrigger", {
  24797. get: function () {
  24798. return ActionManager._OnPickTrigger;
  24799. },
  24800. enumerable: true,
  24801. configurable: true
  24802. });
  24803. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  24804. get: function () {
  24805. return ActionManager._OnLeftPickTrigger;
  24806. },
  24807. enumerable: true,
  24808. configurable: true
  24809. });
  24810. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  24811. get: function () {
  24812. return ActionManager._OnRightPickTrigger;
  24813. },
  24814. enumerable: true,
  24815. configurable: true
  24816. });
  24817. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  24818. get: function () {
  24819. return ActionManager._OnCenterPickTrigger;
  24820. },
  24821. enumerable: true,
  24822. configurable: true
  24823. });
  24824. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  24825. get: function () {
  24826. return ActionManager._OnPointerOverTrigger;
  24827. },
  24828. enumerable: true,
  24829. configurable: true
  24830. });
  24831. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  24832. get: function () {
  24833. return ActionManager._OnPointerOutTrigger;
  24834. },
  24835. enumerable: true,
  24836. configurable: true
  24837. });
  24838. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  24839. get: function () {
  24840. return ActionManager._OnEveryFrameTrigger;
  24841. },
  24842. enumerable: true,
  24843. configurable: true
  24844. });
  24845. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  24846. get: function () {
  24847. return ActionManager._OnIntersectionEnterTrigger;
  24848. },
  24849. enumerable: true,
  24850. configurable: true
  24851. });
  24852. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  24853. get: function () {
  24854. return ActionManager._OnIntersectionExitTrigger;
  24855. },
  24856. enumerable: true,
  24857. configurable: true
  24858. });
  24859. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  24860. get: function () {
  24861. return ActionManager._OnKeyDownTrigger;
  24862. },
  24863. enumerable: true,
  24864. configurable: true
  24865. });
  24866. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  24867. get: function () {
  24868. return ActionManager._OnKeyUpTrigger;
  24869. },
  24870. enumerable: true,
  24871. configurable: true
  24872. });
  24873. // Methods
  24874. ActionManager.prototype.dispose = function () {
  24875. var index = this._scene._actionManagers.indexOf(this);
  24876. if (index > -1) {
  24877. this._scene._actionManagers.splice(index, 1);
  24878. }
  24879. };
  24880. ActionManager.prototype.getScene = function () {
  24881. return this._scene;
  24882. };
  24883. /**
  24884. * Does this action manager handles actions of any of the given triggers
  24885. * @param {number[]} triggers - the triggers to be tested
  24886. * @return {boolean} whether one (or more) of the triggers is handeled
  24887. */
  24888. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  24889. for (var index = 0; index < this.actions.length; index++) {
  24890. var action = this.actions[index];
  24891. if (triggers.indexOf(action.trigger) > -1) {
  24892. return true;
  24893. }
  24894. }
  24895. return false;
  24896. };
  24897. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  24898. /**
  24899. * Does this action manager has pointer triggers
  24900. * @return {boolean} whether or not it has pointer triggers
  24901. */
  24902. get: function () {
  24903. for (var index = 0; index < this.actions.length; index++) {
  24904. var action = this.actions[index];
  24905. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  24906. return true;
  24907. }
  24908. }
  24909. return false;
  24910. },
  24911. enumerable: true,
  24912. configurable: true
  24913. });
  24914. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  24915. /**
  24916. * Does this action manager has pick triggers
  24917. * @return {boolean} whether or not it has pick triggers
  24918. */
  24919. get: function () {
  24920. for (var index = 0; index < this.actions.length; index++) {
  24921. var action = this.actions[index];
  24922. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  24923. return true;
  24924. }
  24925. }
  24926. return false;
  24927. },
  24928. enumerable: true,
  24929. configurable: true
  24930. });
  24931. /**
  24932. * Registers an action to this action manager
  24933. * @param {BABYLON.Action} action - the action to be registered
  24934. * @return {BABYLON.Action} the action amended (prepared) after registration
  24935. */
  24936. ActionManager.prototype.registerAction = function (action) {
  24937. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  24938. if (this.getScene().actionManager !== this) {
  24939. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  24940. return null;
  24941. }
  24942. }
  24943. this.actions.push(action);
  24944. action._actionManager = this;
  24945. action._prepare();
  24946. return action;
  24947. };
  24948. /**
  24949. * Process a specific trigger
  24950. * @param {number} trigger - the trigger to process
  24951. * @param evt {BABYLON.ActionEvent} the event details to be processed
  24952. */
  24953. ActionManager.prototype.processTrigger = function (trigger, evt) {
  24954. for (var index = 0; index < this.actions.length; index++) {
  24955. var action = this.actions[index];
  24956. if (action.trigger === trigger) {
  24957. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  24958. var parameter = action.getTriggerParameter();
  24959. if (parameter) {
  24960. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  24961. var actualkey = String.fromCharCode(unicode).toLowerCase();
  24962. if (actualkey !== parameter.toLowerCase()) {
  24963. continue;
  24964. }
  24965. }
  24966. }
  24967. action._executeCurrent(evt);
  24968. }
  24969. }
  24970. };
  24971. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  24972. var properties = propertyPath.split(".");
  24973. for (var index = 0; index < properties.length - 1; index++) {
  24974. target = target[properties[index]];
  24975. }
  24976. return target;
  24977. };
  24978. ActionManager.prototype._getProperty = function (propertyPath) {
  24979. var properties = propertyPath.split(".");
  24980. return properties[properties.length - 1];
  24981. };
  24982. // Statics
  24983. ActionManager._NothingTrigger = 0;
  24984. ActionManager._OnPickTrigger = 1;
  24985. ActionManager._OnLeftPickTrigger = 2;
  24986. ActionManager._OnRightPickTrigger = 3;
  24987. ActionManager._OnCenterPickTrigger = 4;
  24988. ActionManager._OnPointerOverTrigger = 5;
  24989. ActionManager._OnPointerOutTrigger = 6;
  24990. ActionManager._OnEveryFrameTrigger = 7;
  24991. ActionManager._OnIntersectionEnterTrigger = 8;
  24992. ActionManager._OnIntersectionExitTrigger = 9;
  24993. ActionManager._OnKeyDownTrigger = 10;
  24994. ActionManager._OnKeyUpTrigger = 11;
  24995. return ActionManager;
  24996. })();
  24997. BABYLON.ActionManager = ActionManager;
  24998. })(BABYLON || (BABYLON = {}));
  24999. //# sourceMappingURL=babylon.actionManager.js.map
  25000. var BABYLON;
  25001. (function (BABYLON) {
  25002. var InterpolateValueAction = (function (_super) {
  25003. __extends(InterpolateValueAction, _super);
  25004. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  25005. if (duration === void 0) { duration = 1000; }
  25006. _super.call(this, triggerOptions, condition);
  25007. this.propertyPath = propertyPath;
  25008. this.value = value;
  25009. this.duration = duration;
  25010. this.stopOtherAnimations = stopOtherAnimations;
  25011. this._target = target;
  25012. }
  25013. InterpolateValueAction.prototype._prepare = function () {
  25014. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25015. this._property = this._getProperty(this.propertyPath);
  25016. };
  25017. InterpolateValueAction.prototype.execute = function () {
  25018. var scene = this._actionManager.getScene();
  25019. var keys = [
  25020. {
  25021. frame: 0,
  25022. value: this._target[this._property]
  25023. },
  25024. {
  25025. frame: 100,
  25026. value: this.value
  25027. }
  25028. ];
  25029. var dataType;
  25030. if (typeof this.value === "number") {
  25031. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  25032. }
  25033. else if (this.value instanceof BABYLON.Color3) {
  25034. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  25035. }
  25036. else if (this.value instanceof BABYLON.Vector3) {
  25037. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  25038. }
  25039. else if (this.value instanceof BABYLON.Matrix) {
  25040. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  25041. }
  25042. else if (this.value instanceof BABYLON.Quaternion) {
  25043. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  25044. }
  25045. else {
  25046. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  25047. return;
  25048. }
  25049. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  25050. animation.setKeys(keys);
  25051. if (this.stopOtherAnimations) {
  25052. scene.stopAnimation(this._target);
  25053. }
  25054. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  25055. };
  25056. return InterpolateValueAction;
  25057. })(BABYLON.Action);
  25058. BABYLON.InterpolateValueAction = InterpolateValueAction;
  25059. })(BABYLON || (BABYLON = {}));
  25060. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  25061. var BABYLON;
  25062. (function (BABYLON) {
  25063. var SwitchBooleanAction = (function (_super) {
  25064. __extends(SwitchBooleanAction, _super);
  25065. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  25066. _super.call(this, triggerOptions, condition);
  25067. this.propertyPath = propertyPath;
  25068. this._target = target;
  25069. }
  25070. SwitchBooleanAction.prototype._prepare = function () {
  25071. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25072. this._property = this._getProperty(this.propertyPath);
  25073. };
  25074. SwitchBooleanAction.prototype.execute = function () {
  25075. this._target[this._property] = !this._target[this._property];
  25076. };
  25077. return SwitchBooleanAction;
  25078. })(BABYLON.Action);
  25079. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  25080. var SetStateAction = (function (_super) {
  25081. __extends(SetStateAction, _super);
  25082. function SetStateAction(triggerOptions, target, value, condition) {
  25083. _super.call(this, triggerOptions, condition);
  25084. this.value = value;
  25085. this._target = target;
  25086. }
  25087. SetStateAction.prototype.execute = function () {
  25088. this._target.state = this.value;
  25089. };
  25090. return SetStateAction;
  25091. })(BABYLON.Action);
  25092. BABYLON.SetStateAction = SetStateAction;
  25093. var SetValueAction = (function (_super) {
  25094. __extends(SetValueAction, _super);
  25095. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  25096. _super.call(this, triggerOptions, condition);
  25097. this.propertyPath = propertyPath;
  25098. this.value = value;
  25099. this._target = target;
  25100. }
  25101. SetValueAction.prototype._prepare = function () {
  25102. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25103. this._property = this._getProperty(this.propertyPath);
  25104. };
  25105. SetValueAction.prototype.execute = function () {
  25106. this._target[this._property] = this.value;
  25107. };
  25108. return SetValueAction;
  25109. })(BABYLON.Action);
  25110. BABYLON.SetValueAction = SetValueAction;
  25111. var IncrementValueAction = (function (_super) {
  25112. __extends(IncrementValueAction, _super);
  25113. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  25114. _super.call(this, triggerOptions, condition);
  25115. this.propertyPath = propertyPath;
  25116. this.value = value;
  25117. this._target = target;
  25118. }
  25119. IncrementValueAction.prototype._prepare = function () {
  25120. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  25121. this._property = this._getProperty(this.propertyPath);
  25122. if (typeof this._target[this._property] !== "number") {
  25123. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  25124. }
  25125. };
  25126. IncrementValueAction.prototype.execute = function () {
  25127. this._target[this._property] += this.value;
  25128. };
  25129. return IncrementValueAction;
  25130. })(BABYLON.Action);
  25131. BABYLON.IncrementValueAction = IncrementValueAction;
  25132. var PlayAnimationAction = (function (_super) {
  25133. __extends(PlayAnimationAction, _super);
  25134. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  25135. _super.call(this, triggerOptions, condition);
  25136. this.from = from;
  25137. this.to = to;
  25138. this.loop = loop;
  25139. this._target = target;
  25140. }
  25141. PlayAnimationAction.prototype._prepare = function () {
  25142. };
  25143. PlayAnimationAction.prototype.execute = function () {
  25144. var scene = this._actionManager.getScene();
  25145. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  25146. };
  25147. return PlayAnimationAction;
  25148. })(BABYLON.Action);
  25149. BABYLON.PlayAnimationAction = PlayAnimationAction;
  25150. var StopAnimationAction = (function (_super) {
  25151. __extends(StopAnimationAction, _super);
  25152. function StopAnimationAction(triggerOptions, target, condition) {
  25153. _super.call(this, triggerOptions, condition);
  25154. this._target = target;
  25155. }
  25156. StopAnimationAction.prototype._prepare = function () {
  25157. };
  25158. StopAnimationAction.prototype.execute = function () {
  25159. var scene = this._actionManager.getScene();
  25160. scene.stopAnimation(this._target);
  25161. };
  25162. return StopAnimationAction;
  25163. })(BABYLON.Action);
  25164. BABYLON.StopAnimationAction = StopAnimationAction;
  25165. var DoNothingAction = (function (_super) {
  25166. __extends(DoNothingAction, _super);
  25167. function DoNothingAction(triggerOptions, condition) {
  25168. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  25169. _super.call(this, triggerOptions, condition);
  25170. }
  25171. DoNothingAction.prototype.execute = function () {
  25172. };
  25173. return DoNothingAction;
  25174. })(BABYLON.Action);
  25175. BABYLON.DoNothingAction = DoNothingAction;
  25176. var CombineAction = (function (_super) {
  25177. __extends(CombineAction, _super);
  25178. function CombineAction(triggerOptions, children, condition) {
  25179. _super.call(this, triggerOptions, condition);
  25180. this.children = children;
  25181. }
  25182. CombineAction.prototype._prepare = function () {
  25183. for (var index = 0; index < this.children.length; index++) {
  25184. this.children[index]._actionManager = this._actionManager;
  25185. this.children[index]._prepare();
  25186. }
  25187. };
  25188. CombineAction.prototype.execute = function (evt) {
  25189. for (var index = 0; index < this.children.length; index++) {
  25190. this.children[index].execute(evt);
  25191. }
  25192. };
  25193. return CombineAction;
  25194. })(BABYLON.Action);
  25195. BABYLON.CombineAction = CombineAction;
  25196. var ExecuteCodeAction = (function (_super) {
  25197. __extends(ExecuteCodeAction, _super);
  25198. function ExecuteCodeAction(triggerOptions, func, condition) {
  25199. _super.call(this, triggerOptions, condition);
  25200. this.func = func;
  25201. }
  25202. ExecuteCodeAction.prototype.execute = function (evt) {
  25203. this.func(evt);
  25204. };
  25205. return ExecuteCodeAction;
  25206. })(BABYLON.Action);
  25207. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  25208. var SetParentAction = (function (_super) {
  25209. __extends(SetParentAction, _super);
  25210. function SetParentAction(triggerOptions, target, parent, condition) {
  25211. _super.call(this, triggerOptions, condition);
  25212. this._target = target;
  25213. this._parent = parent;
  25214. }
  25215. SetParentAction.prototype._prepare = function () {
  25216. };
  25217. SetParentAction.prototype.execute = function () {
  25218. if (this._target.parent === this._parent) {
  25219. return;
  25220. }
  25221. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  25222. invertParentWorldMatrix.invert();
  25223. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  25224. this._target.parent = this._parent;
  25225. };
  25226. return SetParentAction;
  25227. })(BABYLON.Action);
  25228. BABYLON.SetParentAction = SetParentAction;
  25229. var PlaySoundAction = (function (_super) {
  25230. __extends(PlaySoundAction, _super);
  25231. function PlaySoundAction(triggerOptions, sound, condition) {
  25232. _super.call(this, triggerOptions, condition);
  25233. this._sound = sound;
  25234. }
  25235. PlaySoundAction.prototype._prepare = function () {
  25236. };
  25237. PlaySoundAction.prototype.execute = function () {
  25238. if (this._sound !== undefined)
  25239. this._sound.play();
  25240. };
  25241. return PlaySoundAction;
  25242. })(BABYLON.Action);
  25243. BABYLON.PlaySoundAction = PlaySoundAction;
  25244. var StopSoundAction = (function (_super) {
  25245. __extends(StopSoundAction, _super);
  25246. function StopSoundAction(triggerOptions, sound, condition) {
  25247. _super.call(this, triggerOptions, condition);
  25248. this._sound = sound;
  25249. }
  25250. StopSoundAction.prototype._prepare = function () {
  25251. };
  25252. StopSoundAction.prototype.execute = function () {
  25253. if (this._sound !== undefined)
  25254. this._sound.stop();
  25255. };
  25256. return StopSoundAction;
  25257. })(BABYLON.Action);
  25258. BABYLON.StopSoundAction = StopSoundAction;
  25259. })(BABYLON || (BABYLON = {}));
  25260. //# sourceMappingURL=babylon.directActions.js.map
  25261. var BABYLON;
  25262. (function (BABYLON) {
  25263. var Geometry = (function () {
  25264. function Geometry(id, scene, vertexData, updatable, mesh) {
  25265. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25266. this._totalVertices = 0;
  25267. this._indices = [];
  25268. this._isDisposed = false;
  25269. this.id = id;
  25270. this._engine = scene.getEngine();
  25271. this._meshes = [];
  25272. this._scene = scene;
  25273. // vertexData
  25274. if (vertexData) {
  25275. this.setAllVerticesData(vertexData, updatable);
  25276. }
  25277. else {
  25278. this._totalVertices = 0;
  25279. this._indices = [];
  25280. }
  25281. // applyToMesh
  25282. if (mesh) {
  25283. this.applyToMesh(mesh);
  25284. mesh.computeWorldMatrix(true);
  25285. }
  25286. }
  25287. Geometry.prototype.getScene = function () {
  25288. return this._scene;
  25289. };
  25290. Geometry.prototype.getEngine = function () {
  25291. return this._engine;
  25292. };
  25293. Geometry.prototype.isReady = function () {
  25294. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  25295. };
  25296. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  25297. vertexData.applyToGeometry(this, updatable);
  25298. this.notifyUpdate();
  25299. };
  25300. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  25301. this._vertexBuffers = this._vertexBuffers || {};
  25302. if (this._vertexBuffers[kind]) {
  25303. this._vertexBuffers[kind].dispose();
  25304. }
  25305. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  25306. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25307. stride = this._vertexBuffers[kind].getStrideSize();
  25308. this._totalVertices = data.length / stride;
  25309. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25310. var meshes = this._meshes;
  25311. var numOfMeshes = meshes.length;
  25312. for (var index = 0; index < numOfMeshes; index++) {
  25313. var mesh = meshes[index];
  25314. mesh._resetPointsArrayCache();
  25315. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25316. mesh._createGlobalSubMesh();
  25317. mesh.computeWorldMatrix(true);
  25318. }
  25319. }
  25320. this.notifyUpdate(kind);
  25321. };
  25322. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  25323. var vertexBuffer = this.getVertexBuffer(kind);
  25324. if (!vertexBuffer) {
  25325. return;
  25326. }
  25327. vertexBuffer.updateDirectly(data, offset);
  25328. this.notifyUpdate(kind);
  25329. };
  25330. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  25331. var vertexBuffer = this.getVertexBuffer(kind);
  25332. if (!vertexBuffer) {
  25333. return;
  25334. }
  25335. vertexBuffer.update(data);
  25336. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25337. var extend;
  25338. var stride = vertexBuffer.getStrideSize();
  25339. this._totalVertices = data.length / stride;
  25340. if (updateExtends) {
  25341. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  25342. }
  25343. var meshes = this._meshes;
  25344. var numOfMeshes = meshes.length;
  25345. for (var index = 0; index < numOfMeshes; index++) {
  25346. var mesh = meshes[index];
  25347. mesh._resetPointsArrayCache();
  25348. if (updateExtends) {
  25349. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25350. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  25351. var subMesh = mesh.subMeshes[subIndex];
  25352. subMesh.refreshBoundingInfo();
  25353. }
  25354. }
  25355. }
  25356. }
  25357. this.notifyUpdate(kind);
  25358. };
  25359. Geometry.prototype.getTotalVertices = function () {
  25360. if (!this.isReady()) {
  25361. return 0;
  25362. }
  25363. return this._totalVertices;
  25364. };
  25365. Geometry.prototype.getVerticesData = function (kind) {
  25366. var vertexBuffer = this.getVertexBuffer(kind);
  25367. if (!vertexBuffer) {
  25368. return null;
  25369. }
  25370. return vertexBuffer.getData();
  25371. };
  25372. Geometry.prototype.getVertexBuffer = function (kind) {
  25373. if (!this.isReady()) {
  25374. return null;
  25375. }
  25376. return this._vertexBuffers[kind];
  25377. };
  25378. Geometry.prototype.getVertexBuffers = function () {
  25379. if (!this.isReady()) {
  25380. return null;
  25381. }
  25382. return this._vertexBuffers;
  25383. };
  25384. Geometry.prototype.isVerticesDataPresent = function (kind) {
  25385. if (!this._vertexBuffers) {
  25386. if (this._delayInfo) {
  25387. return this._delayInfo.indexOf(kind) !== -1;
  25388. }
  25389. return false;
  25390. }
  25391. return this._vertexBuffers[kind] !== undefined;
  25392. };
  25393. Geometry.prototype.getVerticesDataKinds = function () {
  25394. var result = [];
  25395. if (!this._vertexBuffers && this._delayInfo) {
  25396. for (var kind in this._delayInfo) {
  25397. result.push(kind);
  25398. }
  25399. }
  25400. else {
  25401. for (kind in this._vertexBuffers) {
  25402. result.push(kind);
  25403. }
  25404. }
  25405. return result;
  25406. };
  25407. Geometry.prototype.setIndices = function (indices, totalVertices) {
  25408. if (this._indexBuffer) {
  25409. this._engine._releaseBuffer(this._indexBuffer);
  25410. }
  25411. this._indices = indices;
  25412. if (this._meshes.length !== 0 && this._indices) {
  25413. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25414. }
  25415. if (totalVertices !== undefined) {
  25416. this._totalVertices = totalVertices;
  25417. }
  25418. var meshes = this._meshes;
  25419. var numOfMeshes = meshes.length;
  25420. for (var index = 0; index < numOfMeshes; index++) {
  25421. meshes[index]._createGlobalSubMesh();
  25422. }
  25423. this.notifyUpdate();
  25424. };
  25425. Geometry.prototype.getTotalIndices = function () {
  25426. if (!this.isReady()) {
  25427. return 0;
  25428. }
  25429. return this._indices.length;
  25430. };
  25431. Geometry.prototype.getIndices = function () {
  25432. if (!this.isReady()) {
  25433. return null;
  25434. }
  25435. return this._indices;
  25436. };
  25437. Geometry.prototype.getIndexBuffer = function () {
  25438. if (!this.isReady()) {
  25439. return null;
  25440. }
  25441. return this._indexBuffer;
  25442. };
  25443. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  25444. var meshes = this._meshes;
  25445. var index = meshes.indexOf(mesh);
  25446. if (index === -1) {
  25447. return;
  25448. }
  25449. for (var kind in this._vertexBuffers) {
  25450. this._vertexBuffers[kind].dispose();
  25451. }
  25452. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  25453. this._indexBuffer = null;
  25454. }
  25455. meshes.splice(index, 1);
  25456. mesh._geometry = null;
  25457. if (meshes.length === 0 && shouldDispose) {
  25458. this.dispose();
  25459. }
  25460. };
  25461. Geometry.prototype.applyToMesh = function (mesh) {
  25462. if (mesh._geometry === this) {
  25463. return;
  25464. }
  25465. var previousGeometry = mesh._geometry;
  25466. if (previousGeometry) {
  25467. previousGeometry.releaseForMesh(mesh);
  25468. }
  25469. var meshes = this._meshes;
  25470. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  25471. mesh._geometry = this;
  25472. this._scene.pushGeometry(this);
  25473. meshes.push(mesh);
  25474. if (this.isReady()) {
  25475. this._applyToMesh(mesh);
  25476. }
  25477. else {
  25478. mesh._boundingInfo = this._boundingInfo;
  25479. }
  25480. };
  25481. Geometry.prototype._applyToMesh = function (mesh) {
  25482. var numOfMeshes = this._meshes.length;
  25483. for (var kind in this._vertexBuffers) {
  25484. if (numOfMeshes === 1) {
  25485. this._vertexBuffers[kind].create();
  25486. }
  25487. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  25488. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25489. mesh._resetPointsArrayCache();
  25490. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  25491. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25492. mesh._createGlobalSubMesh();
  25493. //bounding info was just created again, world matrix should be applied again.
  25494. mesh._updateBoundingInfo();
  25495. }
  25496. }
  25497. // indexBuffer
  25498. if (numOfMeshes === 1 && this._indices) {
  25499. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25500. }
  25501. if (this._indexBuffer) {
  25502. this._indexBuffer.references = numOfMeshes;
  25503. }
  25504. };
  25505. Geometry.prototype.notifyUpdate = function (kind) {
  25506. if (this.onGeometryUpdated) {
  25507. this.onGeometryUpdated(this, kind);
  25508. }
  25509. };
  25510. Geometry.prototype.load = function (scene, onLoaded) {
  25511. var _this = this;
  25512. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25513. return;
  25514. }
  25515. if (this.isReady()) {
  25516. if (onLoaded) {
  25517. onLoaded();
  25518. }
  25519. return;
  25520. }
  25521. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  25522. scene._addPendingData(this);
  25523. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  25524. _this._delayLoadingFunction(JSON.parse(data), _this);
  25525. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25526. _this._delayInfo = [];
  25527. scene._removePendingData(_this);
  25528. var meshes = _this._meshes;
  25529. var numOfMeshes = meshes.length;
  25530. for (var index = 0; index < numOfMeshes; index++) {
  25531. _this._applyToMesh(meshes[index]);
  25532. }
  25533. if (onLoaded) {
  25534. onLoaded();
  25535. }
  25536. }, function () {
  25537. }, scene.database);
  25538. };
  25539. Geometry.prototype.isDisposed = function () {
  25540. return this._isDisposed;
  25541. };
  25542. Geometry.prototype.dispose = function () {
  25543. var meshes = this._meshes;
  25544. var numOfMeshes = meshes.length;
  25545. var index;
  25546. for (index = 0; index < numOfMeshes; index++) {
  25547. this.releaseForMesh(meshes[index]);
  25548. }
  25549. this._meshes = [];
  25550. for (var kind in this._vertexBuffers) {
  25551. this._vertexBuffers[kind].dispose();
  25552. }
  25553. this._vertexBuffers = [];
  25554. this._totalVertices = 0;
  25555. if (this._indexBuffer) {
  25556. this._engine._releaseBuffer(this._indexBuffer);
  25557. }
  25558. this._indexBuffer = null;
  25559. this._indices = [];
  25560. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25561. this.delayLoadingFile = null;
  25562. this._delayLoadingFunction = null;
  25563. this._delayInfo = [];
  25564. this._boundingInfo = null; // todo: .dispose()
  25565. this._scene.removeGeometry(this);
  25566. this._isDisposed = true;
  25567. };
  25568. Geometry.prototype.copy = function (id) {
  25569. var vertexData = new BABYLON.VertexData();
  25570. vertexData.indices = [];
  25571. var indices = this.getIndices();
  25572. for (var index = 0; index < indices.length; index++) {
  25573. vertexData.indices.push(indices[index]);
  25574. }
  25575. var updatable = false;
  25576. var stopChecking = false;
  25577. for (var kind in this._vertexBuffers) {
  25578. // using slice() to make a copy of the array and not just reference it
  25579. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  25580. if (!stopChecking) {
  25581. updatable = this.getVertexBuffer(kind).isUpdatable();
  25582. stopChecking = !updatable;
  25583. }
  25584. }
  25585. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  25586. geometry.delayLoadState = this.delayLoadState;
  25587. geometry.delayLoadingFile = this.delayLoadingFile;
  25588. geometry._delayLoadingFunction = this._delayLoadingFunction;
  25589. for (kind in this._delayInfo) {
  25590. geometry._delayInfo = geometry._delayInfo || [];
  25591. geometry._delayInfo.push(kind);
  25592. }
  25593. // Bounding info
  25594. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  25595. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25596. return geometry;
  25597. };
  25598. // Statics
  25599. Geometry.ExtractFromMesh = function (mesh, id) {
  25600. var geometry = mesh._geometry;
  25601. if (!geometry) {
  25602. return null;
  25603. }
  25604. return geometry.copy(id);
  25605. };
  25606. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  25607. // be aware Math.random() could cause collisions
  25608. Geometry.RandomId = function () {
  25609. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  25610. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  25611. return v.toString(16);
  25612. });
  25613. };
  25614. return Geometry;
  25615. })();
  25616. BABYLON.Geometry = Geometry;
  25617. /////// Primitives //////////////////////////////////////////////
  25618. var Geometry;
  25619. (function (Geometry) {
  25620. var Primitives;
  25621. (function (Primitives) {
  25622. /// Abstract class
  25623. var _Primitive = (function (_super) {
  25624. __extends(_Primitive, _super);
  25625. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  25626. this._beingRegenerated = true;
  25627. this._canBeRegenerated = canBeRegenerated;
  25628. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  25629. this._beingRegenerated = false;
  25630. }
  25631. _Primitive.prototype.canBeRegenerated = function () {
  25632. return this._canBeRegenerated;
  25633. };
  25634. _Primitive.prototype.regenerate = function () {
  25635. if (!this._canBeRegenerated) {
  25636. return;
  25637. }
  25638. this._beingRegenerated = true;
  25639. this.setAllVerticesData(this._regenerateVertexData(), false);
  25640. this._beingRegenerated = false;
  25641. };
  25642. _Primitive.prototype.asNewGeometry = function (id) {
  25643. return _super.prototype.copy.call(this, id);
  25644. };
  25645. // overrides
  25646. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  25647. if (!this._beingRegenerated) {
  25648. return;
  25649. }
  25650. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  25651. };
  25652. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  25653. if (!this._beingRegenerated) {
  25654. return;
  25655. }
  25656. _super.prototype.setVerticesData.call(this, kind, data, false);
  25657. };
  25658. // to override
  25659. // protected
  25660. _Primitive.prototype._regenerateVertexData = function () {
  25661. throw new Error("Abstract method");
  25662. };
  25663. _Primitive.prototype.copy = function (id) {
  25664. throw new Error("Must be overriden in sub-classes.");
  25665. };
  25666. return _Primitive;
  25667. })(Geometry);
  25668. Primitives._Primitive = _Primitive;
  25669. var Ribbon = (function (_super) {
  25670. __extends(Ribbon, _super);
  25671. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  25672. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25673. this.pathArray = pathArray;
  25674. this.closeArray = closeArray;
  25675. this.closePath = closePath;
  25676. this.offset = offset;
  25677. this.side = side;
  25678. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25679. }
  25680. Ribbon.prototype._regenerateVertexData = function () {
  25681. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  25682. };
  25683. Ribbon.prototype.copy = function (id) {
  25684. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  25685. };
  25686. return Ribbon;
  25687. })(_Primitive);
  25688. Primitives.Ribbon = Ribbon;
  25689. var Box = (function (_super) {
  25690. __extends(Box, _super);
  25691. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  25692. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25693. this.size = size;
  25694. this.side = side;
  25695. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25696. }
  25697. Box.prototype._regenerateVertexData = function () {
  25698. return BABYLON.VertexData.CreateBox(this.size, this.side);
  25699. };
  25700. Box.prototype.copy = function (id) {
  25701. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25702. };
  25703. return Box;
  25704. })(_Primitive);
  25705. Primitives.Box = Box;
  25706. var Sphere = (function (_super) {
  25707. __extends(Sphere, _super);
  25708. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  25709. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25710. this.segments = segments;
  25711. this.diameter = diameter;
  25712. this.side = side;
  25713. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25714. }
  25715. Sphere.prototype._regenerateVertexData = function () {
  25716. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  25717. };
  25718. Sphere.prototype.copy = function (id) {
  25719. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  25720. };
  25721. return Sphere;
  25722. })(_Primitive);
  25723. Primitives.Sphere = Sphere;
  25724. var Cylinder = (function (_super) {
  25725. __extends(Cylinder, _super);
  25726. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  25727. if (subdivisions === void 0) { subdivisions = 1; }
  25728. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25729. this.height = height;
  25730. this.diameterTop = diameterTop;
  25731. this.diameterBottom = diameterBottom;
  25732. this.tessellation = tessellation;
  25733. this.subdivisions = subdivisions;
  25734. this.side = side;
  25735. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25736. }
  25737. Cylinder.prototype._regenerateVertexData = function () {
  25738. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  25739. };
  25740. Cylinder.prototype.copy = function (id) {
  25741. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  25742. };
  25743. return Cylinder;
  25744. })(_Primitive);
  25745. Primitives.Cylinder = Cylinder;
  25746. var Torus = (function (_super) {
  25747. __extends(Torus, _super);
  25748. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  25749. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25750. this.diameter = diameter;
  25751. this.thickness = thickness;
  25752. this.tessellation = tessellation;
  25753. this.side = side;
  25754. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25755. }
  25756. Torus.prototype._regenerateVertexData = function () {
  25757. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  25758. };
  25759. Torus.prototype.copy = function (id) {
  25760. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  25761. };
  25762. return Torus;
  25763. })(_Primitive);
  25764. Primitives.Torus = Torus;
  25765. var Ground = (function (_super) {
  25766. __extends(Ground, _super);
  25767. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  25768. this.width = width;
  25769. this.height = height;
  25770. this.subdivisions = subdivisions;
  25771. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25772. }
  25773. Ground.prototype._regenerateVertexData = function () {
  25774. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  25775. };
  25776. Ground.prototype.copy = function (id) {
  25777. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  25778. };
  25779. return Ground;
  25780. })(_Primitive);
  25781. Primitives.Ground = Ground;
  25782. var TiledGround = (function (_super) {
  25783. __extends(TiledGround, _super);
  25784. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  25785. this.xmin = xmin;
  25786. this.zmin = zmin;
  25787. this.xmax = xmax;
  25788. this.zmax = zmax;
  25789. this.subdivisions = subdivisions;
  25790. this.precision = precision;
  25791. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25792. }
  25793. TiledGround.prototype._regenerateVertexData = function () {
  25794. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  25795. };
  25796. TiledGround.prototype.copy = function (id) {
  25797. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  25798. };
  25799. return TiledGround;
  25800. })(_Primitive);
  25801. Primitives.TiledGround = TiledGround;
  25802. var Plane = (function (_super) {
  25803. __extends(Plane, _super);
  25804. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  25805. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25806. this.size = size;
  25807. this.side = side;
  25808. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25809. }
  25810. Plane.prototype._regenerateVertexData = function () {
  25811. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  25812. };
  25813. Plane.prototype.copy = function (id) {
  25814. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25815. };
  25816. return Plane;
  25817. })(_Primitive);
  25818. Primitives.Plane = Plane;
  25819. var TorusKnot = (function (_super) {
  25820. __extends(TorusKnot, _super);
  25821. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  25822. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25823. this.radius = radius;
  25824. this.tube = tube;
  25825. this.radialSegments = radialSegments;
  25826. this.tubularSegments = tubularSegments;
  25827. this.p = p;
  25828. this.q = q;
  25829. this.side = side;
  25830. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25831. }
  25832. TorusKnot.prototype._regenerateVertexData = function () {
  25833. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  25834. };
  25835. TorusKnot.prototype.copy = function (id) {
  25836. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  25837. };
  25838. return TorusKnot;
  25839. })(_Primitive);
  25840. Primitives.TorusKnot = TorusKnot;
  25841. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  25842. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  25843. })(BABYLON || (BABYLON = {}));
  25844. //# sourceMappingURL=babylon.geometry.js.map
  25845. var BABYLON;
  25846. (function (BABYLON) {
  25847. var Gamepads = (function () {
  25848. function Gamepads(ongamedpadconnected) {
  25849. var _this = this;
  25850. this.babylonGamepads = [];
  25851. this.oneGamepadConnected = false;
  25852. this.isMonitoring = false;
  25853. this.gamepadEventSupported = 'GamepadEvent' in window;
  25854. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  25855. 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=";
  25856. this._callbackGamepadConnected = ongamedpadconnected;
  25857. if (this.gamepadSupportAvailable) {
  25858. // Checking if the gamepad connected event is supported (like in Firefox)
  25859. if (this.gamepadEventSupported) {
  25860. window.addEventListener('gamepadconnected', function (evt) {
  25861. _this._onGamepadConnected(evt);
  25862. }, false);
  25863. window.addEventListener('gamepaddisconnected', function (evt) {
  25864. _this._onGamepadDisconnected(evt);
  25865. }, false);
  25866. }
  25867. else {
  25868. this._startMonitoringGamepads();
  25869. }
  25870. if (!this.oneGamepadConnected) {
  25871. this._insertGamepadDOMInstructions();
  25872. }
  25873. }
  25874. else {
  25875. this._insertGamepadDOMNotSupported();
  25876. }
  25877. }
  25878. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  25879. Gamepads.gamepadDOMInfo = document.createElement("div");
  25880. var buttonAImage = document.createElement("img");
  25881. buttonAImage.src = this.buttonADataURL;
  25882. var spanMessage = document.createElement("span");
  25883. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  25884. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  25885. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  25886. Gamepads.gamepadDOMInfo.style.position = "absolute";
  25887. Gamepads.gamepadDOMInfo.style.width = "100%";
  25888. Gamepads.gamepadDOMInfo.style.height = "48px";
  25889. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  25890. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  25891. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  25892. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  25893. buttonAImage.style.position = "relative";
  25894. buttonAImage.style.bottom = "8px";
  25895. spanMessage.style.position = "relative";
  25896. spanMessage.style.fontSize = "32px";
  25897. spanMessage.style.bottom = "32px";
  25898. spanMessage.style.color = "green";
  25899. document.body.appendChild(Gamepads.gamepadDOMInfo);
  25900. };
  25901. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  25902. Gamepads.gamepadDOMInfo = document.createElement("div");
  25903. var spanMessage = document.createElement("span");
  25904. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  25905. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  25906. Gamepads.gamepadDOMInfo.style.position = "absolute";
  25907. Gamepads.gamepadDOMInfo.style.width = "100%";
  25908. Gamepads.gamepadDOMInfo.style.height = "40px";
  25909. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  25910. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  25911. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  25912. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  25913. spanMessage.style.position = "relative";
  25914. spanMessage.style.fontSize = "32px";
  25915. spanMessage.style.color = "red";
  25916. document.body.appendChild(Gamepads.gamepadDOMInfo);
  25917. };
  25918. Gamepads.prototype.dispose = function () {
  25919. if (Gamepads.gamepadDOMInfo) {
  25920. document.body.removeChild(Gamepads.gamepadDOMInfo);
  25921. }
  25922. };
  25923. Gamepads.prototype._onGamepadConnected = function (evt) {
  25924. var newGamepad = this._addNewGamepad(evt.gamepad);
  25925. if (this._callbackGamepadConnected)
  25926. this._callbackGamepadConnected(newGamepad);
  25927. this._startMonitoringGamepads();
  25928. };
  25929. Gamepads.prototype._addNewGamepad = function (gamepad) {
  25930. if (!this.oneGamepadConnected) {
  25931. this.oneGamepadConnected = true;
  25932. if (Gamepads.gamepadDOMInfo) {
  25933. document.body.removeChild(Gamepads.gamepadDOMInfo);
  25934. Gamepads.gamepadDOMInfo = null;
  25935. }
  25936. }
  25937. var newGamepad;
  25938. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  25939. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  25940. }
  25941. else {
  25942. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  25943. }
  25944. this.babylonGamepads.push(newGamepad);
  25945. return newGamepad;
  25946. };
  25947. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  25948. for (var i in this.babylonGamepads) {
  25949. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  25950. this.babylonGamepads.splice(i, 1);
  25951. break;
  25952. }
  25953. }
  25954. // If no gamepads are left, stop the polling loop.
  25955. if (this.babylonGamepads.length == 0) {
  25956. this._stopMonitoringGamepads();
  25957. }
  25958. };
  25959. Gamepads.prototype._startMonitoringGamepads = function () {
  25960. if (!this.isMonitoring) {
  25961. this.isMonitoring = true;
  25962. this._checkGamepadsStatus();
  25963. }
  25964. };
  25965. Gamepads.prototype._stopMonitoringGamepads = function () {
  25966. this.isMonitoring = false;
  25967. };
  25968. Gamepads.prototype._checkGamepadsStatus = function () {
  25969. var _this = this;
  25970. // updating gamepad objects
  25971. this._updateGamepadObjects();
  25972. for (var i in this.babylonGamepads) {
  25973. this.babylonGamepads[i].update();
  25974. }
  25975. if (this.isMonitoring) {
  25976. if (window.requestAnimationFrame) {
  25977. window.requestAnimationFrame(function () {
  25978. _this._checkGamepadsStatus();
  25979. });
  25980. }
  25981. else if (window.mozRequestAnimationFrame) {
  25982. window.mozRequestAnimationFrame(function () {
  25983. _this._checkGamepadsStatus();
  25984. });
  25985. }
  25986. else if (window.webkitRequestAnimationFrame) {
  25987. window.webkitRequestAnimationFrame(function () {
  25988. _this._checkGamepadsStatus();
  25989. });
  25990. }
  25991. }
  25992. };
  25993. // This function is called only on Chrome, which does not yet support
  25994. // connection/disconnection events, but requires you to monitor
  25995. // an array for changes.
  25996. Gamepads.prototype._updateGamepadObjects = function () {
  25997. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  25998. for (var i = 0; i < gamepads.length; i++) {
  25999. if (gamepads[i]) {
  26000. if (!(gamepads[i].index in this.babylonGamepads)) {
  26001. var newGamepad = this._addNewGamepad(gamepads[i]);
  26002. if (this._callbackGamepadConnected) {
  26003. this._callbackGamepadConnected(newGamepad);
  26004. }
  26005. }
  26006. else {
  26007. this.babylonGamepads[i].browserGamepad = gamepads[i];
  26008. }
  26009. }
  26010. }
  26011. };
  26012. return Gamepads;
  26013. })();
  26014. BABYLON.Gamepads = Gamepads;
  26015. var StickValues = (function () {
  26016. function StickValues(x, y) {
  26017. this.x = x;
  26018. this.y = y;
  26019. }
  26020. return StickValues;
  26021. })();
  26022. BABYLON.StickValues = StickValues;
  26023. var Gamepad = (function () {
  26024. function Gamepad(id, index, browserGamepad) {
  26025. this.id = id;
  26026. this.index = index;
  26027. this.browserGamepad = browserGamepad;
  26028. if (this.browserGamepad.axes.length >= 2) {
  26029. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  26030. }
  26031. if (this.browserGamepad.axes.length >= 4) {
  26032. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  26033. }
  26034. }
  26035. Gamepad.prototype.onleftstickchanged = function (callback) {
  26036. this._onleftstickchanged = callback;
  26037. };
  26038. Gamepad.prototype.onrightstickchanged = function (callback) {
  26039. this._onrightstickchanged = callback;
  26040. };
  26041. Object.defineProperty(Gamepad.prototype, "leftStick", {
  26042. get: function () {
  26043. return this._leftStick;
  26044. },
  26045. set: function (newValues) {
  26046. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  26047. this._onleftstickchanged(newValues);
  26048. }
  26049. this._leftStick = newValues;
  26050. },
  26051. enumerable: true,
  26052. configurable: true
  26053. });
  26054. Object.defineProperty(Gamepad.prototype, "rightStick", {
  26055. get: function () {
  26056. return this._rightStick;
  26057. },
  26058. set: function (newValues) {
  26059. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  26060. this._onrightstickchanged(newValues);
  26061. }
  26062. this._rightStick = newValues;
  26063. },
  26064. enumerable: true,
  26065. configurable: true
  26066. });
  26067. Gamepad.prototype.update = function () {
  26068. if (this._leftStick) {
  26069. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  26070. }
  26071. if (this._rightStick) {
  26072. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  26073. }
  26074. };
  26075. return Gamepad;
  26076. })();
  26077. BABYLON.Gamepad = Gamepad;
  26078. var GenericPad = (function (_super) {
  26079. __extends(GenericPad, _super);
  26080. function GenericPad(id, index, gamepad) {
  26081. _super.call(this, id, index, gamepad);
  26082. this.id = id;
  26083. this.index = index;
  26084. this.gamepad = gamepad;
  26085. this._buttons = new Array(gamepad.buttons.length);
  26086. }
  26087. GenericPad.prototype.onbuttondown = function (callback) {
  26088. this._onbuttondown = callback;
  26089. };
  26090. GenericPad.prototype.onbuttonup = function (callback) {
  26091. this._onbuttonup = callback;
  26092. };
  26093. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  26094. if (newValue !== currentValue) {
  26095. if (this._onbuttondown && newValue === 1) {
  26096. this._onbuttondown(buttonIndex);
  26097. }
  26098. if (this._onbuttonup && newValue === 0) {
  26099. this._onbuttonup(buttonIndex);
  26100. }
  26101. }
  26102. return newValue;
  26103. };
  26104. GenericPad.prototype.update = function () {
  26105. _super.prototype.update.call(this);
  26106. for (var index = 0; index < this._buttons.length; index++) {
  26107. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  26108. }
  26109. };
  26110. return GenericPad;
  26111. })(Gamepad);
  26112. BABYLON.GenericPad = GenericPad;
  26113. (function (Xbox360Button) {
  26114. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  26115. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  26116. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  26117. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  26118. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  26119. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  26120. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  26121. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  26122. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  26123. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  26124. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  26125. var Xbox360Button = BABYLON.Xbox360Button;
  26126. (function (Xbox360Dpad) {
  26127. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  26128. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  26129. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  26130. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  26131. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  26132. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  26133. var Xbox360Pad = (function (_super) {
  26134. __extends(Xbox360Pad, _super);
  26135. function Xbox360Pad() {
  26136. _super.apply(this, arguments);
  26137. this._leftTrigger = 0;
  26138. this._rightTrigger = 0;
  26139. this._buttonA = 0;
  26140. this._buttonB = 0;
  26141. this._buttonX = 0;
  26142. this._buttonY = 0;
  26143. this._buttonBack = 0;
  26144. this._buttonStart = 0;
  26145. this._buttonLB = 0;
  26146. this._buttonRB = 0;
  26147. this._buttonLeftStick = 0;
  26148. this._buttonRightStick = 0;
  26149. this._dPadUp = 0;
  26150. this._dPadDown = 0;
  26151. this._dPadLeft = 0;
  26152. this._dPadRight = 0;
  26153. }
  26154. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  26155. this._onlefttriggerchanged = callback;
  26156. };
  26157. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  26158. this._onrighttriggerchanged = callback;
  26159. };
  26160. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  26161. get: function () {
  26162. return this._leftTrigger;
  26163. },
  26164. set: function (newValue) {
  26165. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  26166. this._onlefttriggerchanged(newValue);
  26167. }
  26168. this._leftTrigger = newValue;
  26169. },
  26170. enumerable: true,
  26171. configurable: true
  26172. });
  26173. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  26174. get: function () {
  26175. return this._rightTrigger;
  26176. },
  26177. set: function (newValue) {
  26178. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  26179. this._onrighttriggerchanged(newValue);
  26180. }
  26181. this._rightTrigger = newValue;
  26182. },
  26183. enumerable: true,
  26184. configurable: true
  26185. });
  26186. Xbox360Pad.prototype.onbuttondown = function (callback) {
  26187. this._onbuttondown = callback;
  26188. };
  26189. Xbox360Pad.prototype.onbuttonup = function (callback) {
  26190. this._onbuttonup = callback;
  26191. };
  26192. Xbox360Pad.prototype.ondpaddown = function (callback) {
  26193. this._ondpaddown = callback;
  26194. };
  26195. Xbox360Pad.prototype.ondpadup = function (callback) {
  26196. this._ondpadup = callback;
  26197. };
  26198. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  26199. if (newValue !== currentValue) {
  26200. if (this._onbuttondown && newValue === 1) {
  26201. this._onbuttondown(buttonType);
  26202. }
  26203. if (this._onbuttonup && newValue === 0) {
  26204. this._onbuttonup(buttonType);
  26205. }
  26206. }
  26207. return newValue;
  26208. };
  26209. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  26210. if (newValue !== currentValue) {
  26211. if (this._ondpaddown && newValue === 1) {
  26212. this._ondpaddown(buttonType);
  26213. }
  26214. if (this._ondpadup && newValue === 0) {
  26215. this._ondpadup(buttonType);
  26216. }
  26217. }
  26218. return newValue;
  26219. };
  26220. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  26221. get: function () {
  26222. return this._buttonA;
  26223. },
  26224. set: function (value) {
  26225. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  26226. },
  26227. enumerable: true,
  26228. configurable: true
  26229. });
  26230. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  26231. get: function () {
  26232. return this._buttonB;
  26233. },
  26234. set: function (value) {
  26235. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  26236. },
  26237. enumerable: true,
  26238. configurable: true
  26239. });
  26240. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  26241. get: function () {
  26242. return this._buttonX;
  26243. },
  26244. set: function (value) {
  26245. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  26246. },
  26247. enumerable: true,
  26248. configurable: true
  26249. });
  26250. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  26251. get: function () {
  26252. return this._buttonY;
  26253. },
  26254. set: function (value) {
  26255. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  26256. },
  26257. enumerable: true,
  26258. configurable: true
  26259. });
  26260. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  26261. get: function () {
  26262. return this._buttonStart;
  26263. },
  26264. set: function (value) {
  26265. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  26266. },
  26267. enumerable: true,
  26268. configurable: true
  26269. });
  26270. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  26271. get: function () {
  26272. return this._buttonBack;
  26273. },
  26274. set: function (value) {
  26275. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  26276. },
  26277. enumerable: true,
  26278. configurable: true
  26279. });
  26280. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  26281. get: function () {
  26282. return this._buttonLB;
  26283. },
  26284. set: function (value) {
  26285. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  26286. },
  26287. enumerable: true,
  26288. configurable: true
  26289. });
  26290. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  26291. get: function () {
  26292. return this._buttonRB;
  26293. },
  26294. set: function (value) {
  26295. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  26296. },
  26297. enumerable: true,
  26298. configurable: true
  26299. });
  26300. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  26301. get: function () {
  26302. return this._buttonLeftStick;
  26303. },
  26304. set: function (value) {
  26305. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  26306. },
  26307. enumerable: true,
  26308. configurable: true
  26309. });
  26310. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  26311. get: function () {
  26312. return this._buttonRightStick;
  26313. },
  26314. set: function (value) {
  26315. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  26316. },
  26317. enumerable: true,
  26318. configurable: true
  26319. });
  26320. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  26321. get: function () {
  26322. return this._dPadUp;
  26323. },
  26324. set: function (value) {
  26325. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  26326. },
  26327. enumerable: true,
  26328. configurable: true
  26329. });
  26330. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  26331. get: function () {
  26332. return this._dPadDown;
  26333. },
  26334. set: function (value) {
  26335. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  26336. },
  26337. enumerable: true,
  26338. configurable: true
  26339. });
  26340. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  26341. get: function () {
  26342. return this._dPadLeft;
  26343. },
  26344. set: function (value) {
  26345. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  26346. },
  26347. enumerable: true,
  26348. configurable: true
  26349. });
  26350. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  26351. get: function () {
  26352. return this._dPadRight;
  26353. },
  26354. set: function (value) {
  26355. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  26356. },
  26357. enumerable: true,
  26358. configurable: true
  26359. });
  26360. Xbox360Pad.prototype.update = function () {
  26361. _super.prototype.update.call(this);
  26362. this.buttonA = this.browserGamepad.buttons[0].value;
  26363. this.buttonB = this.browserGamepad.buttons[1].value;
  26364. this.buttonX = this.browserGamepad.buttons[2].value;
  26365. this.buttonY = this.browserGamepad.buttons[3].value;
  26366. this.buttonLB = this.browserGamepad.buttons[4].value;
  26367. this.buttonRB = this.browserGamepad.buttons[5].value;
  26368. this.leftTrigger = this.browserGamepad.buttons[6].value;
  26369. this.rightTrigger = this.browserGamepad.buttons[7].value;
  26370. this.buttonBack = this.browserGamepad.buttons[8].value;
  26371. this.buttonStart = this.browserGamepad.buttons[9].value;
  26372. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  26373. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  26374. this.dPadUp = this.browserGamepad.buttons[12].value;
  26375. this.dPadDown = this.browserGamepad.buttons[13].value;
  26376. this.dPadLeft = this.browserGamepad.buttons[14].value;
  26377. this.dPadRight = this.browserGamepad.buttons[15].value;
  26378. };
  26379. return Xbox360Pad;
  26380. })(Gamepad);
  26381. BABYLON.Xbox360Pad = Xbox360Pad;
  26382. })(BABYLON || (BABYLON = {}));
  26383. //# sourceMappingURL=babylon.gamepads.js.map
  26384. var BABYLON;
  26385. (function (BABYLON) {
  26386. // We're mainly based on the logic defined into the FreeCamera code
  26387. var GamepadCamera = (function (_super) {
  26388. __extends(GamepadCamera, _super);
  26389. function GamepadCamera(name, position, scene) {
  26390. var _this = this;
  26391. _super.call(this, name, position, scene);
  26392. this.angularSensibility = 200;
  26393. this.moveSensibility = 75;
  26394. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  26395. _this._onNewGameConnected(gamepad);
  26396. });
  26397. }
  26398. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  26399. // Only the first gamepad can control the camera
  26400. if (gamepad.index === 0) {
  26401. this._gamepad = gamepad;
  26402. }
  26403. };
  26404. GamepadCamera.prototype._checkInputs = function () {
  26405. if (!this._gamepad) {
  26406. return;
  26407. }
  26408. var LSValues = this._gamepad.leftStick;
  26409. var normalizedLX = LSValues.x / this.moveSensibility;
  26410. var normalizedLY = LSValues.y / this.moveSensibility;
  26411. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  26412. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  26413. var RSValues = this._gamepad.rightStick;
  26414. var normalizedRX = RSValues.x / this.angularSensibility;
  26415. var normalizedRY = RSValues.y / this.angularSensibility;
  26416. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  26417. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  26418. ;
  26419. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  26420. var speed = this._computeLocalCameraSpeed() * 50.0;
  26421. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  26422. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  26423. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  26424. };
  26425. GamepadCamera.prototype.dispose = function () {
  26426. this._gamepads.dispose();
  26427. _super.prototype.dispose.call(this);
  26428. };
  26429. return GamepadCamera;
  26430. })(BABYLON.FreeCamera);
  26431. BABYLON.GamepadCamera = GamepadCamera;
  26432. })(BABYLON || (BABYLON = {}));
  26433. //# sourceMappingURL=babylon.gamepadCamera.js.map
  26434. var BABYLON;
  26435. (function (BABYLON) {
  26436. var LinesMesh = (function (_super) {
  26437. __extends(LinesMesh, _super);
  26438. function LinesMesh(name, scene, updatable) {
  26439. if (updatable === void 0) { updatable = false; }
  26440. _super.call(this, name, scene);
  26441. this.color = new BABYLON.Color3(1, 1, 1);
  26442. this.alpha = 1;
  26443. this._indices = new Array();
  26444. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  26445. attributes: ["position"],
  26446. uniforms: ["worldViewProjection", "color"],
  26447. needAlphaBlending: true
  26448. });
  26449. }
  26450. Object.defineProperty(LinesMesh.prototype, "material", {
  26451. get: function () {
  26452. return this._colorShader;
  26453. },
  26454. enumerable: true,
  26455. configurable: true
  26456. });
  26457. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  26458. get: function () {
  26459. return false;
  26460. },
  26461. enumerable: true,
  26462. configurable: true
  26463. });
  26464. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  26465. get: function () {
  26466. return false;
  26467. },
  26468. enumerable: true,
  26469. configurable: true
  26470. });
  26471. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  26472. var engine = this.getScene().getEngine();
  26473. var indexToBind = this._geometry.getIndexBuffer();
  26474. // VBOs
  26475. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  26476. // Color
  26477. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  26478. };
  26479. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  26480. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26481. return;
  26482. }
  26483. var engine = this.getScene().getEngine();
  26484. // Draw order
  26485. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  26486. };
  26487. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  26488. return null;
  26489. };
  26490. LinesMesh.prototype.dispose = function (doNotRecurse) {
  26491. this._colorShader.dispose();
  26492. _super.prototype.dispose.call(this, doNotRecurse);
  26493. };
  26494. return LinesMesh;
  26495. })(BABYLON.Mesh);
  26496. BABYLON.LinesMesh = LinesMesh;
  26497. })(BABYLON || (BABYLON = {}));
  26498. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  26499. (function (BABYLON) {
  26500. var OutlineRenderer = (function () {
  26501. function OutlineRenderer(scene) {
  26502. this._scene = scene;
  26503. }
  26504. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  26505. var _this = this;
  26506. if (useOverlay === void 0) { useOverlay = false; }
  26507. var scene = this._scene;
  26508. var engine = this._scene.getEngine();
  26509. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  26510. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  26511. return;
  26512. }
  26513. var mesh = subMesh.getRenderingMesh();
  26514. var material = subMesh.getMaterial();
  26515. engine.enableEffect(this._effect);
  26516. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  26517. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  26518. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  26519. // Bones
  26520. if (mesh.useBones) {
  26521. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  26522. }
  26523. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  26524. // Alpha test
  26525. if (material && material.needAlphaTesting()) {
  26526. var alphaTexture = material.getAlphaTestTexture();
  26527. this._effect.setTexture("diffuseSampler", alphaTexture);
  26528. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  26529. }
  26530. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  26531. _this._effect.setMatrix("world", world);
  26532. });
  26533. };
  26534. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  26535. var defines = [];
  26536. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  26537. var mesh = subMesh.getMesh();
  26538. var material = subMesh.getMaterial();
  26539. // Alpha test
  26540. if (material && material.needAlphaTesting()) {
  26541. defines.push("#define ALPHATEST");
  26542. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26543. attribs.push(BABYLON.VertexBuffer.UVKind);
  26544. defines.push("#define UV1");
  26545. }
  26546. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26547. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  26548. defines.push("#define UV2");
  26549. }
  26550. }
  26551. // Bones
  26552. if (mesh.useBones) {
  26553. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26554. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26555. defines.push("#define BONES");
  26556. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  26557. }
  26558. // Instances
  26559. if (useInstances) {
  26560. defines.push("#define INSTANCES");
  26561. attribs.push("world0");
  26562. attribs.push("world1");
  26563. attribs.push("world2");
  26564. attribs.push("world3");
  26565. }
  26566. // Get correct effect
  26567. var join = defines.join("\n");
  26568. if (this._cachedDefines !== join) {
  26569. this._cachedDefines = join;
  26570. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  26571. }
  26572. return this._effect.isReady();
  26573. };
  26574. return OutlineRenderer;
  26575. })();
  26576. BABYLON.OutlineRenderer = OutlineRenderer;
  26577. })(BABYLON || (BABYLON = {}));
  26578. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  26579. (function (BABYLON) {
  26580. var MeshAssetTask = (function () {
  26581. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  26582. this.name = name;
  26583. this.meshesNames = meshesNames;
  26584. this.rootUrl = rootUrl;
  26585. this.sceneFilename = sceneFilename;
  26586. this.isCompleted = false;
  26587. }
  26588. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26589. var _this = this;
  26590. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  26591. _this.loadedMeshes = meshes;
  26592. _this.loadedParticleSystems = particleSystems;
  26593. _this.loadedSkeletons = skeletons;
  26594. _this.isCompleted = true;
  26595. if (_this.onSuccess) {
  26596. _this.onSuccess(_this);
  26597. }
  26598. onSuccess();
  26599. }, null, function () {
  26600. if (_this.onError) {
  26601. _this.onError(_this);
  26602. }
  26603. onError();
  26604. });
  26605. };
  26606. return MeshAssetTask;
  26607. })();
  26608. BABYLON.MeshAssetTask = MeshAssetTask;
  26609. var TextFileAssetTask = (function () {
  26610. function TextFileAssetTask(name, url) {
  26611. this.name = name;
  26612. this.url = url;
  26613. this.isCompleted = false;
  26614. }
  26615. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26616. var _this = this;
  26617. BABYLON.Tools.LoadFile(this.url, function (data) {
  26618. _this.text = data;
  26619. _this.isCompleted = true;
  26620. if (_this.onSuccess) {
  26621. _this.onSuccess(_this);
  26622. }
  26623. onSuccess();
  26624. }, null, scene.database, false, function () {
  26625. if (_this.onError) {
  26626. _this.onError(_this);
  26627. }
  26628. onError();
  26629. });
  26630. };
  26631. return TextFileAssetTask;
  26632. })();
  26633. BABYLON.TextFileAssetTask = TextFileAssetTask;
  26634. var BinaryFileAssetTask = (function () {
  26635. function BinaryFileAssetTask(name, url) {
  26636. this.name = name;
  26637. this.url = url;
  26638. this.isCompleted = false;
  26639. }
  26640. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26641. var _this = this;
  26642. BABYLON.Tools.LoadFile(this.url, function (data) {
  26643. _this.data = data;
  26644. _this.isCompleted = true;
  26645. if (_this.onSuccess) {
  26646. _this.onSuccess(_this);
  26647. }
  26648. onSuccess();
  26649. }, null, scene.database, true, function () {
  26650. if (_this.onError) {
  26651. _this.onError(_this);
  26652. }
  26653. onError();
  26654. });
  26655. };
  26656. return BinaryFileAssetTask;
  26657. })();
  26658. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  26659. var ImageAssetTask = (function () {
  26660. function ImageAssetTask(name, url) {
  26661. this.name = name;
  26662. this.url = url;
  26663. this.isCompleted = false;
  26664. }
  26665. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26666. var _this = this;
  26667. var img = new Image();
  26668. img.onload = function () {
  26669. _this.image = img;
  26670. _this.isCompleted = true;
  26671. if (_this.onSuccess) {
  26672. _this.onSuccess(_this);
  26673. }
  26674. onSuccess();
  26675. };
  26676. img.onerror = function () {
  26677. if (_this.onError) {
  26678. _this.onError(_this);
  26679. }
  26680. onError();
  26681. };
  26682. img.src = this.url;
  26683. };
  26684. return ImageAssetTask;
  26685. })();
  26686. BABYLON.ImageAssetTask = ImageAssetTask;
  26687. var TextureAssetTask = (function () {
  26688. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  26689. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26690. this.name = name;
  26691. this.url = url;
  26692. this.noMipmap = noMipmap;
  26693. this.invertY = invertY;
  26694. this.samplingMode = samplingMode;
  26695. this.isCompleted = false;
  26696. }
  26697. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26698. var _this = this;
  26699. var onload = function () {
  26700. _this.isCompleted = true;
  26701. if (_this.onSuccess) {
  26702. _this.onSuccess(_this);
  26703. }
  26704. onSuccess();
  26705. };
  26706. var onerror = function () {
  26707. if (_this.onError) {
  26708. _this.onError(_this);
  26709. }
  26710. onError();
  26711. };
  26712. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  26713. };
  26714. return TextureAssetTask;
  26715. })();
  26716. BABYLON.TextureAssetTask = TextureAssetTask;
  26717. var AssetsManager = (function () {
  26718. function AssetsManager(scene) {
  26719. this._tasks = new Array();
  26720. this._waitingTasksCount = 0;
  26721. this.useDefaultLoadingScreen = true;
  26722. this._scene = scene;
  26723. }
  26724. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  26725. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  26726. this._tasks.push(task);
  26727. return task;
  26728. };
  26729. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  26730. var task = new TextFileAssetTask(taskName, url);
  26731. this._tasks.push(task);
  26732. return task;
  26733. };
  26734. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  26735. var task = new BinaryFileAssetTask(taskName, url);
  26736. this._tasks.push(task);
  26737. return task;
  26738. };
  26739. AssetsManager.prototype.addImageTask = function (taskName, url) {
  26740. var task = new ImageAssetTask(taskName, url);
  26741. this._tasks.push(task);
  26742. return task;
  26743. };
  26744. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  26745. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26746. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  26747. this._tasks.push(task);
  26748. return task;
  26749. };
  26750. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  26751. this._waitingTasksCount--;
  26752. if (this._waitingTasksCount === 0) {
  26753. if (this.onFinish) {
  26754. this.onFinish(this._tasks);
  26755. }
  26756. this._scene.getEngine().hideLoadingUI();
  26757. }
  26758. };
  26759. AssetsManager.prototype._runTask = function (task) {
  26760. var _this = this;
  26761. task.run(this._scene, function () {
  26762. if (_this.onTaskSuccess) {
  26763. _this.onTaskSuccess(task);
  26764. }
  26765. _this._decreaseWaitingTasksCount();
  26766. }, function () {
  26767. if (_this.onTaskError) {
  26768. _this.onTaskError(task);
  26769. }
  26770. _this._decreaseWaitingTasksCount();
  26771. });
  26772. };
  26773. AssetsManager.prototype.reset = function () {
  26774. this._tasks = new Array();
  26775. return this;
  26776. };
  26777. AssetsManager.prototype.load = function () {
  26778. this._waitingTasksCount = this._tasks.length;
  26779. if (this._waitingTasksCount === 0) {
  26780. if (this.onFinish) {
  26781. this.onFinish(this._tasks);
  26782. }
  26783. return this;
  26784. }
  26785. if (this.useDefaultLoadingScreen) {
  26786. this._scene.getEngine().displayLoadingUI();
  26787. }
  26788. for (var index = 0; index < this._tasks.length; index++) {
  26789. var task = this._tasks[index];
  26790. this._runTask(task);
  26791. }
  26792. return this;
  26793. };
  26794. return AssetsManager;
  26795. })();
  26796. BABYLON.AssetsManager = AssetsManager;
  26797. })(BABYLON || (BABYLON = {}));
  26798. //# sourceMappingURL=babylon.assetsManager.js.map
  26799. var BABYLON;
  26800. (function (BABYLON) {
  26801. var VRDeviceOrientationCamera = (function (_super) {
  26802. __extends(VRDeviceOrientationCamera, _super);
  26803. function VRDeviceOrientationCamera(name, position, scene) {
  26804. _super.call(this, name, position, scene);
  26805. this._alpha = 0;
  26806. this._beta = 0;
  26807. this._gamma = 0;
  26808. }
  26809. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  26810. this._alpha = +evt.alpha | 0;
  26811. this._beta = +evt.beta | 0;
  26812. this._gamma = +evt.gamma | 0;
  26813. if (this._gamma < 0) {
  26814. this._gamma = 90 + this._gamma;
  26815. }
  26816. else {
  26817. // Incline it in the correct angle.
  26818. this._gamma = 270 - this._gamma;
  26819. }
  26820. this.rotation.x = this._gamma / 180.0 * Math.PI;
  26821. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  26822. this.rotation.z = this._beta / 180.0 * Math.PI;
  26823. };
  26824. return VRDeviceOrientationCamera;
  26825. })(BABYLON.OculusCamera);
  26826. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  26827. })(BABYLON || (BABYLON = {}));
  26828. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  26829. var BABYLON;
  26830. (function (BABYLON) {
  26831. var WebVRCamera = (function (_super) {
  26832. __extends(WebVRCamera, _super);
  26833. function WebVRCamera(name, position, scene) {
  26834. _super.call(this, name, position, scene);
  26835. this._hmdDevice = null;
  26836. this._sensorDevice = null;
  26837. this._cacheState = null;
  26838. this._cacheQuaternion = new BABYLON.Quaternion();
  26839. this._cacheRotation = BABYLON.Vector3.Zero();
  26840. this._vrEnabled = false;
  26841. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  26842. }
  26843. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  26844. var size = devices.length;
  26845. var i = 0;
  26846. // Reset devices.
  26847. this._sensorDevice = null;
  26848. this._hmdDevice = null;
  26849. while (i < size && this._hmdDevice === null) {
  26850. if (devices[i] instanceof HMDVRDevice) {
  26851. this._hmdDevice = devices[i];
  26852. }
  26853. i++;
  26854. }
  26855. i = 0;
  26856. while (i < size && this._sensorDevice === null) {
  26857. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  26858. this._sensorDevice = devices[i];
  26859. }
  26860. i++;
  26861. }
  26862. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  26863. };
  26864. WebVRCamera.prototype._update = function () {
  26865. if (this._vrEnabled) {
  26866. this._cacheState = this._sensorDevice.getState();
  26867. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  26868. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  26869. this.rotation.x = -this._cacheRotation.z;
  26870. this.rotation.y = -this._cacheRotation.y;
  26871. this.rotation.z = this._cacheRotation.x;
  26872. }
  26873. _super.prototype._update.call(this);
  26874. };
  26875. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  26876. _super.prototype.attachControl.call(this, element, noPreventDefault);
  26877. if (navigator.getVRDevices) {
  26878. navigator.getVRDevices().then(this._getWebVRDevices);
  26879. }
  26880. else if (navigator.mozGetVRDevices) {
  26881. navigator.mozGetVRDevices(this._getWebVRDevices);
  26882. }
  26883. };
  26884. WebVRCamera.prototype.detachControl = function (element) {
  26885. _super.prototype.detachControl.call(this, element);
  26886. this._vrEnabled = false;
  26887. };
  26888. return WebVRCamera;
  26889. })(BABYLON.OculusCamera);
  26890. BABYLON.WebVRCamera = WebVRCamera;
  26891. })(BABYLON || (BABYLON = {}));
  26892. //# sourceMappingURL=babylon.webVRCamera.js.map
  26893. var BABYLON;
  26894. (function (BABYLON) {
  26895. // Standard optimizations
  26896. var SceneOptimization = (function () {
  26897. function SceneOptimization(priority) {
  26898. if (priority === void 0) { priority = 0; }
  26899. this.priority = priority;
  26900. this.apply = function (scene) {
  26901. return true; // Return true if everything that can be done was applied
  26902. };
  26903. }
  26904. return SceneOptimization;
  26905. })();
  26906. BABYLON.SceneOptimization = SceneOptimization;
  26907. var TextureOptimization = (function (_super) {
  26908. __extends(TextureOptimization, _super);
  26909. function TextureOptimization(priority, maximumSize) {
  26910. var _this = this;
  26911. if (priority === void 0) { priority = 0; }
  26912. if (maximumSize === void 0) { maximumSize = 1024; }
  26913. _super.call(this, priority);
  26914. this.priority = priority;
  26915. this.maximumSize = maximumSize;
  26916. this.apply = function (scene) {
  26917. var allDone = true;
  26918. for (var index = 0; index < scene.textures.length; index++) {
  26919. var texture = scene.textures[index];
  26920. if (!texture.canRescale) {
  26921. continue;
  26922. }
  26923. var currentSize = texture.getSize();
  26924. var maxDimension = Math.max(currentSize.width, currentSize.height);
  26925. if (maxDimension > _this.maximumSize) {
  26926. texture.scale(0.5);
  26927. allDone = false;
  26928. }
  26929. }
  26930. return allDone;
  26931. };
  26932. }
  26933. return TextureOptimization;
  26934. })(SceneOptimization);
  26935. BABYLON.TextureOptimization = TextureOptimization;
  26936. var HardwareScalingOptimization = (function (_super) {
  26937. __extends(HardwareScalingOptimization, _super);
  26938. function HardwareScalingOptimization(priority, maximumScale) {
  26939. var _this = this;
  26940. if (priority === void 0) { priority = 0; }
  26941. if (maximumScale === void 0) { maximumScale = 2; }
  26942. _super.call(this, priority);
  26943. this.priority = priority;
  26944. this.maximumScale = maximumScale;
  26945. this._currentScale = 1;
  26946. this.apply = function (scene) {
  26947. _this._currentScale++;
  26948. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  26949. return _this._currentScale >= _this.maximumScale;
  26950. };
  26951. }
  26952. return HardwareScalingOptimization;
  26953. })(SceneOptimization);
  26954. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  26955. var ShadowsOptimization = (function (_super) {
  26956. __extends(ShadowsOptimization, _super);
  26957. function ShadowsOptimization() {
  26958. _super.apply(this, arguments);
  26959. this.apply = function (scene) {
  26960. scene.shadowsEnabled = false;
  26961. return true;
  26962. };
  26963. }
  26964. return ShadowsOptimization;
  26965. })(SceneOptimization);
  26966. BABYLON.ShadowsOptimization = ShadowsOptimization;
  26967. var PostProcessesOptimization = (function (_super) {
  26968. __extends(PostProcessesOptimization, _super);
  26969. function PostProcessesOptimization() {
  26970. _super.apply(this, arguments);
  26971. this.apply = function (scene) {
  26972. scene.postProcessesEnabled = false;
  26973. return true;
  26974. };
  26975. }
  26976. return PostProcessesOptimization;
  26977. })(SceneOptimization);
  26978. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  26979. var LensFlaresOptimization = (function (_super) {
  26980. __extends(LensFlaresOptimization, _super);
  26981. function LensFlaresOptimization() {
  26982. _super.apply(this, arguments);
  26983. this.apply = function (scene) {
  26984. scene.lensFlaresEnabled = false;
  26985. return true;
  26986. };
  26987. }
  26988. return LensFlaresOptimization;
  26989. })(SceneOptimization);
  26990. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  26991. var ParticlesOptimization = (function (_super) {
  26992. __extends(ParticlesOptimization, _super);
  26993. function ParticlesOptimization() {
  26994. _super.apply(this, arguments);
  26995. this.apply = function (scene) {
  26996. scene.particlesEnabled = false;
  26997. return true;
  26998. };
  26999. }
  27000. return ParticlesOptimization;
  27001. })(SceneOptimization);
  27002. BABYLON.ParticlesOptimization = ParticlesOptimization;
  27003. var RenderTargetsOptimization = (function (_super) {
  27004. __extends(RenderTargetsOptimization, _super);
  27005. function RenderTargetsOptimization() {
  27006. _super.apply(this, arguments);
  27007. this.apply = function (scene) {
  27008. scene.renderTargetsEnabled = false;
  27009. return true;
  27010. };
  27011. }
  27012. return RenderTargetsOptimization;
  27013. })(SceneOptimization);
  27014. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  27015. var MergeMeshesOptimization = (function (_super) {
  27016. __extends(MergeMeshesOptimization, _super);
  27017. function MergeMeshesOptimization() {
  27018. var _this = this;
  27019. _super.apply(this, arguments);
  27020. this._canBeMerged = function (abstractMesh) {
  27021. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  27022. return false;
  27023. }
  27024. var mesh = abstractMesh;
  27025. if (!mesh.isVisible || !mesh.isEnabled()) {
  27026. return false;
  27027. }
  27028. if (mesh.instances.length > 0) {
  27029. return false;
  27030. }
  27031. if (mesh.skeleton || mesh.hasLODLevels) {
  27032. return false;
  27033. }
  27034. return true;
  27035. };
  27036. this.apply = function (scene) {
  27037. var globalPool = scene.meshes.slice(0);
  27038. var globalLength = globalPool.length;
  27039. for (var index = 0; index < globalLength; index++) {
  27040. var currentPool = new Array();
  27041. var current = globalPool[index];
  27042. // Checks
  27043. if (!_this._canBeMerged(current)) {
  27044. continue;
  27045. }
  27046. currentPool.push(current);
  27047. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  27048. var otherMesh = globalPool[subIndex];
  27049. if (!_this._canBeMerged(otherMesh)) {
  27050. continue;
  27051. }
  27052. if (otherMesh.material !== current.material) {
  27053. continue;
  27054. }
  27055. if (otherMesh.checkCollisions !== current.checkCollisions) {
  27056. continue;
  27057. }
  27058. currentPool.push(otherMesh);
  27059. globalLength--;
  27060. globalPool.splice(subIndex, 1);
  27061. subIndex--;
  27062. }
  27063. if (currentPool.length < 2) {
  27064. continue;
  27065. }
  27066. // Merge meshes
  27067. BABYLON.Mesh.MergeMeshes(currentPool);
  27068. }
  27069. return true;
  27070. };
  27071. }
  27072. return MergeMeshesOptimization;
  27073. })(SceneOptimization);
  27074. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  27075. // Options
  27076. var SceneOptimizerOptions = (function () {
  27077. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  27078. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  27079. if (trackerDuration === void 0) { trackerDuration = 2000; }
  27080. this.targetFrameRate = targetFrameRate;
  27081. this.trackerDuration = trackerDuration;
  27082. this.optimizations = new Array();
  27083. }
  27084. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  27085. var result = new SceneOptimizerOptions(targetFrameRate);
  27086. var priority = 0;
  27087. result.optimizations.push(new MergeMeshesOptimization(priority));
  27088. result.optimizations.push(new ShadowsOptimization(priority));
  27089. result.optimizations.push(new LensFlaresOptimization(priority));
  27090. // Next priority
  27091. priority++;
  27092. result.optimizations.push(new PostProcessesOptimization(priority));
  27093. result.optimizations.push(new ParticlesOptimization(priority));
  27094. // Next priority
  27095. priority++;
  27096. result.optimizations.push(new TextureOptimization(priority, 1024));
  27097. return result;
  27098. };
  27099. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  27100. var result = new SceneOptimizerOptions(targetFrameRate);
  27101. var priority = 0;
  27102. result.optimizations.push(new MergeMeshesOptimization(priority));
  27103. result.optimizations.push(new ShadowsOptimization(priority));
  27104. result.optimizations.push(new LensFlaresOptimization(priority));
  27105. // Next priority
  27106. priority++;
  27107. result.optimizations.push(new PostProcessesOptimization(priority));
  27108. result.optimizations.push(new ParticlesOptimization(priority));
  27109. // Next priority
  27110. priority++;
  27111. result.optimizations.push(new TextureOptimization(priority, 512));
  27112. // Next priority
  27113. priority++;
  27114. result.optimizations.push(new RenderTargetsOptimization(priority));
  27115. // Next priority
  27116. priority++;
  27117. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  27118. return result;
  27119. };
  27120. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  27121. var result = new SceneOptimizerOptions(targetFrameRate);
  27122. var priority = 0;
  27123. result.optimizations.push(new MergeMeshesOptimization(priority));
  27124. result.optimizations.push(new ShadowsOptimization(priority));
  27125. result.optimizations.push(new LensFlaresOptimization(priority));
  27126. // Next priority
  27127. priority++;
  27128. result.optimizations.push(new PostProcessesOptimization(priority));
  27129. result.optimizations.push(new ParticlesOptimization(priority));
  27130. // Next priority
  27131. priority++;
  27132. result.optimizations.push(new TextureOptimization(priority, 256));
  27133. // Next priority
  27134. priority++;
  27135. result.optimizations.push(new RenderTargetsOptimization(priority));
  27136. // Next priority
  27137. priority++;
  27138. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  27139. return result;
  27140. };
  27141. return SceneOptimizerOptions;
  27142. })();
  27143. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  27144. // Scene optimizer tool
  27145. var SceneOptimizer = (function () {
  27146. function SceneOptimizer() {
  27147. }
  27148. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  27149. // TODO: add an epsilon
  27150. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  27151. if (onSuccess) {
  27152. onSuccess();
  27153. }
  27154. return;
  27155. }
  27156. // Apply current level of optimizations
  27157. var allDone = true;
  27158. var noOptimizationApplied = true;
  27159. for (var index = 0; index < options.optimizations.length; index++) {
  27160. var optimization = options.optimizations[index];
  27161. if (optimization.priority === currentPriorityLevel) {
  27162. noOptimizationApplied = false;
  27163. allDone = allDone && optimization.apply(scene);
  27164. }
  27165. }
  27166. // If no optimization was applied, this is a failure :(
  27167. if (noOptimizationApplied) {
  27168. if (onFailure) {
  27169. onFailure();
  27170. }
  27171. return;
  27172. }
  27173. // If all optimizations were done, move to next level
  27174. if (allDone) {
  27175. currentPriorityLevel++;
  27176. }
  27177. // Let's the system running for a specific amount of time before checking FPS
  27178. scene.executeWhenReady(function () {
  27179. setTimeout(function () {
  27180. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  27181. }, options.trackerDuration);
  27182. });
  27183. };
  27184. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  27185. if (!options) {
  27186. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  27187. }
  27188. // Let's the system running for a specific amount of time before checking FPS
  27189. scene.executeWhenReady(function () {
  27190. setTimeout(function () {
  27191. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  27192. }, options.trackerDuration);
  27193. });
  27194. };
  27195. return SceneOptimizer;
  27196. })();
  27197. BABYLON.SceneOptimizer = SceneOptimizer;
  27198. })(BABYLON || (BABYLON = {}));
  27199. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  27200. (function (BABYLON) {
  27201. var Internals;
  27202. (function (Internals) {
  27203. var MeshLODLevel = (function () {
  27204. function MeshLODLevel(distance, mesh) {
  27205. this.distance = distance;
  27206. this.mesh = mesh;
  27207. }
  27208. return MeshLODLevel;
  27209. })();
  27210. Internals.MeshLODLevel = MeshLODLevel;
  27211. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27212. })(BABYLON || (BABYLON = {}));
  27213. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  27214. (function (BABYLON) {
  27215. var AudioEngine = (function () {
  27216. function AudioEngine() {
  27217. this.audioContext = null;
  27218. this.canUseWebAudio = false;
  27219. this.WarnedWebAudioUnsupported = false;
  27220. try {
  27221. if (typeof AudioContext !== 'undefined') {
  27222. this.audioContext = new AudioContext();
  27223. this.canUseWebAudio = true;
  27224. }
  27225. else if (typeof webkitAudioContext !== 'undefined') {
  27226. this.audioContext = new webkitAudioContext();
  27227. this.canUseWebAudio = true;
  27228. }
  27229. }
  27230. catch (e) {
  27231. this.canUseWebAudio = false;
  27232. BABYLON.Tools.Error("Web Audio: " + e.message);
  27233. }
  27234. // create a global volume gain node
  27235. if (this.canUseWebAudio) {
  27236. this.masterGain = this.audioContext.createGain();
  27237. this.masterGain.gain.value = 1;
  27238. this.masterGain.connect(this.audioContext.destination);
  27239. }
  27240. }
  27241. AudioEngine.prototype.dispose = function () {
  27242. if (this.canUseWebAudio) {
  27243. if (this._connectedAnalyser) {
  27244. this._connectedAnalyser.stopDebugCanvas();
  27245. this._connectedAnalyser.dispose();
  27246. this.masterGain.disconnect();
  27247. this.masterGain.connect(this.audioContext.destination);
  27248. this._connectedAnalyser = null;
  27249. }
  27250. this.masterGain.gain.value = 1;
  27251. }
  27252. this.WarnedWebAudioUnsupported = false;
  27253. };
  27254. AudioEngine.prototype.getGlobalVolume = function () {
  27255. if (this.canUseWebAudio) {
  27256. return this.masterGain.gain.value;
  27257. }
  27258. else {
  27259. return -1;
  27260. }
  27261. };
  27262. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  27263. if (this.canUseWebAudio) {
  27264. this.masterGain.gain.value = newVolume;
  27265. }
  27266. };
  27267. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  27268. if (this._connectedAnalyser) {
  27269. this._connectedAnalyser.stopDebugCanvas();
  27270. }
  27271. this._connectedAnalyser = analyser;
  27272. if (this.canUseWebAudio) {
  27273. this.masterGain.disconnect();
  27274. this._connectedAnalyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  27275. }
  27276. };
  27277. return AudioEngine;
  27278. })();
  27279. BABYLON.AudioEngine = AudioEngine;
  27280. })(BABYLON || (BABYLON = {}));
  27281. //# sourceMappingURL=babylon.audioEngine.js.mapvar BABYLON;
  27282. (function (BABYLON) {
  27283. var Sound = (function () {
  27284. /**
  27285. * Create a sound and attach it to a scene
  27286. * @param name Name of your sound
  27287. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  27288. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  27289. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  27290. */
  27291. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  27292. var _this = this;
  27293. this.autoplay = false;
  27294. this.loop = false;
  27295. this.useCustomAttenuation = false;
  27296. this.spatialSound = false;
  27297. this.refDistance = 1;
  27298. this.rolloffFactor = 1;
  27299. this.maxDistance = 100;
  27300. this.distanceModel = "linear";
  27301. this._panningModel = "equalpower";
  27302. this._playbackRate = 1;
  27303. this._startTime = 0;
  27304. this._startOffset = 0;
  27305. this._position = BABYLON.Vector3.Zero();
  27306. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  27307. this._volume = 1;
  27308. this._isLoaded = false;
  27309. this._isReadyToPlay = false;
  27310. this.isPlaying = false;
  27311. this.isPaused = false;
  27312. this._isDirectional = false;
  27313. // Used if you'd like to create a directional sound.
  27314. // If not set, the sound will be omnidirectional
  27315. this._coneInnerAngle = 360;
  27316. this._coneOuterAngle = 360;
  27317. this._coneOuterGain = 0;
  27318. this.name = name;
  27319. this._scene = scene;
  27320. this._readyToPlayCallback = readyToPlayCallback;
  27321. // Default custom attenuation function is a linear attenuation
  27322. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  27323. if (currentDistance < maxDistance) {
  27324. return currentVolume * (1 - currentDistance / maxDistance);
  27325. }
  27326. else {
  27327. return 0;
  27328. }
  27329. };
  27330. if (options) {
  27331. this.autoplay = options.autoplay || false;
  27332. this.loop = options.loop || false;
  27333. // if volume === 0, we need another way to check this option
  27334. if (options.volume !== undefined) {
  27335. this._volume = options.volume;
  27336. }
  27337. this.spatialSound = options.spatialSound || false;
  27338. this.maxDistance = options.maxDistance || 100;
  27339. this.useCustomAttenuation = options.useCustomAttenuation || false;
  27340. this.rolloffFactor = options.rolloffFactor || 1;
  27341. this.refDistance = options.refDistance || 1;
  27342. this.distanceModel = options.distanceModel || "linear";
  27343. this._playbackRate = options.playbackRate || 1;
  27344. }
  27345. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27346. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  27347. this._soundGain.gain.value = this._volume;
  27348. this._inputAudioNode = this._soundGain;
  27349. this._ouputAudioNode = this._soundGain;
  27350. if (this.spatialSound) {
  27351. this._createSpatialParameters();
  27352. }
  27353. this._scene.mainSoundTrack.AddSound(this);
  27354. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  27355. if (urlOrArrayBuffer) {
  27356. // If it's an URL
  27357. if (typeof (urlOrArrayBuffer) === "string") {
  27358. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  27359. _this._soundLoaded(data);
  27360. }, null, null, true);
  27361. }
  27362. else {
  27363. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  27364. this._soundLoaded(urlOrArrayBuffer);
  27365. }
  27366. else {
  27367. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  27368. }
  27369. }
  27370. }
  27371. }
  27372. else {
  27373. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  27374. this._scene.mainSoundTrack.AddSound(this);
  27375. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  27376. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  27377. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  27378. }
  27379. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  27380. if (this._readyToPlayCallback) {
  27381. window.setTimeout(function () {
  27382. _this._readyToPlayCallback();
  27383. }, 1000);
  27384. }
  27385. }
  27386. }
  27387. Sound.prototype.dispose = function () {
  27388. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  27389. if (this.isPlaying) {
  27390. this.stop();
  27391. }
  27392. this._isReadyToPlay = false;
  27393. if (this.soundTrackId === -1) {
  27394. this._scene.mainSoundTrack.RemoveSound(this);
  27395. }
  27396. else {
  27397. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  27398. }
  27399. if (this._soundGain) {
  27400. this._soundGain.disconnect();
  27401. this._soundGain = null;
  27402. }
  27403. if (this._soundPanner) {
  27404. this._soundPanner.disconnect();
  27405. this._soundPanner = null;
  27406. }
  27407. if (this._soundSource) {
  27408. this._soundSource.disconnect();
  27409. this._soundSource = null;
  27410. }
  27411. this._audioBuffer = null;
  27412. if (this._connectedMesh) {
  27413. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  27414. this._connectedMesh = null;
  27415. }
  27416. }
  27417. };
  27418. Sound.prototype._soundLoaded = function (audioData) {
  27419. var _this = this;
  27420. this._isLoaded = true;
  27421. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  27422. _this._audioBuffer = buffer;
  27423. _this._isReadyToPlay = true;
  27424. if (_this.autoplay) {
  27425. _this.play();
  27426. }
  27427. if (_this._readyToPlayCallback) {
  27428. _this._readyToPlayCallback();
  27429. }
  27430. }, function (error) {
  27431. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  27432. });
  27433. };
  27434. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  27435. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27436. this._audioBuffer = audioBuffer;
  27437. this._isReadyToPlay = true;
  27438. }
  27439. };
  27440. Sound.prototype.updateOptions = function (options) {
  27441. if (options) {
  27442. this.loop = options.loop || this.loop;
  27443. this.maxDistance = options.maxDistance || this.maxDistance;
  27444. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  27445. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  27446. this.refDistance = options.refDistance || this.refDistance;
  27447. this.distanceModel = options.distanceModel || this.distanceModel;
  27448. this._playbackRate = options.playbackRate || this._playbackRate;
  27449. }
  27450. };
  27451. Sound.prototype._createSpatialParameters = function () {
  27452. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27453. if (this._scene.headphone) {
  27454. this._panningModel = "HRTF";
  27455. }
  27456. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  27457. if (this.useCustomAttenuation) {
  27458. // Tricks to disable in a way embedded Web Audio attenuation
  27459. this._soundPanner.distanceModel = "linear";
  27460. this._soundPanner.maxDistance = Number.MAX_VALUE;
  27461. this._soundPanner.refDistance = 1;
  27462. this._soundPanner.rolloffFactor = 1;
  27463. this._soundPanner.panningModel = this._panningModel;
  27464. }
  27465. else {
  27466. this._soundPanner.distanceModel = this.distanceModel;
  27467. this._soundPanner.maxDistance = this.maxDistance;
  27468. this._soundPanner.refDistance = this.refDistance;
  27469. this._soundPanner.rolloffFactor = this.rolloffFactor;
  27470. this._soundPanner.panningModel = this._panningModel;
  27471. }
  27472. this._soundPanner.connect(this._ouputAudioNode);
  27473. this._inputAudioNode = this._soundPanner;
  27474. }
  27475. };
  27476. Sound.prototype.switchPanningModelToHRTF = function () {
  27477. this._panningModel = "HRTF";
  27478. this._switchPanningModel();
  27479. };
  27480. Sound.prototype.switchPanningModelToEqualPower = function () {
  27481. this._panningModel = "equalpower";
  27482. this._switchPanningModel();
  27483. };
  27484. Sound.prototype._switchPanningModel = function () {
  27485. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  27486. this._soundPanner.panningModel = this._panningModel;
  27487. }
  27488. };
  27489. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  27490. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27491. this._ouputAudioNode.disconnect();
  27492. this._ouputAudioNode.connect(soundTrackAudioNode);
  27493. }
  27494. };
  27495. /**
  27496. * Transform this sound into a directional source
  27497. * @param coneInnerAngle Size of the inner cone in degree
  27498. * @param coneOuterAngle Size of the outer cone in degree
  27499. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  27500. */
  27501. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  27502. if (coneOuterAngle < coneInnerAngle) {
  27503. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  27504. return;
  27505. }
  27506. this._coneInnerAngle = coneInnerAngle;
  27507. this._coneOuterAngle = coneOuterAngle;
  27508. this._coneOuterGain = coneOuterGain;
  27509. this._isDirectional = true;
  27510. if (this.isPlaying && this.loop) {
  27511. this.stop();
  27512. this.play();
  27513. }
  27514. };
  27515. Sound.prototype.setPosition = function (newPosition) {
  27516. this._position = newPosition;
  27517. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  27518. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  27519. }
  27520. };
  27521. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  27522. this._localDirection = newLocalDirection;
  27523. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  27524. this._updateDirection();
  27525. }
  27526. };
  27527. Sound.prototype._updateDirection = function () {
  27528. var mat = this._connectedMesh.getWorldMatrix();
  27529. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  27530. direction.normalize();
  27531. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  27532. };
  27533. Sound.prototype.updateDistanceFromListener = function () {
  27534. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  27535. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  27536. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  27537. }
  27538. };
  27539. Sound.prototype.setAttenuationFunction = function (callback) {
  27540. this._customAttenuationFunction = callback;
  27541. };
  27542. /**
  27543. * Play the sound
  27544. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  27545. */
  27546. Sound.prototype.play = function (time) {
  27547. var _this = this;
  27548. if (this._isReadyToPlay && this._scene.audioEnabled) {
  27549. try {
  27550. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  27551. if (!this._soundSource) {
  27552. if (this.spatialSound) {
  27553. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  27554. if (this._isDirectional) {
  27555. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  27556. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  27557. this._soundPanner.coneOuterGain = this._coneOuterGain;
  27558. if (this._connectedMesh) {
  27559. this._updateDirection();
  27560. }
  27561. else {
  27562. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  27563. }
  27564. }
  27565. }
  27566. }
  27567. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  27568. this._soundSource.buffer = this._audioBuffer;
  27569. this._soundSource.connect(this._inputAudioNode);
  27570. this._soundSource.loop = this.loop;
  27571. this._soundSource.playbackRate.value = this._playbackRate;
  27572. this._startTime = startTime;
  27573. this._soundSource.onended = function () {
  27574. _this._onended();
  27575. };
  27576. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  27577. this.isPlaying = true;
  27578. this.isPaused = false;
  27579. }
  27580. catch (ex) {
  27581. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  27582. }
  27583. }
  27584. };
  27585. Sound.prototype._onended = function () {
  27586. this.isPlaying = false;
  27587. if (this.onended) {
  27588. this.onended();
  27589. }
  27590. };
  27591. /**
  27592. * Stop the sound
  27593. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  27594. */
  27595. Sound.prototype.stop = function (time) {
  27596. if (this.isPlaying) {
  27597. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  27598. this._soundSource.stop(stopTime);
  27599. this.isPlaying = false;
  27600. }
  27601. };
  27602. Sound.prototype.pause = function () {
  27603. if (this.isPlaying) {
  27604. this.stop(0);
  27605. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  27606. this.isPaused = true;
  27607. }
  27608. };
  27609. Sound.prototype.setVolume = function (newVolume, time) {
  27610. if (BABYLON.Engine.audioEngine.canUseWebAudio && !this.spatialSound) {
  27611. if (time) {
  27612. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  27613. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  27614. }
  27615. else {
  27616. this._soundGain.gain.value = newVolume;
  27617. }
  27618. }
  27619. this._volume = newVolume;
  27620. };
  27621. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  27622. this._playbackRate = newPlaybackRate;
  27623. if (this.isPlaying) {
  27624. this._soundSource.playbackRate.value = this._playbackRate;
  27625. }
  27626. };
  27627. Sound.prototype.getVolume = function () {
  27628. return this._volume;
  27629. };
  27630. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  27631. var _this = this;
  27632. this._connectedMesh = meshToConnectTo;
  27633. if (!this.spatialSound) {
  27634. this._createSpatialParameters();
  27635. this.spatialSound = true;
  27636. if (this.isPlaying && this.loop) {
  27637. this.stop();
  27638. this.play();
  27639. }
  27640. }
  27641. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  27642. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  27643. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  27644. };
  27645. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  27646. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  27647. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  27648. this._updateDirection();
  27649. }
  27650. };
  27651. return Sound;
  27652. })();
  27653. BABYLON.Sound = Sound;
  27654. })(BABYLON || (BABYLON = {}));
  27655. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  27656. (function (BABYLON) {
  27657. var SoundTrack = (function () {
  27658. function SoundTrack(scene, options) {
  27659. this.id = -1;
  27660. this._isMainTrack = false;
  27661. this._scene = scene;
  27662. this._audioEngine = BABYLON.Engine.audioEngine;
  27663. this.soundCollection = new Array();
  27664. if (this._audioEngine.canUseWebAudio) {
  27665. this._trackGain = this._audioEngine.audioContext.createGain();
  27666. this._trackGain.connect(this._audioEngine.masterGain);
  27667. if (options) {
  27668. if (options.volume) {
  27669. this._trackGain.gain.value = options.volume;
  27670. }
  27671. if (options.mainTrack) {
  27672. this._isMainTrack = options.mainTrack;
  27673. }
  27674. }
  27675. }
  27676. if (!this._isMainTrack) {
  27677. this._scene.soundTracks.push(this);
  27678. this.id = this._scene.soundTracks.length - 1;
  27679. }
  27680. }
  27681. SoundTrack.prototype.dispose = function () {
  27682. if (this._audioEngine.canUseWebAudio) {
  27683. if (this._connectedAnalyser) {
  27684. this._connectedAnalyser.stopDebugCanvas();
  27685. }
  27686. while (this.soundCollection.length) {
  27687. this.soundCollection[0].dispose();
  27688. }
  27689. this._trackGain.disconnect();
  27690. this._trackGain = null;
  27691. }
  27692. };
  27693. SoundTrack.prototype.AddSound = function (sound) {
  27694. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27695. sound.connectToSoundTrackAudioNode(this._trackGain);
  27696. }
  27697. if (sound.soundTrackId) {
  27698. if (sound.soundTrackId === -1) {
  27699. this._scene.mainSoundTrack.RemoveSound(sound);
  27700. }
  27701. else {
  27702. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  27703. }
  27704. }
  27705. this.soundCollection.push(sound);
  27706. sound.soundTrackId = this.id;
  27707. };
  27708. SoundTrack.prototype.RemoveSound = function (sound) {
  27709. var index = this.soundCollection.indexOf(sound);
  27710. if (index !== -1) {
  27711. this.soundCollection.splice(index, 1);
  27712. }
  27713. };
  27714. SoundTrack.prototype.setVolume = function (newVolume) {
  27715. if (this._audioEngine.canUseWebAudio) {
  27716. this._trackGain.gain.value = newVolume;
  27717. }
  27718. };
  27719. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  27720. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27721. for (var i = 0; i < this.soundCollection.length; i++) {
  27722. this.soundCollection[i].switchPanningModelToHRTF();
  27723. }
  27724. }
  27725. };
  27726. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  27727. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27728. for (var i = 0; i < this.soundCollection.length; i++) {
  27729. this.soundCollection[i].switchPanningModelToEqualPower();
  27730. }
  27731. }
  27732. };
  27733. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  27734. if (this._connectedAnalyser) {
  27735. this._connectedAnalyser.stopDebugCanvas();
  27736. }
  27737. this._connectedAnalyser = analyser;
  27738. if (this._audioEngine.canUseWebAudio) {
  27739. this._trackGain.disconnect();
  27740. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  27741. }
  27742. };
  27743. return SoundTrack;
  27744. })();
  27745. BABYLON.SoundTrack = SoundTrack;
  27746. })(BABYLON || (BABYLON = {}));
  27747. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  27748. (function (BABYLON) {
  27749. var DebugLayer = (function () {
  27750. function DebugLayer(scene) {
  27751. var _this = this;
  27752. this._transformationMatrix = BABYLON.Matrix.Identity();
  27753. this._enabled = false;
  27754. this._labelsEnabled = false;
  27755. this._displayStatistics = true;
  27756. this._displayTree = false;
  27757. this._displayLogs = false;
  27758. this._identityMatrix = BABYLON.Matrix.Identity();
  27759. this.axisRatio = 0.02;
  27760. this.accentColor = "orange";
  27761. this._scene = scene;
  27762. this._syncPositions = function () {
  27763. var engine = _this._scene.getEngine();
  27764. var canvasRect = engine.getRenderingCanvasClientRect();
  27765. if (_this._showUI) {
  27766. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  27767. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  27768. _this._statsDiv.style.width = "400px";
  27769. _this._statsDiv.style.height = "auto";
  27770. _this._statsSubsetDiv.style.maxHeight = "240px";
  27771. _this._optionsDiv.style.left = "0px";
  27772. _this._optionsDiv.style.top = "10px";
  27773. _this._optionsDiv.style.width = "200px";
  27774. _this._optionsDiv.style.height = "auto";
  27775. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  27776. _this._logDiv.style.left = "0px";
  27777. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  27778. _this._logDiv.style.width = "600px";
  27779. _this._logDiv.style.height = "160px";
  27780. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  27781. _this._treeDiv.style.top = "10px";
  27782. _this._treeDiv.style.width = "300px";
  27783. _this._treeDiv.style.height = "auto";
  27784. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  27785. }
  27786. _this._globalDiv.style.left = canvasRect.left + "px";
  27787. _this._globalDiv.style.top = canvasRect.top + "px";
  27788. _this._drawingCanvas.style.left = "0px";
  27789. _this._drawingCanvas.style.top = "0px";
  27790. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  27791. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  27792. var devicePixelRatio = window.devicePixelRatio || 1;
  27793. var context = _this._drawingContext;
  27794. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  27795. _this._ratio = devicePixelRatio / backingStoreRatio;
  27796. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  27797. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  27798. };
  27799. this._onCanvasClick = function (evt) {
  27800. _this._clickPosition = {
  27801. x: evt.clientX * _this._ratio,
  27802. y: evt.clientY * _this._ratio
  27803. };
  27804. };
  27805. this._syncUI = function () {
  27806. if (_this._showUI) {
  27807. if (_this._displayStatistics) {
  27808. _this._displayStats();
  27809. _this._statsDiv.style.display = "";
  27810. }
  27811. else {
  27812. _this._statsDiv.style.display = "none";
  27813. }
  27814. if (_this._displayLogs) {
  27815. _this._logDiv.style.display = "";
  27816. }
  27817. else {
  27818. _this._logDiv.style.display = "none";
  27819. }
  27820. if (_this._displayTree) {
  27821. _this._treeDiv.style.display = "";
  27822. if (_this._needToRefreshMeshesTree) {
  27823. _this._needToRefreshMeshesTree = false;
  27824. _this._refreshMeshesTreeContent();
  27825. }
  27826. }
  27827. else {
  27828. _this._treeDiv.style.display = "none";
  27829. }
  27830. }
  27831. };
  27832. this._syncData = function () {
  27833. if (_this._labelsEnabled || !_this._showUI) {
  27834. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  27835. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  27836. var engine = _this._scene.getEngine();
  27837. var viewport = _this._camera.viewport;
  27838. var globalViewport = viewport.toGlobal(engine);
  27839. // Meshes
  27840. var meshes = _this._camera.getActiveMeshes();
  27841. for (var index = 0; index < meshes.length; index++) {
  27842. var mesh = meshes.data[index];
  27843. var position = mesh.getBoundingInfo().boundingSphere.center;
  27844. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27845. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  27846. _this._renderAxis(projectedPosition, mesh, globalViewport);
  27847. }
  27848. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  27849. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  27850. mesh.renderOverlay = !mesh.renderOverlay;
  27851. }, function () {
  27852. return mesh.renderOverlay ? 'red' : 'black';
  27853. });
  27854. }
  27855. }
  27856. // Cameras
  27857. var cameras = _this._scene.cameras;
  27858. for (index = 0; index < cameras.length; index++) {
  27859. var camera = cameras[index];
  27860. if (camera === _this._camera) {
  27861. continue;
  27862. }
  27863. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27864. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  27865. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  27866. _this._camera.detachControl(engine.getRenderingCanvas());
  27867. _this._camera = camera;
  27868. _this._camera.attachControl(engine.getRenderingCanvas());
  27869. }, function () {
  27870. return "purple";
  27871. });
  27872. }
  27873. }
  27874. // Lights
  27875. var lights = _this._scene.lights;
  27876. for (index = 0; index < lights.length; index++) {
  27877. var light = lights[index];
  27878. if (light.position) {
  27879. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  27880. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  27881. _this._renderLabel(light.name, projectedPosition, -20, function () {
  27882. light.setEnabled(!light.isEnabled());
  27883. }, function () {
  27884. return light.isEnabled() ? "orange" : "gray";
  27885. });
  27886. }
  27887. }
  27888. }
  27889. }
  27890. _this._clickPosition = undefined;
  27891. };
  27892. }
  27893. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  27894. while (this._treeSubsetDiv.hasChildNodes()) {
  27895. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  27896. }
  27897. // Add meshes
  27898. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  27899. sortedArray.sort(function (a, b) {
  27900. if (a.name === b.name) {
  27901. return 0;
  27902. }
  27903. return (a.name > b.name) ? 1 : -1;
  27904. });
  27905. for (var index = 0; index < sortedArray.length; index++) {
  27906. var mesh = sortedArray[index];
  27907. if (!mesh.isEnabled()) {
  27908. continue;
  27909. }
  27910. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  27911. m.isVisible = element.checked;
  27912. }, mesh);
  27913. }
  27914. };
  27915. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  27916. this._drawingContext.beginPath();
  27917. this._drawingContext.moveTo(zero.x, zero.y);
  27918. this._drawingContext.lineTo(unit.x, unit.y);
  27919. this._drawingContext.strokeStyle = color;
  27920. this._drawingContext.lineWidth = 4;
  27921. this._drawingContext.stroke();
  27922. this._drawingContext.font = "normal 14px Segoe UI";
  27923. this._drawingContext.fillStyle = color;
  27924. this._drawingContext.fillText(label, unitText.x, unitText.y);
  27925. };
  27926. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  27927. var position = mesh.getBoundingInfo().boundingSphere.center;
  27928. var worldMatrix = mesh.getWorldMatrix();
  27929. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  27930. var unit = (unprojectedVector.subtract(position)).length();
  27931. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27932. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27933. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  27934. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27935. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27936. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  27937. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  27938. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  27939. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  27940. };
  27941. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  27942. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  27943. this._drawingContext.font = "normal 12px Segoe UI";
  27944. var textMetrics = this._drawingContext.measureText(text);
  27945. var centerX = projectedPosition.x - textMetrics.width / 2;
  27946. var centerY = projectedPosition.y;
  27947. var clientRect = this._drawingCanvas.getBoundingClientRect();
  27948. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  27949. onClick();
  27950. }
  27951. this._drawingContext.beginPath();
  27952. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  27953. this._drawingContext.fillStyle = getFillStyle();
  27954. this._drawingContext.globalAlpha = 0.5;
  27955. this._drawingContext.fill();
  27956. this._drawingContext.globalAlpha = 1.0;
  27957. this._drawingContext.strokeStyle = '#FFFFFF';
  27958. this._drawingContext.lineWidth = 1;
  27959. this._drawingContext.stroke();
  27960. this._drawingContext.fillStyle = "#FFFFFF";
  27961. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  27962. this._drawingContext.beginPath();
  27963. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  27964. this._drawingContext.fill();
  27965. }
  27966. };
  27967. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  27968. if (!this._clickPosition) {
  27969. return false;
  27970. }
  27971. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  27972. return false;
  27973. }
  27974. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  27975. return false;
  27976. }
  27977. return true;
  27978. };
  27979. DebugLayer.prototype.isVisible = function () {
  27980. return this._enabled;
  27981. };
  27982. DebugLayer.prototype.hide = function () {
  27983. if (!this._enabled) {
  27984. return;
  27985. }
  27986. this._enabled = false;
  27987. var engine = this._scene.getEngine();
  27988. this._scene.unregisterBeforeRender(this._syncData);
  27989. this._scene.unregisterAfterRender(this._syncUI);
  27990. document.body.removeChild(this._globalDiv);
  27991. window.removeEventListener("resize", this._syncPositions);
  27992. this._scene.forceShowBoundingBoxes = false;
  27993. this._scene.forceWireframe = false;
  27994. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  27995. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  27996. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  27997. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  27998. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  27999. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  28000. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  28001. this._scene.shadowsEnabled = true;
  28002. this._scene.particlesEnabled = true;
  28003. this._scene.postProcessesEnabled = true;
  28004. this._scene.collisionsEnabled = true;
  28005. this._scene.lightsEnabled = true;
  28006. this._scene.texturesEnabled = true;
  28007. this._scene.lensFlaresEnabled = true;
  28008. this._scene.proceduralTexturesEnabled = true;
  28009. this._scene.renderTargetsEnabled = true;
  28010. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  28011. };
  28012. DebugLayer.prototype.show = function (showUI, camera) {
  28013. if (showUI === void 0) { showUI = true; }
  28014. if (camera === void 0) { camera = null; }
  28015. if (this._enabled) {
  28016. return;
  28017. }
  28018. this._enabled = true;
  28019. if (camera) {
  28020. this._camera = camera;
  28021. }
  28022. else {
  28023. this._camera = this._scene.activeCamera;
  28024. }
  28025. this._showUI = showUI;
  28026. var engine = this._scene.getEngine();
  28027. this._globalDiv = document.createElement("div");
  28028. document.body.appendChild(this._globalDiv);
  28029. this._generateDOMelements();
  28030. window.addEventListener("resize", this._syncPositions);
  28031. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  28032. this._syncPositions();
  28033. this._scene.registerBeforeRender(this._syncData);
  28034. this._scene.registerAfterRender(this._syncUI);
  28035. };
  28036. DebugLayer.prototype._clearLabels = function () {
  28037. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  28038. for (var index = 0; index < this._scene.meshes.length; index++) {
  28039. var mesh = this._scene.meshes[index];
  28040. mesh.renderOverlay = false;
  28041. }
  28042. };
  28043. DebugLayer.prototype._generateheader = function (root, text) {
  28044. var header = document.createElement("div");
  28045. header.innerHTML = text + "&nbsp;";
  28046. header.style.textAlign = "right";
  28047. header.style.width = "100%";
  28048. header.style.color = "white";
  28049. header.style.backgroundColor = "Black";
  28050. header.style.padding = "5px 5px 4px 0px";
  28051. header.style.marginLeft = "-5px";
  28052. header.style.fontWeight = "bold";
  28053. root.appendChild(header);
  28054. };
  28055. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  28056. var label = document.createElement("label");
  28057. label.innerHTML = title;
  28058. label.style.color = color;
  28059. root.appendChild(label);
  28060. root.appendChild(document.createElement("br"));
  28061. };
  28062. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  28063. if (tag === void 0) { tag = null; }
  28064. var label = document.createElement("label");
  28065. var boundingBoxesCheckbox = document.createElement("input");
  28066. boundingBoxesCheckbox.type = "checkbox";
  28067. boundingBoxesCheckbox.checked = initialState;
  28068. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  28069. task(evt.target, tag);
  28070. });
  28071. label.appendChild(boundingBoxesCheckbox);
  28072. var container = document.createElement("span");
  28073. var leftPart = document.createElement("span");
  28074. var rightPart = document.createElement("span");
  28075. rightPart.style.cssFloat = "right";
  28076. leftPart.innerHTML = leftTitle;
  28077. rightPart.innerHTML = rightTitle;
  28078. rightPart.style.fontSize = "12px";
  28079. rightPart.style.maxWidth = "200px";
  28080. container.appendChild(leftPart);
  28081. container.appendChild(rightPart);
  28082. label.appendChild(container);
  28083. root.appendChild(label);
  28084. root.appendChild(document.createElement("br"));
  28085. };
  28086. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  28087. if (tag === void 0) { tag = null; }
  28088. var label = document.createElement("label");
  28089. var checkBox = document.createElement("input");
  28090. checkBox.type = "checkbox";
  28091. checkBox.checked = initialState;
  28092. checkBox.addEventListener("change", function (evt) {
  28093. task(evt.target, tag);
  28094. });
  28095. label.appendChild(checkBox);
  28096. label.appendChild(document.createTextNode(title));
  28097. root.appendChild(label);
  28098. root.appendChild(document.createElement("br"));
  28099. };
  28100. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  28101. if (tag === void 0) { tag = null; }
  28102. var button = document.createElement("button");
  28103. button.innerHTML = title;
  28104. button.style.height = "24px";
  28105. button.style.color = "#444444";
  28106. button.style.border = "1px solid white";
  28107. button.className = "debugLayerButton";
  28108. button.addEventListener("click", function (evt) {
  28109. task(evt.target, tag);
  28110. });
  28111. root.appendChild(button);
  28112. root.appendChild(document.createElement("br"));
  28113. };
  28114. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  28115. if (tag === void 0) { tag = null; }
  28116. var label = document.createElement("label");
  28117. var boundingBoxesRadio = document.createElement("input");
  28118. boundingBoxesRadio.type = "radio";
  28119. boundingBoxesRadio.name = name;
  28120. boundingBoxesRadio.checked = initialState;
  28121. boundingBoxesRadio.addEventListener("change", function (evt) {
  28122. task(evt.target, tag);
  28123. });
  28124. label.appendChild(boundingBoxesRadio);
  28125. label.appendChild(document.createTextNode(title));
  28126. root.appendChild(label);
  28127. root.appendChild(document.createElement("br"));
  28128. };
  28129. DebugLayer.prototype._generateDOMelements = function () {
  28130. var _this = this;
  28131. this._globalDiv.id = "DebugLayer";
  28132. this._globalDiv.style.position = "absolute";
  28133. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  28134. this._globalDiv.style.fontSize = "14px";
  28135. this._globalDiv.style.color = "white";
  28136. // Drawing canvas
  28137. this._drawingCanvas = document.createElement("canvas");
  28138. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  28139. this._drawingCanvas.style.position = "absolute";
  28140. this._drawingCanvas.style.pointerEvents = "none";
  28141. this._drawingContext = this._drawingCanvas.getContext("2d");
  28142. this._globalDiv.appendChild(this._drawingCanvas);
  28143. if (this._showUI) {
  28144. var background = "rgba(128, 128, 128, 0.4)";
  28145. var border = "rgb(180, 180, 180) solid 1px";
  28146. // Stats
  28147. this._statsDiv = document.createElement("div");
  28148. this._statsDiv.id = "DebugLayerStats";
  28149. this._statsDiv.style.border = border;
  28150. this._statsDiv.style.position = "absolute";
  28151. this._statsDiv.style.background = background;
  28152. this._statsDiv.style.padding = "0px 0px 0px 5px";
  28153. this._generateheader(this._statsDiv, "STATISTICS");
  28154. this._statsSubsetDiv = document.createElement("div");
  28155. this._statsSubsetDiv.style.paddingTop = "5px";
  28156. this._statsSubsetDiv.style.paddingBottom = "5px";
  28157. this._statsSubsetDiv.style.overflowY = "auto";
  28158. this._statsDiv.appendChild(this._statsSubsetDiv);
  28159. // Tree
  28160. this._treeDiv = document.createElement("div");
  28161. this._treeDiv.id = "DebugLayerTree";
  28162. this._treeDiv.style.border = border;
  28163. this._treeDiv.style.position = "absolute";
  28164. this._treeDiv.style.background = background;
  28165. this._treeDiv.style.padding = "0px 0px 0px 5px";
  28166. this._treeDiv.style.display = "none";
  28167. this._generateheader(this._treeDiv, "MESHES TREE");
  28168. this._treeSubsetDiv = document.createElement("div");
  28169. this._treeSubsetDiv.style.paddingTop = "5px";
  28170. this._treeSubsetDiv.style.paddingRight = "5px";
  28171. this._treeSubsetDiv.style.overflowY = "auto";
  28172. this._treeSubsetDiv.style.maxHeight = "300px";
  28173. this._treeDiv.appendChild(this._treeSubsetDiv);
  28174. this._needToRefreshMeshesTree = true;
  28175. // Logs
  28176. this._logDiv = document.createElement("div");
  28177. this._logDiv.style.border = border;
  28178. this._logDiv.id = "DebugLayerLogs";
  28179. this._logDiv.style.position = "absolute";
  28180. this._logDiv.style.background = background;
  28181. this._logDiv.style.padding = "0px 0px 0px 5px";
  28182. this._logDiv.style.display = "none";
  28183. this._generateheader(this._logDiv, "LOGS");
  28184. this._logSubsetDiv = document.createElement("div");
  28185. this._logSubsetDiv.style.height = "127px";
  28186. this._logSubsetDiv.style.paddingTop = "5px";
  28187. this._logSubsetDiv.style.overflowY = "auto";
  28188. this._logSubsetDiv.style.fontSize = "12px";
  28189. this._logSubsetDiv.style.fontFamily = "consolas";
  28190. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  28191. this._logDiv.appendChild(this._logSubsetDiv);
  28192. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  28193. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  28194. };
  28195. // Options
  28196. this._optionsDiv = document.createElement("div");
  28197. this._optionsDiv.id = "DebugLayerOptions";
  28198. this._optionsDiv.style.border = border;
  28199. this._optionsDiv.style.position = "absolute";
  28200. this._optionsDiv.style.background = background;
  28201. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  28202. this._optionsDiv.style.overflowY = "auto";
  28203. this._generateheader(this._optionsDiv, "OPTIONS");
  28204. this._optionsSubsetDiv = document.createElement("div");
  28205. this._optionsSubsetDiv.style.paddingTop = "5px";
  28206. this._optionsSubsetDiv.style.paddingBottom = "5px";
  28207. this._optionsSubsetDiv.style.overflowY = "auto";
  28208. this._optionsSubsetDiv.style.maxHeight = "200px";
  28209. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  28210. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  28211. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  28212. _this._displayStatistics = element.checked;
  28213. });
  28214. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  28215. _this._displayLogs = element.checked;
  28216. });
  28217. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  28218. _this._displayTree = element.checked;
  28219. _this._needToRefreshMeshesTree = true;
  28220. });
  28221. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28222. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  28223. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  28224. _this._scene.forceShowBoundingBoxes = element.checked;
  28225. });
  28226. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  28227. _this._labelsEnabled = element.checked;
  28228. if (!_this._labelsEnabled) {
  28229. _this._clearLabels();
  28230. }
  28231. });
  28232. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  28233. if (element.checked) {
  28234. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  28235. }
  28236. else {
  28237. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  28238. }
  28239. });
  28240. ;
  28241. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28242. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  28243. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  28244. if (element.checked) {
  28245. _this._scene.forceWireframe = false;
  28246. _this._scene.forcePointsCloud = false;
  28247. }
  28248. });
  28249. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  28250. if (element.checked) {
  28251. _this._scene.forceWireframe = true;
  28252. _this._scene.forcePointsCloud = false;
  28253. }
  28254. });
  28255. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  28256. if (element.checked) {
  28257. _this._scene.forceWireframe = false;
  28258. _this._scene.forcePointsCloud = true;
  28259. }
  28260. });
  28261. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28262. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  28263. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  28264. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  28265. });
  28266. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  28267. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  28268. });
  28269. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  28270. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  28271. });
  28272. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  28273. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  28274. });
  28275. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  28276. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  28277. });
  28278. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  28279. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  28280. });
  28281. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  28282. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  28283. });
  28284. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  28285. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  28286. });
  28287. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28288. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  28289. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  28290. _this._scene.animationsEnabled = element.checked;
  28291. });
  28292. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  28293. _this._scene.collisionsEnabled = element.checked;
  28294. });
  28295. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  28296. _this._scene.fogEnabled = element.checked;
  28297. });
  28298. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  28299. _this._scene.lensFlaresEnabled = element.checked;
  28300. });
  28301. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  28302. _this._scene.lightsEnabled = element.checked;
  28303. });
  28304. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  28305. _this._scene.particlesEnabled = element.checked;
  28306. });
  28307. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  28308. _this._scene.postProcessesEnabled = element.checked;
  28309. });
  28310. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  28311. _this._scene.proceduralTexturesEnabled = element.checked;
  28312. });
  28313. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  28314. _this._scene.renderTargetsEnabled = element.checked;
  28315. });
  28316. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  28317. _this._scene.shadowsEnabled = element.checked;
  28318. });
  28319. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  28320. _this._scene.skeletonsEnabled = element.checked;
  28321. });
  28322. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) {
  28323. _this._scene.spritesEnabled = element.checked;
  28324. });
  28325. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  28326. _this._scene.texturesEnabled = element.checked;
  28327. });
  28328. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28329. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28330. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  28331. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  28332. if (element.checked) {
  28333. _this._scene.headphone = true;
  28334. }
  28335. });
  28336. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  28337. if (element.checked) {
  28338. _this._scene.headphone = false;
  28339. }
  28340. });
  28341. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  28342. _this._scene.audioEnabled = !element.checked;
  28343. });
  28344. }
  28345. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28346. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  28347. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) {
  28348. _this._scene.dumpNextRenderTargets = true;
  28349. });
  28350. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  28351. this._globalDiv.appendChild(this._statsDiv);
  28352. this._globalDiv.appendChild(this._logDiv);
  28353. this._globalDiv.appendChild(this._optionsDiv);
  28354. this._globalDiv.appendChild(this._treeDiv);
  28355. }
  28356. };
  28357. DebugLayer.prototype._displayStats = function () {
  28358. var scene = this._scene;
  28359. var engine = scene.getEngine();
  28360. var glInfo = engine.getGlInfo();
  28361. 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>";
  28362. if (this.customStatsFunction) {
  28363. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  28364. }
  28365. };
  28366. return DebugLayer;
  28367. })();
  28368. BABYLON.DebugLayer = DebugLayer;
  28369. })(BABYLON || (BABYLON = {}));
  28370. //# sourceMappingURL=babylon.debugLayer.js.map
  28371. var BABYLON;
  28372. (function (BABYLON) {
  28373. var RawTexture = (function (_super) {
  28374. __extends(RawTexture, _super);
  28375. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  28376. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28377. if (invertY === void 0) { invertY = false; }
  28378. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28379. _super.call(this, null, scene, !generateMipMaps, invertY);
  28380. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  28381. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28382. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28383. }
  28384. // Statics
  28385. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28386. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28387. if (invertY === void 0) { invertY = false; }
  28388. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28389. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  28390. };
  28391. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28392. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28393. if (invertY === void 0) { invertY = false; }
  28394. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28395. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  28396. };
  28397. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28398. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28399. if (invertY === void 0) { invertY = false; }
  28400. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28401. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  28402. };
  28403. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28404. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28405. if (invertY === void 0) { invertY = false; }
  28406. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28407. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  28408. };
  28409. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  28410. if (generateMipMaps === void 0) { generateMipMaps = true; }
  28411. if (invertY === void 0) { invertY = false; }
  28412. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28413. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  28414. };
  28415. return RawTexture;
  28416. })(BABYLON.Texture);
  28417. BABYLON.RawTexture = RawTexture;
  28418. })(BABYLON || (BABYLON = {}));
  28419. //# sourceMappingURL=babylon.rawTexture.js.map
  28420. var BABYLON;
  28421. (function (BABYLON) {
  28422. var IndexedVector2 = (function (_super) {
  28423. __extends(IndexedVector2, _super);
  28424. function IndexedVector2(original, index) {
  28425. _super.call(this, original.x, original.y);
  28426. this.index = index;
  28427. }
  28428. return IndexedVector2;
  28429. })(BABYLON.Vector2);
  28430. var PolygonPoints = (function () {
  28431. function PolygonPoints() {
  28432. this.elements = new Array();
  28433. }
  28434. PolygonPoints.prototype.add = function (originalPoints) {
  28435. var _this = this;
  28436. var result = new Array();
  28437. originalPoints.forEach(function (point) {
  28438. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  28439. var newPoint = new IndexedVector2(point, _this.elements.length);
  28440. result.push(newPoint);
  28441. _this.elements.push(newPoint);
  28442. }
  28443. });
  28444. return result;
  28445. };
  28446. PolygonPoints.prototype.computeBounds = function () {
  28447. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  28448. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  28449. this.elements.forEach(function (point) {
  28450. // x
  28451. if (point.x < lmin.x) {
  28452. lmin.x = point.x;
  28453. }
  28454. else if (point.x > lmax.x) {
  28455. lmax.x = point.x;
  28456. }
  28457. // y
  28458. if (point.y < lmin.y) {
  28459. lmin.y = point.y;
  28460. }
  28461. else if (point.y > lmax.y) {
  28462. lmax.y = point.y;
  28463. }
  28464. });
  28465. return {
  28466. min: lmin,
  28467. max: lmax,
  28468. width: lmax.x - lmin.x,
  28469. height: lmax.y - lmin.y
  28470. };
  28471. };
  28472. return PolygonPoints;
  28473. })();
  28474. var Polygon = (function () {
  28475. function Polygon() {
  28476. }
  28477. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  28478. return [
  28479. new BABYLON.Vector2(xmin, ymin),
  28480. new BABYLON.Vector2(xmax, ymin),
  28481. new BABYLON.Vector2(xmax, ymax),
  28482. new BABYLON.Vector2(xmin, ymax)
  28483. ];
  28484. };
  28485. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  28486. if (cx === void 0) { cx = 0; }
  28487. if (cy === void 0) { cy = 0; }
  28488. if (numberOfSides === void 0) { numberOfSides = 32; }
  28489. var result = new Array();
  28490. var angle = 0;
  28491. var increment = (Math.PI * 2) / numberOfSides;
  28492. for (var i = 0; i < numberOfSides; i++) {
  28493. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  28494. angle -= increment;
  28495. }
  28496. return result;
  28497. };
  28498. Polygon.Parse = function (input) {
  28499. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  28500. var i, result = [];
  28501. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  28502. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  28503. }
  28504. return result;
  28505. };
  28506. Polygon.StartingAt = function (x, y) {
  28507. return BABYLON.Path2.StartingAt(x, y);
  28508. };
  28509. return Polygon;
  28510. })();
  28511. BABYLON.Polygon = Polygon;
  28512. var PolygonMeshBuilder = (function () {
  28513. function PolygonMeshBuilder(name, contours, scene) {
  28514. this._points = new PolygonPoints();
  28515. if (!("poly2tri" in window)) {
  28516. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  28517. }
  28518. this._name = name;
  28519. this._scene = scene;
  28520. var points;
  28521. if (contours instanceof BABYLON.Path2) {
  28522. points = contours.getPoints();
  28523. }
  28524. else {
  28525. points = contours;
  28526. }
  28527. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  28528. }
  28529. PolygonMeshBuilder.prototype.addHole = function (hole) {
  28530. this._swctx.addHole(this._points.add(hole));
  28531. return this;
  28532. };
  28533. PolygonMeshBuilder.prototype.build = function (updatable) {
  28534. if (updatable === void 0) { updatable = false; }
  28535. var result = new BABYLON.Mesh(this._name, this._scene);
  28536. var normals = [];
  28537. var positions = [];
  28538. var uvs = [];
  28539. var bounds = this._points.computeBounds();
  28540. this._points.elements.forEach(function (p) {
  28541. normals.push(0, 1.0, 0);
  28542. positions.push(p.x, 0, p.y);
  28543. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  28544. });
  28545. var indices = [];
  28546. this._swctx.triangulate();
  28547. this._swctx.getTriangles().forEach(function (triangle) {
  28548. triangle.getPoints().forEach(function (point) {
  28549. indices.push(point.index);
  28550. });
  28551. });
  28552. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  28553. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  28554. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  28555. result.setIndices(indices);
  28556. return result;
  28557. };
  28558. return PolygonMeshBuilder;
  28559. })();
  28560. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  28561. })(BABYLON || (BABYLON = {}));
  28562. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  28563. (function (BABYLON) {
  28564. var SimplificationSettings = (function () {
  28565. function SimplificationSettings(quality, distance, optimizeMesh) {
  28566. this.quality = quality;
  28567. this.distance = distance;
  28568. this.optimizeMesh = optimizeMesh;
  28569. }
  28570. return SimplificationSettings;
  28571. })();
  28572. BABYLON.SimplificationSettings = SimplificationSettings;
  28573. var SimplificationQueue = (function () {
  28574. function SimplificationQueue() {
  28575. this.running = false;
  28576. this._simplificationArray = [];
  28577. }
  28578. SimplificationQueue.prototype.addTask = function (task) {
  28579. this._simplificationArray.push(task);
  28580. };
  28581. SimplificationQueue.prototype.executeNext = function () {
  28582. var task = this._simplificationArray.pop();
  28583. if (task) {
  28584. this.running = true;
  28585. this.runSimplification(task);
  28586. }
  28587. else {
  28588. this.running = false;
  28589. }
  28590. };
  28591. SimplificationQueue.prototype.runSimplification = function (task) {
  28592. var _this = this;
  28593. if (task.parallelProcessing) {
  28594. //parallel simplifier
  28595. task.settings.forEach(function (setting) {
  28596. var simplifier = _this.getSimplifier(task);
  28597. simplifier.simplify(setting, function (newMesh) {
  28598. task.mesh.addLODLevel(setting.distance, newMesh);
  28599. newMesh.isVisible = true;
  28600. //check if it is the last
  28601. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  28602. //all done, run the success callback.
  28603. task.successCallback();
  28604. }
  28605. _this.executeNext();
  28606. });
  28607. });
  28608. }
  28609. else {
  28610. //single simplifier.
  28611. var simplifier = this.getSimplifier(task);
  28612. var runDecimation = function (setting, callback) {
  28613. simplifier.simplify(setting, function (newMesh) {
  28614. task.mesh.addLODLevel(setting.distance, newMesh);
  28615. newMesh.isVisible = true;
  28616. //run the next quality level
  28617. callback();
  28618. });
  28619. };
  28620. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  28621. runDecimation(task.settings[loop.index], function () {
  28622. loop.executeNext();
  28623. });
  28624. }, function () {
  28625. //execution ended, run the success callback.
  28626. if (task.successCallback) {
  28627. task.successCallback();
  28628. }
  28629. _this.executeNext();
  28630. });
  28631. }
  28632. };
  28633. SimplificationQueue.prototype.getSimplifier = function (task) {
  28634. switch (task.simplificationType) {
  28635. case 0 /* QUADRATIC */:
  28636. default:
  28637. return new QuadraticErrorSimplification(task.mesh);
  28638. }
  28639. };
  28640. return SimplificationQueue;
  28641. })();
  28642. BABYLON.SimplificationQueue = SimplificationQueue;
  28643. /**
  28644. * The implemented types of simplification.
  28645. * At the moment only Quadratic Error Decimation is implemented.
  28646. */
  28647. (function (SimplificationType) {
  28648. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  28649. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  28650. var SimplificationType = BABYLON.SimplificationType;
  28651. var DecimationTriangle = (function () {
  28652. function DecimationTriangle(vertices) {
  28653. this.vertices = vertices;
  28654. this.error = new Array(4);
  28655. this.deleted = false;
  28656. this.isDirty = false;
  28657. this.deletePending = false;
  28658. this.borderFactor = 0;
  28659. }
  28660. return DecimationTriangle;
  28661. })();
  28662. BABYLON.DecimationTriangle = DecimationTriangle;
  28663. var DecimationVertex = (function () {
  28664. function DecimationVertex(position, id) {
  28665. this.position = position;
  28666. this.id = id;
  28667. this.isBorder = true;
  28668. this.q = new QuadraticMatrix();
  28669. this.triangleCount = 0;
  28670. this.triangleStart = 0;
  28671. this.originalOffsets = [];
  28672. }
  28673. DecimationVertex.prototype.updatePosition = function (newPosition) {
  28674. this.position.copyFrom(newPosition);
  28675. };
  28676. return DecimationVertex;
  28677. })();
  28678. BABYLON.DecimationVertex = DecimationVertex;
  28679. var QuadraticMatrix = (function () {
  28680. function QuadraticMatrix(data) {
  28681. this.data = new Array(10);
  28682. for (var i = 0; i < 10; ++i) {
  28683. if (data && data[i]) {
  28684. this.data[i] = data[i];
  28685. }
  28686. else {
  28687. this.data[i] = 0;
  28688. }
  28689. }
  28690. }
  28691. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  28692. 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];
  28693. return det;
  28694. };
  28695. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  28696. for (var i = 0; i < 10; ++i) {
  28697. this.data[i] += matrix.data[i];
  28698. }
  28699. };
  28700. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  28701. for (var i = 0; i < 10; ++i) {
  28702. this.data[i] += data[i];
  28703. }
  28704. };
  28705. QuadraticMatrix.prototype.add = function (matrix) {
  28706. var m = new QuadraticMatrix();
  28707. for (var i = 0; i < 10; ++i) {
  28708. m.data[i] = this.data[i] + matrix.data[i];
  28709. }
  28710. return m;
  28711. };
  28712. QuadraticMatrix.FromData = function (a, b, c, d) {
  28713. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  28714. };
  28715. //returning an array to avoid garbage collection
  28716. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  28717. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  28718. };
  28719. return QuadraticMatrix;
  28720. })();
  28721. BABYLON.QuadraticMatrix = QuadraticMatrix;
  28722. var Reference = (function () {
  28723. function Reference(vertexId, triangleId) {
  28724. this.vertexId = vertexId;
  28725. this.triangleId = triangleId;
  28726. }
  28727. return Reference;
  28728. })();
  28729. BABYLON.Reference = Reference;
  28730. /**
  28731. * An implementation of the Quadratic Error simplification algorithm.
  28732. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  28733. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  28734. * @author RaananW
  28735. */
  28736. var QuadraticErrorSimplification = (function () {
  28737. function QuadraticErrorSimplification(_mesh) {
  28738. this._mesh = _mesh;
  28739. this.initialized = false;
  28740. this.syncIterations = 5000;
  28741. this.aggressiveness = 7;
  28742. this.decimationIterations = 100;
  28743. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  28744. }
  28745. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  28746. var _this = this;
  28747. this.initDecimatedMesh();
  28748. //iterating through the submeshes array, one after the other.
  28749. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  28750. _this.initWithMesh(loop.index, function () {
  28751. _this.runDecimation(settings, loop.index, function () {
  28752. loop.executeNext();
  28753. });
  28754. }, settings.optimizeMesh);
  28755. }, function () {
  28756. setTimeout(function () {
  28757. successCallback(_this._reconstructedMesh);
  28758. }, 0);
  28759. });
  28760. };
  28761. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  28762. var _this = this;
  28763. var gCount = 0;
  28764. triangle.vertices.forEach(function (vertex) {
  28765. var count = 0;
  28766. var vPos = vertex.position;
  28767. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  28768. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  28769. ++count;
  28770. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  28771. ++count;
  28772. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  28773. ++count;
  28774. if (count > 1) {
  28775. ++gCount;
  28776. }
  28777. ;
  28778. });
  28779. if (gCount > 1) {
  28780. console.log(triangle, gCount);
  28781. }
  28782. return gCount > 1;
  28783. };
  28784. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  28785. var _this = this;
  28786. var targetCount = ~~(this.triangles.length * settings.quality);
  28787. var deletedTriangles = 0;
  28788. var triangleCount = this.triangles.length;
  28789. var iterationFunction = function (iteration, callback) {
  28790. setTimeout(function () {
  28791. if (iteration % 5 === 0) {
  28792. _this.updateMesh(iteration === 0);
  28793. }
  28794. for (var i = 0; i < _this.triangles.length; ++i) {
  28795. _this.triangles[i].isDirty = false;
  28796. }
  28797. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  28798. var trianglesIterator = function (i) {
  28799. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  28800. var t = _this.triangles[tIdx];
  28801. if (!t)
  28802. return;
  28803. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  28804. return;
  28805. }
  28806. for (var j = 0; j < 3; ++j) {
  28807. if (t.error[j] < threshold) {
  28808. var deleted0 = [];
  28809. var deleted1 = [];
  28810. var v0 = t.vertices[j];
  28811. var v1 = t.vertices[(j + 1) % 3];
  28812. if (v0.isBorder !== v1.isBorder)
  28813. continue;
  28814. var p = BABYLON.Vector3.Zero();
  28815. var n = BABYLON.Vector3.Zero();
  28816. var uv = BABYLON.Vector2.Zero();
  28817. var color = new BABYLON.Color4(0, 0, 0, 1);
  28818. _this.calculateError(v0, v1, p, n, uv, color);
  28819. var delTr = [];
  28820. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  28821. continue;
  28822. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  28823. continue;
  28824. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  28825. continue;
  28826. var uniqueArray = [];
  28827. delTr.forEach(function (deletedT) {
  28828. if (uniqueArray.indexOf(deletedT) === -1) {
  28829. deletedT.deletePending = true;
  28830. uniqueArray.push(deletedT);
  28831. }
  28832. });
  28833. if (uniqueArray.length % 2 != 0) {
  28834. continue;
  28835. }
  28836. v0.q = v1.q.add(v0.q);
  28837. v0.updatePosition(p);
  28838. var tStart = _this.references.length;
  28839. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  28840. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  28841. var tCount = _this.references.length - tStart;
  28842. if (tCount <= v0.triangleCount) {
  28843. if (tCount) {
  28844. for (var c = 0; c < tCount; c++) {
  28845. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  28846. }
  28847. }
  28848. }
  28849. else {
  28850. v0.triangleStart = tStart;
  28851. }
  28852. v0.triangleCount = tCount;
  28853. break;
  28854. }
  28855. }
  28856. };
  28857. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  28858. return (triangleCount - deletedTriangles <= targetCount);
  28859. });
  28860. }, 0);
  28861. };
  28862. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  28863. if (triangleCount - deletedTriangles <= targetCount)
  28864. loop.breakLoop();
  28865. else {
  28866. iterationFunction(loop.index, function () {
  28867. loop.executeNext();
  28868. });
  28869. }
  28870. }, function () {
  28871. setTimeout(function () {
  28872. //reconstruct this part of the mesh
  28873. _this.reconstructMesh(submeshIndex);
  28874. successCallback();
  28875. }, 0);
  28876. });
  28877. };
  28878. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  28879. var _this = this;
  28880. this.vertices = [];
  28881. this.triangles = [];
  28882. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28883. var indices = this._mesh.getIndices();
  28884. var submesh = this._mesh.subMeshes[submeshIndex];
  28885. var findInVertices = function (positionToSearch) {
  28886. if (optimizeMesh) {
  28887. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  28888. if (_this.vertices[ii].position.equals(positionToSearch)) {
  28889. return _this.vertices[ii];
  28890. }
  28891. }
  28892. }
  28893. return null;
  28894. };
  28895. var vertexReferences = [];
  28896. var vertexInit = function (i) {
  28897. var offset = i + submesh.verticesStart;
  28898. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  28899. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  28900. vertex.originalOffsets.push(offset);
  28901. if (vertex.id == _this.vertices.length) {
  28902. _this.vertices.push(vertex);
  28903. }
  28904. vertexReferences.push(vertex.id);
  28905. };
  28906. //var totalVertices = mesh.getTotalVertices();
  28907. var totalVertices = submesh.verticesCount;
  28908. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  28909. var indicesInit = function (i) {
  28910. var offset = (submesh.indexStart / 3) + i;
  28911. var pos = (offset * 3);
  28912. var i0 = indices[pos + 0];
  28913. var i1 = indices[pos + 1];
  28914. var i2 = indices[pos + 2];
  28915. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  28916. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  28917. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  28918. var triangle = new DecimationTriangle([v0, v1, v2]);
  28919. triangle.originalOffset = pos;
  28920. _this.triangles.push(triangle);
  28921. };
  28922. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  28923. _this.init(callback);
  28924. });
  28925. });
  28926. };
  28927. QuadraticErrorSimplification.prototype.init = function (callback) {
  28928. var _this = this;
  28929. var triangleInit1 = function (i) {
  28930. var t = _this.triangles[i];
  28931. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  28932. for (var j = 0; j < 3; j++) {
  28933. 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))));
  28934. }
  28935. };
  28936. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  28937. var triangleInit2 = function (i) {
  28938. var t = _this.triangles[i];
  28939. for (var j = 0; j < 3; ++j) {
  28940. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  28941. }
  28942. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28943. };
  28944. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  28945. _this.initialized = true;
  28946. callback();
  28947. });
  28948. });
  28949. };
  28950. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  28951. var newTriangles = [];
  28952. var i;
  28953. for (i = 0; i < this.vertices.length; ++i) {
  28954. this.vertices[i].triangleCount = 0;
  28955. }
  28956. var t;
  28957. var j;
  28958. for (i = 0; i < this.triangles.length; ++i) {
  28959. if (!this.triangles[i].deleted) {
  28960. t = this.triangles[i];
  28961. for (j = 0; j < 3; ++j) {
  28962. t.vertices[j].triangleCount = 1;
  28963. }
  28964. newTriangles.push(t);
  28965. }
  28966. }
  28967. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  28968. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  28969. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  28970. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  28971. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28972. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28973. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  28974. var vertexCount = 0;
  28975. for (i = 0; i < this.vertices.length; ++i) {
  28976. var vertex = this.vertices[i];
  28977. vertex.id = vertexCount;
  28978. if (vertex.triangleCount) {
  28979. vertex.originalOffsets.forEach(function (originalOffset) {
  28980. newPositionData.push(vertex.position.x);
  28981. newPositionData.push(vertex.position.y);
  28982. newPositionData.push(vertex.position.z);
  28983. newNormalData.push(normalData[originalOffset * 3]);
  28984. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  28985. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  28986. if (uvs && uvs.length) {
  28987. newUVsData.push(uvs[(originalOffset * 2)]);
  28988. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  28989. }
  28990. else if (colorsData && colorsData.length) {
  28991. newColorsData.push(colorsData[(originalOffset * 4)]);
  28992. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  28993. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  28994. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  28995. }
  28996. ++vertexCount;
  28997. });
  28998. }
  28999. }
  29000. var startingIndex = this._reconstructedMesh.getTotalIndices();
  29001. var startingVertex = this._reconstructedMesh.getTotalVertices();
  29002. var submeshesArray = this._reconstructedMesh.subMeshes;
  29003. this._reconstructedMesh.subMeshes = [];
  29004. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  29005. var originalIndices = this._mesh.getIndices();
  29006. for (i = 0; i < newTriangles.length; ++i) {
  29007. var t = newTriangles[i];
  29008. //now get the new referencing point for each vertex
  29009. [0, 1, 2].forEach(function (idx) {
  29010. var id = originalIndices[t.originalOffset + idx];
  29011. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  29012. if (offset < 0)
  29013. offset = 0;
  29014. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  29015. });
  29016. }
  29017. //overwriting the old vertex buffers and indices.
  29018. this._reconstructedMesh.setIndices(newIndicesArray);
  29019. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  29020. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  29021. if (newUVsData.length > 0)
  29022. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  29023. if (newColorsData.length > 0)
  29024. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  29025. //create submesh
  29026. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  29027. if (submeshIndex > 0) {
  29028. this._reconstructedMesh.subMeshes = [];
  29029. submeshesArray.forEach(function (submesh) {
  29030. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  29031. });
  29032. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  29033. }
  29034. };
  29035. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  29036. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  29037. this._reconstructedMesh.material = this._mesh.material;
  29038. this._reconstructedMesh.parent = this._mesh.parent;
  29039. this._reconstructedMesh.isVisible = false;
  29040. };
  29041. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  29042. for (var i = 0; i < vertex1.triangleCount; ++i) {
  29043. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  29044. if (t.deleted)
  29045. continue;
  29046. var s = this.references[vertex1.triangleStart + i].vertexId;
  29047. var v1 = t.vertices[(s + 1) % 3];
  29048. var v2 = t.vertices[(s + 2) % 3];
  29049. if ((v1 === vertex2 || v2 === vertex2)) {
  29050. deletedArray[i] = true;
  29051. delTr.push(t);
  29052. continue;
  29053. }
  29054. var d1 = v1.position.subtract(point);
  29055. d1 = d1.normalize();
  29056. var d2 = v2.position.subtract(point);
  29057. d2 = d2.normalize();
  29058. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  29059. return true;
  29060. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  29061. deletedArray[i] = false;
  29062. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  29063. return true;
  29064. }
  29065. return false;
  29066. };
  29067. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  29068. var newDeleted = deletedTriangles;
  29069. for (var i = 0; i < vertex.triangleCount; ++i) {
  29070. var ref = this.references[vertex.triangleStart + i];
  29071. var t = this.triangles[ref.triangleId];
  29072. if (t.deleted)
  29073. continue;
  29074. if (deletedArray[i] && t.deletePending) {
  29075. t.deleted = true;
  29076. newDeleted++;
  29077. continue;
  29078. }
  29079. t.vertices[ref.vertexId] = origVertex;
  29080. t.isDirty = true;
  29081. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  29082. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  29083. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  29084. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  29085. this.references.push(ref);
  29086. }
  29087. return newDeleted;
  29088. };
  29089. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  29090. for (var i = 0; i < this.vertices.length; ++i) {
  29091. var vCount = [];
  29092. var vId = [];
  29093. var v = this.vertices[i];
  29094. var j;
  29095. for (j = 0; j < v.triangleCount; ++j) {
  29096. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  29097. for (var ii = 0; ii < 3; ii++) {
  29098. var ofs = 0;
  29099. var vv = triangle.vertices[ii];
  29100. while (ofs < vCount.length) {
  29101. if (vId[ofs] === vv.id)
  29102. break;
  29103. ++ofs;
  29104. }
  29105. if (ofs === vCount.length) {
  29106. vCount.push(1);
  29107. vId.push(vv.id);
  29108. }
  29109. else {
  29110. vCount[ofs]++;
  29111. }
  29112. }
  29113. }
  29114. for (j = 0; j < vCount.length; ++j) {
  29115. if (vCount[j] === 1) {
  29116. this.vertices[vId[j]].isBorder = true;
  29117. }
  29118. else {
  29119. this.vertices[vId[j]].isBorder = false;
  29120. }
  29121. }
  29122. }
  29123. };
  29124. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  29125. if (identifyBorders === void 0) { identifyBorders = false; }
  29126. var i;
  29127. if (!identifyBorders) {
  29128. var newTrianglesVector = [];
  29129. for (i = 0; i < this.triangles.length; ++i) {
  29130. if (!this.triangles[i].deleted) {
  29131. newTrianglesVector.push(this.triangles[i]);
  29132. }
  29133. }
  29134. this.triangles = newTrianglesVector;
  29135. }
  29136. for (i = 0; i < this.vertices.length; ++i) {
  29137. this.vertices[i].triangleCount = 0;
  29138. this.vertices[i].triangleStart = 0;
  29139. }
  29140. var t;
  29141. var j;
  29142. var v;
  29143. for (i = 0; i < this.triangles.length; ++i) {
  29144. t = this.triangles[i];
  29145. for (j = 0; j < 3; ++j) {
  29146. v = t.vertices[j];
  29147. v.triangleCount++;
  29148. }
  29149. }
  29150. var tStart = 0;
  29151. for (i = 0; i < this.vertices.length; ++i) {
  29152. this.vertices[i].triangleStart = tStart;
  29153. tStart += this.vertices[i].triangleCount;
  29154. this.vertices[i].triangleCount = 0;
  29155. }
  29156. var newReferences = new Array(this.triangles.length * 3);
  29157. for (i = 0; i < this.triangles.length; ++i) {
  29158. t = this.triangles[i];
  29159. for (j = 0; j < 3; ++j) {
  29160. v = t.vertices[j];
  29161. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  29162. v.triangleCount++;
  29163. }
  29164. }
  29165. this.references = newReferences;
  29166. if (identifyBorders) {
  29167. this.identifyBorder();
  29168. }
  29169. };
  29170. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  29171. var x = point.x;
  29172. var y = point.y;
  29173. var z = point.z;
  29174. 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];
  29175. };
  29176. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  29177. var q = vertex1.q.add(vertex2.q);
  29178. var border = vertex1.isBorder && vertex2.isBorder;
  29179. var error = 0;
  29180. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  29181. if (qDet !== 0 && !border) {
  29182. if (!pointResult) {
  29183. pointResult = BABYLON.Vector3.Zero();
  29184. }
  29185. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  29186. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  29187. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  29188. error = this.vertexError(q, pointResult);
  29189. }
  29190. else {
  29191. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  29192. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  29193. var error1 = this.vertexError(q, vertex1.position);
  29194. var error2 = this.vertexError(q, vertex2.position);
  29195. var error3 = this.vertexError(q, p3);
  29196. error = Math.min(error1, error2, error3);
  29197. if (error === error1) {
  29198. if (pointResult) {
  29199. pointResult.copyFrom(vertex1.position);
  29200. }
  29201. }
  29202. else if (error === error2) {
  29203. if (pointResult) {
  29204. pointResult.copyFrom(vertex2.position);
  29205. }
  29206. }
  29207. else {
  29208. if (pointResult) {
  29209. pointResult.copyFrom(p3);
  29210. }
  29211. }
  29212. }
  29213. return error;
  29214. };
  29215. return QuadraticErrorSimplification;
  29216. })();
  29217. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  29218. })(BABYLON || (BABYLON = {}));
  29219. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  29220. (function (BABYLON) {
  29221. var Analyser = (function () {
  29222. function Analyser(scene) {
  29223. this.SMOOTHING = 0.75;
  29224. this.FFT_SIZE = 512;
  29225. this.BARGRAPHAMPLITUDE = 256;
  29226. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  29227. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  29228. this._scene = scene;
  29229. this._audioEngine = BABYLON.Engine.audioEngine;
  29230. if (this._audioEngine.canUseWebAudio) {
  29231. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  29232. this._webAudioAnalyser.minDecibels = -140;
  29233. this._webAudioAnalyser.maxDecibels = 0;
  29234. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  29235. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  29236. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  29237. }
  29238. }
  29239. Analyser.prototype.getFrequencyBinCount = function () {
  29240. if (this._audioEngine.canUseWebAudio) {
  29241. return this._webAudioAnalyser.frequencyBinCount;
  29242. }
  29243. else {
  29244. return 0;
  29245. }
  29246. };
  29247. Analyser.prototype.getByteFrequencyData = function () {
  29248. if (this._audioEngine.canUseWebAudio) {
  29249. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  29250. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  29251. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  29252. }
  29253. return this._byteFreqs;
  29254. };
  29255. Analyser.prototype.getByteTimeDomainData = function () {
  29256. if (this._audioEngine.canUseWebAudio) {
  29257. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  29258. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  29259. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  29260. }
  29261. return this._byteTime;
  29262. };
  29263. Analyser.prototype.getFloatFrequencyData = function () {
  29264. if (this._audioEngine.canUseWebAudio) {
  29265. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  29266. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  29267. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  29268. }
  29269. return this._floatFreqs;
  29270. };
  29271. Analyser.prototype.drawDebugCanvas = function () {
  29272. var _this = this;
  29273. if (this._audioEngine.canUseWebAudio) {
  29274. if (!this._debugCanvas) {
  29275. this._debugCanvas = document.createElement("canvas");
  29276. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  29277. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  29278. this._debugCanvas.style.position = "absolute";
  29279. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  29280. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  29281. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  29282. document.body.appendChild(this._debugCanvas);
  29283. this._registerFunc = function () {
  29284. _this.drawDebugCanvas();
  29285. };
  29286. this._scene.registerBeforeRender(this._registerFunc);
  29287. }
  29288. if (this._registerFunc) {
  29289. var workingArray = this.getByteFrequencyData();
  29290. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  29291. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  29292. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  29293. var value = workingArray[i];
  29294. var percent = value / this.BARGRAPHAMPLITUDE;
  29295. var height = this.DEBUGCANVASSIZE.height * percent;
  29296. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  29297. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  29298. var hue = i / this.getFrequencyBinCount() * 360;
  29299. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  29300. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  29301. }
  29302. }
  29303. }
  29304. };
  29305. Analyser.prototype.stopDebugCanvas = function () {
  29306. if (this._debugCanvas) {
  29307. this._scene.unregisterBeforeRender(this._registerFunc);
  29308. this._registerFunc = null;
  29309. document.body.removeChild(this._debugCanvas);
  29310. this._debugCanvas = null;
  29311. this._debugCanvasContext = null;
  29312. }
  29313. };
  29314. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  29315. if (this._audioEngine.canUseWebAudio) {
  29316. inputAudioNode.connect(this._webAudioAnalyser);
  29317. this._webAudioAnalyser.connect(outputAudioNode);
  29318. }
  29319. };
  29320. Analyser.prototype.dispose = function () {
  29321. if (this._audioEngine.canUseWebAudio) {
  29322. this._webAudioAnalyser.disconnect();
  29323. }
  29324. };
  29325. return Analyser;
  29326. })();
  29327. BABYLON.Analyser = Analyser;
  29328. })(BABYLON || (BABYLON = {}));
  29329. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  29330. (function (BABYLON) {
  29331. var DepthRenderer = (function () {
  29332. function DepthRenderer(scene, type) {
  29333. var _this = this;
  29334. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  29335. this._viewMatrix = BABYLON.Matrix.Zero();
  29336. this._projectionMatrix = BABYLON.Matrix.Zero();
  29337. this._transformMatrix = BABYLON.Matrix.Zero();
  29338. this._worldViewProjection = BABYLON.Matrix.Zero();
  29339. this._scene = scene;
  29340. var engine = scene.getEngine();
  29341. // Render target
  29342. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  29343. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29344. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29345. this._depthMap.refreshRate = 1;
  29346. this._depthMap.renderParticles = false;
  29347. this._depthMap.renderList = null;
  29348. // Custom render function
  29349. var renderSubMesh = function (subMesh) {
  29350. var mesh = subMesh.getRenderingMesh();
  29351. var scene = _this._scene;
  29352. var engine = scene.getEngine();
  29353. // Culling
  29354. engine.setState(subMesh.getMaterial().backFaceCulling);
  29355. // Managing instances
  29356. var batch = mesh._getInstancesRenderList(subMesh._id);
  29357. if (batch.mustReturn) {
  29358. return;
  29359. }
  29360. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  29361. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  29362. engine.enableEffect(_this._effect);
  29363. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  29364. var material = subMesh.getMaterial();
  29365. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  29366. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  29367. // Alpha test
  29368. if (material && material.needAlphaTesting()) {
  29369. var alphaTexture = material.getAlphaTestTexture();
  29370. _this._effect.setTexture("diffuseSampler", alphaTexture);
  29371. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29372. }
  29373. // Bones
  29374. if (mesh.useBones) {
  29375. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29376. }
  29377. // Draw
  29378. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  29379. }
  29380. };
  29381. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  29382. var index;
  29383. for (index = 0; index < opaqueSubMeshes.length; index++) {
  29384. renderSubMesh(opaqueSubMeshes.data[index]);
  29385. }
  29386. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  29387. renderSubMesh(alphaTestSubMeshes.data[index]);
  29388. }
  29389. };
  29390. }
  29391. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  29392. var defines = [];
  29393. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29394. var mesh = subMesh.getMesh();
  29395. var scene = mesh.getScene();
  29396. var material = subMesh.getMaterial();
  29397. // Alpha test
  29398. if (material && material.needAlphaTesting()) {
  29399. defines.push("#define ALPHATEST");
  29400. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29401. attribs.push(BABYLON.VertexBuffer.UVKind);
  29402. defines.push("#define UV1");
  29403. }
  29404. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29405. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29406. defines.push("#define UV2");
  29407. }
  29408. }
  29409. // Bones
  29410. if (mesh.useBones) {
  29411. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29412. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29413. defines.push("#define BONES");
  29414. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29415. }
  29416. // Instances
  29417. if (useInstances) {
  29418. defines.push("#define INSTANCES");
  29419. attribs.push("world0");
  29420. attribs.push("world1");
  29421. attribs.push("world2");
  29422. attribs.push("world3");
  29423. }
  29424. // Get correct effect
  29425. var join = defines.join("\n");
  29426. if (this._cachedDefines !== join) {
  29427. this._cachedDefines = join;
  29428. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  29429. }
  29430. return this._effect.isReady();
  29431. };
  29432. DepthRenderer.prototype.getDepthMap = function () {
  29433. return this._depthMap;
  29434. };
  29435. // Methods
  29436. DepthRenderer.prototype.dispose = function () {
  29437. this._depthMap.dispose();
  29438. };
  29439. return DepthRenderer;
  29440. })();
  29441. BABYLON.DepthRenderer = DepthRenderer;
  29442. })(BABYLON || (BABYLON = {}));
  29443. //# sourceMappingURL=babylon.depthRenderer.js.map
  29444. var BABYLON;
  29445. (function (BABYLON) {
  29446. var SSAORenderingPipeline = (function (_super) {
  29447. __extends(SSAORenderingPipeline, _super);
  29448. /**
  29449. * @constructor
  29450. * @param {string} name - The rendering pipeline name
  29451. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  29452. * @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 }
  29453. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  29454. */
  29455. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  29456. var _this = this;
  29457. _super.call(this, scene.getEngine(), name);
  29458. // Members
  29459. /**
  29460. * The PassPostProcess id in the pipeline that contains the original scene color
  29461. * @type {string}
  29462. */
  29463. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  29464. /**
  29465. * The SSAO PostProcess id in the pipeline
  29466. * @type {string}
  29467. */
  29468. this.SSAORenderEffect = "SSAORenderEffect";
  29469. /**
  29470. * The horizontal blur PostProcess id in the pipeline
  29471. * @type {string}
  29472. */
  29473. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  29474. /**
  29475. * The vertical blur PostProcess id in the pipeline
  29476. * @type {string}
  29477. */
  29478. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  29479. /**
  29480. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  29481. * @type {string}
  29482. */
  29483. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  29484. /**
  29485. * The output strength of the SSAO post-process. Default value is 1.0.
  29486. * @type {number}
  29487. */
  29488. this.totalStrength = 1.0;
  29489. /**
  29490. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  29491. * @type {number}
  29492. */
  29493. this.radius = 0.0002;
  29494. /**
  29495. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  29496. * Must not be equal to fallOff and superior to fallOff.
  29497. * Default value is 0.0075
  29498. * @type {number}
  29499. */
  29500. this.area = 0.0075;
  29501. /**
  29502. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  29503. * Must not be equal to area and inferior to area.
  29504. * Default value is 0.0002
  29505. * @type {number}
  29506. */
  29507. this.fallOff = 0.0002;
  29508. this._firstUpdate = true;
  29509. this._scene = scene;
  29510. // Set up assets
  29511. this._createRandomTexture();
  29512. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  29513. var ssaoRatio = ratio.ssaoRatio || ratio;
  29514. var combineRatio = ratio.combineRatio || ratio;
  29515. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29516. this._createSSAOPostProcess(ssaoRatio);
  29517. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29518. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29519. this._createSSAOCombinePostProcess(combineRatio);
  29520. // Set up pipeline
  29521. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  29522. return _this._originalColorPostProcess;
  29523. }, true));
  29524. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  29525. return _this._ssaoPostProcess;
  29526. }, true));
  29527. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  29528. return _this._blurHPostProcess;
  29529. }, true));
  29530. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  29531. return _this._blurVPostProcess;
  29532. }, true));
  29533. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  29534. return _this._ssaoCombinePostProcess;
  29535. }, true));
  29536. // Finish
  29537. scene.postProcessRenderPipelineManager.addPipeline(this);
  29538. if (cameras)
  29539. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  29540. }
  29541. // Public Methods
  29542. /**
  29543. * Returns the horizontal blur PostProcess
  29544. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  29545. */
  29546. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  29547. return this._blurHPostProcess;
  29548. };
  29549. /**
  29550. * Returns the vertical blur PostProcess
  29551. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  29552. */
  29553. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  29554. return this._blurVPostProcess;
  29555. };
  29556. /**
  29557. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  29558. */
  29559. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  29560. if (disableDepthRender === void 0) { disableDepthRender = false; }
  29561. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  29562. this._originalColorPostProcess = undefined;
  29563. this._ssaoPostProcess = undefined;
  29564. this._blurHPostProcess = undefined;
  29565. this._blurVPostProcess = undefined;
  29566. this._ssaoCombinePostProcess = undefined;
  29567. this._randomTexture.dispose();
  29568. if (disableDepthRender)
  29569. this._scene.disableDepthRenderer();
  29570. };
  29571. // Private Methods
  29572. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  29573. var _this = this;
  29574. var sampleSphere = [
  29575. 0.5381,
  29576. 0.1856,
  29577. -0.4319,
  29578. 0.1379,
  29579. 0.2486,
  29580. 0.4430,
  29581. 0.3371,
  29582. 0.5679,
  29583. -0.0057,
  29584. -0.6999,
  29585. -0.0451,
  29586. -0.0019,
  29587. 0.0689,
  29588. -0.1598,
  29589. -0.8547,
  29590. 0.0560,
  29591. 0.0069,
  29592. -0.1843,
  29593. -0.0146,
  29594. 0.1402,
  29595. 0.0762,
  29596. 0.0100,
  29597. -0.1924,
  29598. -0.0344,
  29599. -0.3577,
  29600. -0.5301,
  29601. -0.4358,
  29602. -0.3169,
  29603. 0.1063,
  29604. 0.0158,
  29605. 0.0103,
  29606. -0.5869,
  29607. 0.0046,
  29608. -0.0897,
  29609. -0.4940,
  29610. 0.3287,
  29611. 0.7119,
  29612. -0.0154,
  29613. -0.0918,
  29614. -0.0533,
  29615. 0.0596,
  29616. -0.5411,
  29617. 0.0352,
  29618. -0.0631,
  29619. 0.5460,
  29620. -0.4776,
  29621. 0.2847,
  29622. -0.0271
  29623. ];
  29624. var samplesFactor = 1.0 / 16.0;
  29625. 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);
  29626. this._ssaoPostProcess.onApply = function (effect) {
  29627. if (_this._firstUpdate) {
  29628. effect.setArray3("sampleSphere", sampleSphere);
  29629. effect.setFloat("samplesFactor", samplesFactor);
  29630. effect.setFloat("randTextureTiles", 4.0 / ratio);
  29631. _this._firstUpdate = false;
  29632. }
  29633. effect.setFloat("totalStrength", _this.totalStrength);
  29634. effect.setFloat("radius", _this.radius);
  29635. effect.setFloat("area", _this.area);
  29636. effect.setFloat("fallOff", _this.fallOff);
  29637. effect.setTexture("textureSampler", _this._depthTexture);
  29638. effect.setTexture("randomSampler", _this._randomTexture);
  29639. };
  29640. };
  29641. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  29642. var _this = this;
  29643. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29644. this._ssaoCombinePostProcess.onApply = function (effect) {
  29645. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  29646. };
  29647. };
  29648. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  29649. var size = 512;
  29650. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  29651. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29652. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29653. var context = this._randomTexture.getContext();
  29654. var rand = function (min, max) {
  29655. return Math.random() * (max - min) + min;
  29656. };
  29657. for (var x = 0; x < size; x++) {
  29658. for (var y = 0; y < size; y++) {
  29659. var randVector = BABYLON.Vector3.Zero();
  29660. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  29661. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  29662. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  29663. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  29664. context.fillRect(x, y, 1, 1);
  29665. }
  29666. }
  29667. this._randomTexture.update(false);
  29668. };
  29669. return SSAORenderingPipeline;
  29670. })(BABYLON.PostProcessRenderPipeline);
  29671. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  29672. })(BABYLON || (BABYLON = {}));
  29673. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  29674. var BABYLON;
  29675. (function (BABYLON) {
  29676. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  29677. var VolumetricLightScatteringPostProcess = (function (_super) {
  29678. __extends(VolumetricLightScatteringPostProcess, _super);
  29679. /**
  29680. * @constructor
  29681. * @param {string} name - The post-process name
  29682. * @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)
  29683. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  29684. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  29685. * @param {number} samples - The post-process quality, default 100
  29686. * @param {number} samplingMode - The post-process filtering mode
  29687. * @param {BABYLON.Engine} engine - The babylon engine
  29688. * @param {boolean} reusable - If the post-process is reusable
  29689. */
  29690. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  29691. var _this = this;
  29692. if (samples === void 0) { samples = 100; }
  29693. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  29694. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  29695. this._screenCoordinates = BABYLON.Vector2.Zero();
  29696. /**
  29697. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  29698. * @type {boolean}
  29699. */
  29700. this.useCustomMeshPosition = false;
  29701. /**
  29702. * If the post-process should inverse the light scattering direction
  29703. * @type {boolean}
  29704. */
  29705. this.invert = true;
  29706. /**
  29707. * Array containing the excluded meshes not rendered in the internal pass
  29708. */
  29709. this.excludedMeshes = new Array();
  29710. this.exposure = 0.3;
  29711. this.decay = 0.96815;
  29712. this.weight = 0.58767;
  29713. this.density = 0.926;
  29714. var scene = camera.getScene();
  29715. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  29716. // Configure mesh
  29717. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  29718. // Configure
  29719. this._createPass(scene, ratio.passRatio || ratio);
  29720. this.onApply = function (effect) {
  29721. _this._updateMeshScreenCoordinates(scene);
  29722. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  29723. effect.setFloat("exposure", _this.exposure);
  29724. effect.setFloat("decay", _this.decay);
  29725. effect.setFloat("weight", _this.weight);
  29726. effect.setFloat("density", _this.density);
  29727. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  29728. };
  29729. }
  29730. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  29731. var mesh = subMesh.getMesh();
  29732. var defines = [];
  29733. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29734. var material = subMesh.getMaterial();
  29735. var needUV = false;
  29736. // Render this.mesh as default
  29737. if (mesh === this.mesh) {
  29738. defines.push("#define BASIC_RENDER");
  29739. defines.push("#define NEED_UV");
  29740. needUV = true;
  29741. }
  29742. // Alpha test
  29743. if (material) {
  29744. if (material.needAlphaTesting() || mesh === this.mesh)
  29745. defines.push("#define ALPHATEST");
  29746. if (material.opacityTexture !== undefined) {
  29747. defines.push("#define OPACITY");
  29748. if (material.opacityTexture.getAlphaFromRGB)
  29749. defines.push("#define OPACITYRGB");
  29750. if (!needUV)
  29751. defines.push("#define NEED_UV");
  29752. }
  29753. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29754. attribs.push(BABYLON.VertexBuffer.UVKind);
  29755. defines.push("#define UV1");
  29756. }
  29757. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29758. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29759. defines.push("#define UV2");
  29760. }
  29761. }
  29762. // Bones
  29763. if (mesh.useBones) {
  29764. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29765. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29766. defines.push("#define BONES");
  29767. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29768. }
  29769. // Instances
  29770. if (useInstances) {
  29771. defines.push("#define INSTANCES");
  29772. attribs.push("world0");
  29773. attribs.push("world1");
  29774. attribs.push("world2");
  29775. attribs.push("world3");
  29776. }
  29777. // Get correct effect
  29778. var join = defines.join("\n");
  29779. if (this._cachedDefines !== join) {
  29780. this._cachedDefines = join;
  29781. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel"], ["diffuseSampler", "opacitySampler"], join);
  29782. }
  29783. return this._volumetricLightScatteringPass.isReady();
  29784. };
  29785. /**
  29786. * Sets the new light position for light scattering effect
  29787. * @param {BABYLON.Vector3} The new custom light position
  29788. */
  29789. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  29790. this._customMeshPosition = position;
  29791. };
  29792. /**
  29793. * Returns the light position for light scattering effect
  29794. * @return {BABYLON.Vector3} The custom light position
  29795. */
  29796. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  29797. return this._customMeshPosition;
  29798. };
  29799. /**
  29800. * Disposes the internal assets and detaches the post-process from the camera
  29801. */
  29802. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  29803. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  29804. if (rttIndex !== -1) {
  29805. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  29806. }
  29807. this._volumetricLightScatteringRTT.dispose();
  29808. _super.prototype.dispose.call(this, camera);
  29809. };
  29810. /**
  29811. * Returns the render target texture used by the post-process
  29812. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  29813. */
  29814. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  29815. return this._volumetricLightScatteringRTT;
  29816. };
  29817. // Private methods
  29818. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  29819. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  29820. return true;
  29821. }
  29822. return false;
  29823. };
  29824. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  29825. var _this = this;
  29826. var engine = scene.getEngine();
  29827. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  29828. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29829. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29830. this._volumetricLightScatteringRTT.renderList = null;
  29831. this._volumetricLightScatteringRTT.renderParticles = false;
  29832. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  29833. // Custom render function for submeshes
  29834. var renderSubMesh = function (subMesh) {
  29835. var mesh = subMesh.getRenderingMesh();
  29836. if (_this._meshExcluded(mesh)) {
  29837. return;
  29838. }
  29839. var scene = mesh.getScene();
  29840. var engine = scene.getEngine();
  29841. // Culling
  29842. engine.setState(subMesh.getMaterial().backFaceCulling);
  29843. // Managing instances
  29844. var batch = mesh._getInstancesRenderList(subMesh._id);
  29845. if (batch.mustReturn) {
  29846. return;
  29847. }
  29848. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  29849. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  29850. engine.enableEffect(_this._volumetricLightScatteringPass);
  29851. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  29852. var material = subMesh.getMaterial();
  29853. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  29854. // Alpha test
  29855. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  29856. var alphaTexture = material.getAlphaTestTexture();
  29857. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  29858. if (alphaTexture) {
  29859. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29860. }
  29861. if (material.opacityTexture !== undefined) {
  29862. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  29863. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  29864. }
  29865. }
  29866. // Bones
  29867. if (mesh.useBones) {
  29868. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29869. }
  29870. // Draw
  29871. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  29872. }
  29873. };
  29874. // Render target texture callbacks
  29875. var savedSceneClearColor;
  29876. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  29877. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  29878. savedSceneClearColor = scene.clearColor;
  29879. scene.clearColor = sceneClearColor;
  29880. };
  29881. this._volumetricLightScatteringRTT.onAfterRender = function () {
  29882. scene.clearColor = savedSceneClearColor;
  29883. };
  29884. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  29885. var engine = scene.getEngine();
  29886. var index;
  29887. for (index = 0; index < opaqueSubMeshes.length; index++) {
  29888. renderSubMesh(opaqueSubMeshes.data[index]);
  29889. }
  29890. engine.setAlphaTesting(true);
  29891. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  29892. renderSubMesh(alphaTestSubMeshes.data[index]);
  29893. }
  29894. engine.setAlphaTesting(false);
  29895. if (transparentSubMeshes.length) {
  29896. for (index = 0; index < transparentSubMeshes.length; index++) {
  29897. var submesh = transparentSubMeshes.data[index];
  29898. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  29899. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  29900. }
  29901. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  29902. sortedArray.sort(function (a, b) {
  29903. // Alpha index first
  29904. if (a._alphaIndex > b._alphaIndex) {
  29905. return 1;
  29906. }
  29907. if (a._alphaIndex < b._alphaIndex) {
  29908. return -1;
  29909. }
  29910. // Then distance to camera
  29911. if (a._distanceToCamera < b._distanceToCamera) {
  29912. return 1;
  29913. }
  29914. if (a._distanceToCamera > b._distanceToCamera) {
  29915. return -1;
  29916. }
  29917. return 0;
  29918. });
  29919. // Render sub meshes
  29920. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29921. for (index = 0; index < sortedArray.length; index++) {
  29922. renderSubMesh(sortedArray[index]);
  29923. }
  29924. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29925. }
  29926. };
  29927. };
  29928. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  29929. var transform = scene.getTransformMatrix();
  29930. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  29931. this._screenCoordinates.x = pos.x / this._viewPort.width;
  29932. this._screenCoordinates.y = pos.y / this._viewPort.height;
  29933. if (this.invert)
  29934. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  29935. };
  29936. // Static methods
  29937. /**
  29938. * Creates a default mesh for the Volumeric Light Scattering post-process
  29939. * @param {string} The mesh name
  29940. * @param {BABYLON.Scene} The scene where to create the mesh
  29941. * @return {BABYLON.Mesh} the default mesh
  29942. */
  29943. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  29944. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  29945. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  29946. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  29947. return mesh;
  29948. };
  29949. return VolumetricLightScatteringPostProcess;
  29950. })(BABYLON.PostProcess);
  29951. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  29952. })(BABYLON || (BABYLON = {}));
  29953. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  29954. var BABYLON;
  29955. (function (BABYLON) {
  29956. var LensRenderingPipeline = (function (_super) {
  29957. __extends(LensRenderingPipeline, _super);
  29958. /**
  29959. * @constructor
  29960. *
  29961. * Effect parameters are as follow:
  29962. * {
  29963. * chromatic_aberration: number; // from 0 to x (1 for realism)
  29964. * edge_blur: number; // from 0 to x (1 for realism)
  29965. * distortion: number; // from 0 to x (1 for realism)
  29966. * grain_amount: number; // from 0 to 1
  29967. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  29968. * dof_focus_depth: number; // depth-of-field: focus depth; unset to disable (disabled by default)
  29969. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  29970. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  29971. * dof_gain: number; // depth-of-field: depthOfField gain; unset to disable (disabled by default)
  29972. * dof_threshold: number; // depth-of-field: depthOfField threshold (default: 1)
  29973. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  29974. * }
  29975. * Note: if an effect parameter is unset, effect is disabled
  29976. *
  29977. * @param {string} name - The rendering pipeline name
  29978. * @param {object} parameters - An object containing all parameters (see above)
  29979. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  29980. * @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)
  29981. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  29982. */
  29983. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  29984. var _this = this;
  29985. if (ratio === void 0) { ratio = 1.0; }
  29986. _super.call(this, scene.getEngine(), name);
  29987. // Lens effects can be of the following:
  29988. // - chromatic aberration (slight shift of RGB colors)
  29989. // - blur on the edge of the lens
  29990. // - lens distortion
  29991. // - depth-of-field blur & highlights enhancing
  29992. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  29993. // - grain effect (noise or custom texture)
  29994. // Two additional texture samplers are needed:
  29995. // - depth map (for depth-of-field)
  29996. // - grain texture
  29997. /**
  29998. * The chromatic aberration PostProcess id in the pipeline
  29999. * @type {string}
  30000. */
  30001. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  30002. /**
  30003. * The highlights enhancing PostProcess id in the pipeline
  30004. * @type {string}
  30005. */
  30006. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  30007. /**
  30008. * The depth-of-field PostProcess id in the pipeline
  30009. * @type {string}
  30010. */
  30011. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  30012. this._scene = scene;
  30013. // Fetch texture samplers
  30014. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  30015. if (parameters.grain_texture) {
  30016. this._grainTexture = parameters.grain_texture;
  30017. }
  30018. else {
  30019. this._createGrainTexture();
  30020. }
  30021. // save parameters
  30022. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  30023. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  30024. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  30025. this._distortion = parameters.distortion ? parameters.distortion : 0;
  30026. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  30027. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  30028. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  30029. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  30030. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  30031. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  30032. // Create effects
  30033. this._createChromaticAberrationPostProcess(ratio);
  30034. this._createHighlightsPostProcess(ratio);
  30035. this._createDepthOfFieldPostProcess(ratio);
  30036. // Set up pipeline
  30037. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () {
  30038. return _this._chromaticAberrationPostProcess;
  30039. }, true));
  30040. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () {
  30041. return _this._highlightsPostProcess;
  30042. }, true));
  30043. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () {
  30044. return _this._depthOfFieldPostProcess;
  30045. }, true));
  30046. if (this._highlightsGain == -1) {
  30047. this._disableEffect(this.HighlightsEnhancingEffect, null);
  30048. }
  30049. // Finish
  30050. scene.postProcessRenderPipelineManager.addPipeline(this);
  30051. if (cameras) {
  30052. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  30053. }
  30054. }
  30055. // public methods (self explanatory)
  30056. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) {
  30057. this._edgeBlur = amount;
  30058. };
  30059. LensRenderingPipeline.prototype.disableEdgeBlur = function () {
  30060. this._edgeBlur = 0;
  30061. };
  30062. LensRenderingPipeline.prototype.setGrainAmount = function (amount) {
  30063. this._grainAmount = amount;
  30064. };
  30065. LensRenderingPipeline.prototype.disableGrain = function () {
  30066. this._grainAmount = 0;
  30067. };
  30068. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) {
  30069. this._chromaticAberration = amount;
  30070. };
  30071. LensRenderingPipeline.prototype.disableChromaticAberration = function () {
  30072. this._chromaticAberration = 0;
  30073. };
  30074. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) {
  30075. this._distortion = amount;
  30076. };
  30077. LensRenderingPipeline.prototype.disableEdgeDistortion = function () {
  30078. this._distortion = 0;
  30079. };
  30080. LensRenderingPipeline.prototype.setFocusDepth = function (amount) {
  30081. this._dofDepth = amount;
  30082. };
  30083. LensRenderingPipeline.prototype.disableDepthOfField = function () {
  30084. this._dofDepth = -1;
  30085. };
  30086. LensRenderingPipeline.prototype.setAperture = function (amount) {
  30087. this._dofAperture = amount;
  30088. };
  30089. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  30090. this._dofPentagon = true;
  30091. };
  30092. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  30093. this._dofPentagon = false;
  30094. };
  30095. LensRenderingPipeline.prototype.enableNoiseBlur = function () {
  30096. this._blurNoise = true;
  30097. };
  30098. LensRenderingPipeline.prototype.disableNoiseBlur = function () {
  30099. this._blurNoise = false;
  30100. };
  30101. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  30102. this._highlightsGain = amount;
  30103. };
  30104. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  30105. if (this._highlightsGain == -1) {
  30106. this._highlightsGain = 1.0;
  30107. }
  30108. this._highlightsThreshold = amount;
  30109. };
  30110. LensRenderingPipeline.prototype.disableHighlights = function () {
  30111. this._highlightsGain = -1;
  30112. };
  30113. /**
  30114. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  30115. */
  30116. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  30117. if (disableDepthRender === void 0) { disableDepthRender = false; }
  30118. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  30119. this._chromaticAberrationPostProcess = undefined;
  30120. this._highlightsPostProcess = undefined;
  30121. this._depthOfFieldPostProcess = undefined;
  30122. this._grainTexture.dispose();
  30123. if (disableDepthRender)
  30124. this._scene.disableDepthRenderer();
  30125. };
  30126. // colors shifting and distortion
  30127. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  30128. var _this = this;
  30129. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30130. this._chromaticAberrationPostProcess.onApply = function (effect) {
  30131. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  30132. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  30133. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  30134. };
  30135. };
  30136. // highlights enhancing
  30137. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  30138. var _this = this;
  30139. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30140. this._highlightsPostProcess.onApply = function (effect) {
  30141. effect.setFloat('gain', _this._highlightsGain);
  30142. effect.setFloat('threshold', _this._highlightsThreshold);
  30143. effect.setBool('pentagon', _this._dofPentagon);
  30144. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  30145. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  30146. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  30147. };
  30148. };
  30149. // colors shifting and distortion
  30150. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  30151. var _this = this;
  30152. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  30153. "focus_depth",
  30154. "aperture",
  30155. "pentagon",
  30156. "maxZ",
  30157. "edge_blur",
  30158. "chromatic_aberration",
  30159. "distortion",
  30160. "blur_noise",
  30161. "grain_amount",
  30162. "screen_width",
  30163. "screen_height",
  30164. "highlights"
  30165. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  30166. this._depthOfFieldPostProcess.onApply = function (effect) {
  30167. effect.setBool('blur_noise', _this._blurNoise);
  30168. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  30169. effect.setFloat('grain_amount', _this._grainAmount);
  30170. effect.setTexture("depthSampler", _this._depthTexture);
  30171. effect.setTexture("grainSampler", _this._grainTexture);
  30172. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  30173. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  30174. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  30175. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  30176. effect.setFloat('distortion', _this._distortion);
  30177. effect.setFloat('focus_depth', _this._dofDepth);
  30178. effect.setFloat('aperture', _this._dofAperture);
  30179. effect.setFloat('edge_blur', _this._edgeBlur);
  30180. effect.setBool('highlights', (_this._highlightsGain != -1));
  30181. };
  30182. };
  30183. // creates a black and white random noise texture, 512x512
  30184. LensRenderingPipeline.prototype._createGrainTexture = function () {
  30185. var size = 512;
  30186. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  30187. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30188. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30189. var context = this._grainTexture.getContext();
  30190. var rand = function (min, max) {
  30191. return Math.random() * (max - min) + min;
  30192. };
  30193. var value;
  30194. for (var x = 0; x < size; x++) {
  30195. for (var y = 0; y < size; y++) {
  30196. value = Math.floor(rand(0.42, 0.58) * 255);
  30197. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  30198. context.fillRect(x, y, 1, 1);
  30199. }
  30200. }
  30201. this._grainTexture.update(false);
  30202. };
  30203. return LensRenderingPipeline;
  30204. })(BABYLON.PostProcessRenderPipeline);
  30205. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  30206. })(BABYLON || (BABYLON = {}));
  30207. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map//
  30208. // This post-process allows the modification of rendered colors by using
  30209. // a 'look-up table' (LUT). This effect is also called Color Grading.
  30210. //
  30211. // The object needs to be provided an url to a texture containing the color
  30212. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  30213. // Use an image editing software to tweak the LUT to match your needs.
  30214. //
  30215. // For an example of a color LUT, see here:
  30216. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  30217. // For explanations on color grading, see here:
  30218. // http://udn.epicgames.com/Three/ColorGrading.html
  30219. //
  30220. var BABYLON;
  30221. (function (BABYLON) {
  30222. var ColorCorrectionPostProcess = (function (_super) {
  30223. __extends(ColorCorrectionPostProcess, _super);
  30224. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  30225. var _this = this;
  30226. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  30227. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  30228. this._colorTableTexture.anisotropicFilteringLevel = 1;
  30229. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30230. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30231. this.onApply = function (effect) {
  30232. effect.setTexture("colorTable", _this._colorTableTexture);
  30233. };
  30234. }
  30235. return ColorCorrectionPostProcess;
  30236. })(BABYLON.PostProcess);
  30237. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  30238. })(BABYLON || (BABYLON = {}));
  30239. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.mapvar BABYLON;
  30240. (function (BABYLON) {
  30241. var SmartCollection = (function () {
  30242. function SmartCollection(capacity) {
  30243. if (capacity === void 0) { capacity = 10; }
  30244. this.count = 0;
  30245. this._initialCapacity = capacity;
  30246. this.items = {};
  30247. this._keys = new Array(this._initialCapacity);
  30248. }
  30249. SmartCollection.prototype.add = function (key, item) {
  30250. if (this.items[key] != undefined) {
  30251. return -1;
  30252. }
  30253. this.items[key] = item;
  30254. //literal keys are always strings, but we keep source type of key in _keys array
  30255. this._keys[this.count++] = key;
  30256. if (this.count > this._keys.length) {
  30257. this._keys.length *= 2;
  30258. }
  30259. return this.count;
  30260. };
  30261. SmartCollection.prototype.remove = function (key) {
  30262. if (this.items[key] == undefined) {
  30263. return -1;
  30264. }
  30265. return this.removeItemOfIndex(this.indexOf(key));
  30266. };
  30267. SmartCollection.prototype.removeItemOfIndex = function (index) {
  30268. if (index < this.count && index > -1) {
  30269. delete this.items[this._keys[index]];
  30270. while (index < this.count) {
  30271. this._keys[index] = this._keys[index + 1];
  30272. index++;
  30273. }
  30274. }
  30275. else {
  30276. return -1;
  30277. }
  30278. return --this.count;
  30279. };
  30280. SmartCollection.prototype.indexOf = function (key) {
  30281. for (var i = 0; i !== this.count; i++) {
  30282. if (this._keys[i] === key) {
  30283. return i;
  30284. }
  30285. }
  30286. return -1;
  30287. };
  30288. SmartCollection.prototype.item = function (key) {
  30289. return this.items[key];
  30290. };
  30291. SmartCollection.prototype.getAllKeys = function () {
  30292. if (this.count > 0) {
  30293. var keys = new Array(this.count);
  30294. for (var i = 0; i < this.count; i++) {
  30295. keys[i] = this._keys[i];
  30296. }
  30297. return keys;
  30298. }
  30299. else {
  30300. return undefined;
  30301. }
  30302. };
  30303. SmartCollection.prototype.getKeyByIndex = function (index) {
  30304. if (index < this.count && index > -1) {
  30305. return this._keys[index];
  30306. }
  30307. else {
  30308. return undefined;
  30309. }
  30310. };
  30311. SmartCollection.prototype.getItemByIndex = function (index) {
  30312. if (index < this.count && index > -1) {
  30313. return this.items[this._keys[index]];
  30314. }
  30315. else {
  30316. return undefined;
  30317. }
  30318. };
  30319. SmartCollection.prototype.empty = function () {
  30320. if (this.count > 0) {
  30321. this.count = 0;
  30322. this.items = {};
  30323. this._keys = new Array(this._initialCapacity);
  30324. }
  30325. };
  30326. SmartCollection.prototype.forEach = function (block) {
  30327. var key;
  30328. for (key in this.items) {
  30329. if (this.items.hasOwnProperty(key)) {
  30330. block(this.items[key]);
  30331. }
  30332. }
  30333. };
  30334. return SmartCollection;
  30335. })();
  30336. BABYLON.SmartCollection = SmartCollection;
  30337. })(BABYLON || (BABYLON = {}));
  30338. //# sourceMappingURL=babylon.smartCollection.js.map