babylon.2.1-rc.debug.js 1.6 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805
  1. var __extends = (this && 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. };
  7. var BABYLON;
  8. (function (BABYLON) {
  9. var Color3 = (function () {
  10. function Color3(r, g, b) {
  11. if (r === void 0) { r = 0; }
  12. if (g === void 0) { g = 0; }
  13. if (b === void 0) { b = 0; }
  14. this.r = r;
  15. this.g = g;
  16. this.b = b;
  17. }
  18. Color3.prototype.toString = function () {
  19. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  20. };
  21. // Operators
  22. Color3.prototype.toArray = function (array, index) {
  23. if (index === undefined) {
  24. index = 0;
  25. }
  26. array[index] = this.r;
  27. array[index + 1] = this.g;
  28. array[index + 2] = this.b;
  29. return this;
  30. };
  31. Color3.prototype.toColor4 = function (alpha) {
  32. if (alpha === void 0) { alpha = 1; }
  33. return new Color4(this.r, this.g, this.b, alpha);
  34. };
  35. Color3.prototype.asArray = function () {
  36. var result = [];
  37. this.toArray(result, 0);
  38. return result;
  39. };
  40. Color3.prototype.toLuminance = function () {
  41. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  42. };
  43. Color3.prototype.multiply = function (otherColor) {
  44. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  45. };
  46. Color3.prototype.multiplyToRef = function (otherColor, result) {
  47. result.r = this.r * otherColor.r;
  48. result.g = this.g * otherColor.g;
  49. result.b = this.b * otherColor.b;
  50. return this;
  51. };
  52. Color3.prototype.equals = function (otherColor) {
  53. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  54. };
  55. Color3.prototype.scale = function (scale) {
  56. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  57. };
  58. Color3.prototype.scaleToRef = function (scale, result) {
  59. result.r = this.r * scale;
  60. result.g = this.g * scale;
  61. result.b = this.b * scale;
  62. return this;
  63. };
  64. Color3.prototype.add = function (otherColor) {
  65. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  66. };
  67. Color3.prototype.addToRef = function (otherColor, result) {
  68. result.r = this.r + otherColor.r;
  69. result.g = this.g + otherColor.g;
  70. result.b = this.b + otherColor.b;
  71. return this;
  72. };
  73. Color3.prototype.subtract = function (otherColor) {
  74. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  75. };
  76. Color3.prototype.subtractToRef = function (otherColor, result) {
  77. result.r = this.r - otherColor.r;
  78. result.g = this.g - otherColor.g;
  79. result.b = this.b - otherColor.b;
  80. return this;
  81. };
  82. Color3.prototype.clone = function () {
  83. return new Color3(this.r, this.g, this.b);
  84. };
  85. Color3.prototype.copyFrom = function (source) {
  86. this.r = source.r;
  87. this.g = source.g;
  88. this.b = source.b;
  89. return this;
  90. };
  91. Color3.prototype.copyFromFloats = function (r, g, b) {
  92. this.r = r;
  93. this.g = g;
  94. this.b = b;
  95. return this;
  96. };
  97. // Statics
  98. Color3.FromArray = function (array, offset) {
  99. if (offset === void 0) { offset = 0; }
  100. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  101. };
  102. Color3.FromInts = function (r, g, b) {
  103. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  104. };
  105. Color3.Lerp = function (start, end, amount) {
  106. var r = start.r + ((end.r - start.r) * amount);
  107. var g = start.g + ((end.g - start.g) * amount);
  108. var b = start.b + ((end.b - start.b) * amount);
  109. return new Color3(r, g, b);
  110. };
  111. Color3.Red = function () { return new Color3(1, 0, 0); };
  112. Color3.Green = function () { return new Color3(0, 1, 0); };
  113. Color3.Blue = function () { return new Color3(0, 0, 1); };
  114. Color3.Black = function () { return new Color3(0, 0, 0); };
  115. Color3.White = function () { return new Color3(1, 1, 1); };
  116. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  117. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  118. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  119. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  120. return Color3;
  121. })();
  122. BABYLON.Color3 = Color3;
  123. var Color4 = (function () {
  124. function Color4(r, g, b, a) {
  125. this.r = r;
  126. this.g = g;
  127. this.b = b;
  128. this.a = a;
  129. }
  130. // Operators
  131. Color4.prototype.addInPlace = function (right) {
  132. this.r += right.r;
  133. this.g += right.g;
  134. this.b += right.b;
  135. this.a += right.a;
  136. return this;
  137. };
  138. Color4.prototype.asArray = function () {
  139. var result = [];
  140. this.toArray(result, 0);
  141. return result;
  142. };
  143. Color4.prototype.toArray = function (array, index) {
  144. if (index === undefined) {
  145. index = 0;
  146. }
  147. array[index] = this.r;
  148. array[index + 1] = this.g;
  149. array[index + 2] = this.b;
  150. array[index + 3] = this.a;
  151. return this;
  152. };
  153. Color4.prototype.add = function (right) {
  154. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  155. };
  156. Color4.prototype.subtract = function (right) {
  157. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  158. };
  159. Color4.prototype.subtractToRef = function (right, result) {
  160. result.r = this.r - right.r;
  161. result.g = this.g - right.g;
  162. result.b = this.b - right.b;
  163. result.a = this.a - right.a;
  164. return this;
  165. };
  166. Color4.prototype.scale = function (scale) {
  167. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  168. };
  169. Color4.prototype.scaleToRef = function (scale, result) {
  170. result.r = this.r * scale;
  171. result.g = this.g * scale;
  172. result.b = this.b * scale;
  173. result.a = this.a * scale;
  174. return this;
  175. };
  176. Color4.prototype.toString = function () {
  177. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  178. };
  179. Color4.prototype.clone = function () {
  180. return new Color4(this.r, this.g, this.b, this.a);
  181. };
  182. Color4.prototype.copyFrom = function (source) {
  183. this.r = source.r;
  184. this.g = source.g;
  185. this.b = source.b;
  186. this.a = source.a;
  187. return this;
  188. };
  189. // Statics
  190. Color4.Lerp = function (left, right, amount) {
  191. var result = new Color4(0, 0, 0, 0);
  192. Color4.LerpToRef(left, right, amount, result);
  193. return result;
  194. };
  195. Color4.LerpToRef = function (left, right, amount, result) {
  196. result.r = left.r + (right.r - left.r) * amount;
  197. result.g = left.g + (right.g - left.g) * amount;
  198. result.b = left.b + (right.b - left.b) * amount;
  199. result.a = left.a + (right.a - left.a) * amount;
  200. };
  201. Color4.FromArray = function (array, offset) {
  202. if (offset === void 0) { offset = 0; }
  203. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  204. };
  205. Color4.FromInts = function (r, g, b, a) {
  206. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  207. };
  208. return Color4;
  209. })();
  210. BABYLON.Color4 = Color4;
  211. var Vector2 = (function () {
  212. function Vector2(x, y) {
  213. this.x = x;
  214. this.y = y;
  215. }
  216. Vector2.prototype.toString = function () {
  217. return "{X: " + this.x + " Y:" + this.y + "}";
  218. };
  219. // Operators
  220. Vector2.prototype.toArray = function (array, index) {
  221. if (index === void 0) { index = 0; }
  222. array[index] = this.x;
  223. array[index + 1] = this.y;
  224. return this;
  225. };
  226. Vector2.prototype.asArray = function () {
  227. var result = [];
  228. this.toArray(result, 0);
  229. return result;
  230. };
  231. Vector2.prototype.copyFrom = function (source) {
  232. this.x = source.x;
  233. this.y = source.y;
  234. return this;
  235. };
  236. Vector2.prototype.copyFromFloats = function (x, y) {
  237. this.x = x;
  238. this.y = y;
  239. return this;
  240. };
  241. Vector2.prototype.add = function (otherVector) {
  242. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  243. };
  244. Vector2.prototype.addVector3 = function (otherVector) {
  245. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  246. };
  247. Vector2.prototype.subtract = function (otherVector) {
  248. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  249. };
  250. Vector2.prototype.subtractInPlace = function (otherVector) {
  251. this.x -= otherVector.x;
  252. this.y -= otherVector.y;
  253. return this;
  254. };
  255. Vector2.prototype.multiplyInPlace = function (otherVector) {
  256. this.x *= otherVector.x;
  257. this.y *= otherVector.y;
  258. return this;
  259. };
  260. Vector2.prototype.multiply = function (otherVector) {
  261. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  262. };
  263. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  264. result.x = this.x * otherVector.x;
  265. result.y = this.y * otherVector.y;
  266. return this;
  267. };
  268. Vector2.prototype.multiplyByFloats = function (x, y) {
  269. return new Vector2(this.x * x, this.y * y);
  270. };
  271. Vector2.prototype.divide = function (otherVector) {
  272. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  273. };
  274. Vector2.prototype.divideToRef = function (otherVector, result) {
  275. result.x = this.x / otherVector.x;
  276. result.y = this.y / otherVector.y;
  277. return this;
  278. };
  279. Vector2.prototype.negate = function () {
  280. return new Vector2(-this.x, -this.y);
  281. };
  282. Vector2.prototype.scaleInPlace = function (scale) {
  283. this.x *= scale;
  284. this.y *= scale;
  285. return this;
  286. };
  287. Vector2.prototype.scale = function (scale) {
  288. return new Vector2(this.x * scale, this.y * scale);
  289. };
  290. Vector2.prototype.equals = function (otherVector) {
  291. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  292. };
  293. Vector2.prototype.equalsWithEpsilon = function (otherVector) {
  294. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y);
  295. };
  296. // Properties
  297. Vector2.prototype.length = function () {
  298. return Math.sqrt(this.x * this.x + this.y * this.y);
  299. };
  300. Vector2.prototype.lengthSquared = function () {
  301. return (this.x * this.x + this.y * this.y);
  302. };
  303. // Methods
  304. Vector2.prototype.normalize = function () {
  305. var len = this.length();
  306. if (len === 0)
  307. return this;
  308. var num = 1.0 / len;
  309. this.x *= num;
  310. this.y *= num;
  311. return this;
  312. };
  313. Vector2.prototype.clone = function () {
  314. return new Vector2(this.x, this.y);
  315. };
  316. // Statics
  317. Vector2.Zero = function () {
  318. return new Vector2(0, 0);
  319. };
  320. Vector2.FromArray = function (array, offset) {
  321. if (offset === void 0) { offset = 0; }
  322. return new Vector2(array[offset], array[offset + 1]);
  323. };
  324. Vector2.FromArrayToRef = function (array, offset, result) {
  325. result.x = array[offset];
  326. result.y = array[offset + 1];
  327. };
  328. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  329. var squared = amount * amount;
  330. var cubed = amount * squared;
  331. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  332. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  333. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  334. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  335. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  336. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  337. return new Vector2(x, y);
  338. };
  339. Vector2.Clamp = function (value, min, max) {
  340. var x = value.x;
  341. x = (x > max.x) ? max.x : x;
  342. x = (x < min.x) ? min.x : x;
  343. var y = value.y;
  344. y = (y > max.y) ? max.y : y;
  345. y = (y < min.y) ? min.y : y;
  346. return new Vector2(x, y);
  347. };
  348. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  349. var squared = amount * amount;
  350. var cubed = amount * squared;
  351. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  352. var part2 = (-2.0 * cubed) + (3.0 * squared);
  353. var part3 = (cubed - (2.0 * squared)) + amount;
  354. var part4 = cubed - squared;
  355. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  356. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  357. return new Vector2(x, y);
  358. };
  359. Vector2.Lerp = function (start, end, amount) {
  360. var x = start.x + ((end.x - start.x) * amount);
  361. var y = start.y + ((end.y - start.y) * amount);
  362. return new Vector2(x, y);
  363. };
  364. Vector2.Dot = function (left, right) {
  365. return left.x * right.x + left.y * right.y;
  366. };
  367. Vector2.Normalize = function (vector) {
  368. var newVector = vector.clone();
  369. newVector.normalize();
  370. return newVector;
  371. };
  372. Vector2.Minimize = function (left, right) {
  373. var x = (left.x < right.x) ? left.x : right.x;
  374. var y = (left.y < right.y) ? left.y : right.y;
  375. return new Vector2(x, y);
  376. };
  377. Vector2.Maximize = function (left, right) {
  378. var x = (left.x > right.x) ? left.x : right.x;
  379. var y = (left.y > right.y) ? left.y : right.y;
  380. return new Vector2(x, y);
  381. };
  382. Vector2.Transform = function (vector, transformation) {
  383. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  384. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  385. return new Vector2(x, y);
  386. };
  387. Vector2.Distance = function (value1, value2) {
  388. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  389. };
  390. Vector2.DistanceSquared = function (value1, value2) {
  391. var x = value1.x - value2.x;
  392. var y = value1.y - value2.y;
  393. return (x * x) + (y * y);
  394. };
  395. return Vector2;
  396. })();
  397. BABYLON.Vector2 = Vector2;
  398. var Vector3 = (function () {
  399. function Vector3(x, y, z) {
  400. this.x = x;
  401. this.y = y;
  402. this.z = z;
  403. }
  404. Vector3.prototype.toString = function () {
  405. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  406. };
  407. // Operators
  408. Vector3.prototype.asArray = function () {
  409. var result = [];
  410. this.toArray(result, 0);
  411. return result;
  412. };
  413. Vector3.prototype.toArray = function (array, index) {
  414. if (index === void 0) { index = 0; }
  415. array[index] = this.x;
  416. array[index + 1] = this.y;
  417. array[index + 2] = this.z;
  418. return this;
  419. };
  420. Vector3.prototype.toQuaternion = function () {
  421. var result = new Quaternion(0, 0, 0, 1);
  422. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  423. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  424. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  425. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  426. var cosy = Math.cos(this.y * 0.5);
  427. var siny = Math.sin(this.y * 0.5);
  428. result.x = coszMinusx * siny;
  429. result.y = -sinzMinusx * siny;
  430. result.z = sinxPlusz * cosy;
  431. result.w = cosxPlusz * cosy;
  432. return result;
  433. };
  434. Vector3.prototype.addInPlace = function (otherVector) {
  435. this.x += otherVector.x;
  436. this.y += otherVector.y;
  437. this.z += otherVector.z;
  438. return this;
  439. };
  440. Vector3.prototype.add = function (otherVector) {
  441. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  442. };
  443. Vector3.prototype.addToRef = function (otherVector, result) {
  444. result.x = this.x + otherVector.x;
  445. result.y = this.y + otherVector.y;
  446. result.z = this.z + otherVector.z;
  447. return this;
  448. };
  449. Vector3.prototype.subtractInPlace = function (otherVector) {
  450. this.x -= otherVector.x;
  451. this.y -= otherVector.y;
  452. this.z -= otherVector.z;
  453. return this;
  454. };
  455. Vector3.prototype.subtract = function (otherVector) {
  456. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  457. };
  458. Vector3.prototype.subtractToRef = function (otherVector, result) {
  459. result.x = this.x - otherVector.x;
  460. result.y = this.y - otherVector.y;
  461. result.z = this.z - otherVector.z;
  462. return this;
  463. };
  464. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  465. return new Vector3(this.x - x, this.y - y, this.z - z);
  466. };
  467. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  468. result.x = this.x - x;
  469. result.y = this.y - y;
  470. result.z = this.z - z;
  471. return this;
  472. };
  473. Vector3.prototype.negate = function () {
  474. return new Vector3(-this.x, -this.y, -this.z);
  475. };
  476. Vector3.prototype.scaleInPlace = function (scale) {
  477. this.x *= scale;
  478. this.y *= scale;
  479. this.z *= scale;
  480. return this;
  481. };
  482. Vector3.prototype.scale = function (scale) {
  483. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  484. };
  485. Vector3.prototype.scaleToRef = function (scale, result) {
  486. result.x = this.x * scale;
  487. result.y = this.y * scale;
  488. result.z = this.z * scale;
  489. };
  490. Vector3.prototype.equals = function (otherVector) {
  491. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  492. };
  493. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  494. return otherVector && BABYLON.Tools.WithinEpsilon(this.x, otherVector.x) && BABYLON.Tools.WithinEpsilon(this.y, otherVector.y) && BABYLON.Tools.WithinEpsilon(this.z, otherVector.z);
  495. };
  496. Vector3.prototype.equalsToFloats = function (x, y, z) {
  497. return this.x === x && this.y === y && this.z === z;
  498. };
  499. Vector3.prototype.multiplyInPlace = function (otherVector) {
  500. this.x *= otherVector.x;
  501. this.y *= otherVector.y;
  502. this.z *= otherVector.z;
  503. return this;
  504. };
  505. Vector3.prototype.multiply = function (otherVector) {
  506. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  507. };
  508. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  509. result.x = this.x * otherVector.x;
  510. result.y = this.y * otherVector.y;
  511. result.z = this.z * otherVector.z;
  512. return this;
  513. };
  514. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  515. return new Vector3(this.x * x, this.y * y, this.z * z);
  516. };
  517. Vector3.prototype.divide = function (otherVector) {
  518. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  519. };
  520. Vector3.prototype.divideToRef = function (otherVector, result) {
  521. result.x = this.x / otherVector.x;
  522. result.y = this.y / otherVector.y;
  523. result.z = this.z / otherVector.z;
  524. return this;
  525. };
  526. Vector3.prototype.MinimizeInPlace = function (other) {
  527. if (other.x < this.x)
  528. this.x = other.x;
  529. if (other.y < this.y)
  530. this.y = other.y;
  531. if (other.z < this.z)
  532. this.z = other.z;
  533. return this;
  534. };
  535. Vector3.prototype.MaximizeInPlace = function (other) {
  536. if (other.x > this.x)
  537. this.x = other.x;
  538. if (other.y > this.y)
  539. this.y = other.y;
  540. if (other.z > this.z)
  541. this.z = other.z;
  542. return this;
  543. };
  544. // Properties
  545. Vector3.prototype.length = function () {
  546. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  547. };
  548. Vector3.prototype.lengthSquared = function () {
  549. return (this.x * this.x + this.y * this.y + this.z * this.z);
  550. };
  551. // Methods
  552. Vector3.prototype.normalize = function () {
  553. var len = this.length();
  554. if (len === 0 || len === 1.0)
  555. return this;
  556. var num = 1.0 / len;
  557. this.x *= num;
  558. this.y *= num;
  559. this.z *= num;
  560. return this;
  561. };
  562. Vector3.prototype.clone = function () {
  563. return new Vector3(this.x, this.y, this.z);
  564. };
  565. Vector3.prototype.copyFrom = function (source) {
  566. this.x = source.x;
  567. this.y = source.y;
  568. this.z = source.z;
  569. return this;
  570. };
  571. Vector3.prototype.copyFromFloats = function (x, y, z) {
  572. this.x = x;
  573. this.y = y;
  574. this.z = z;
  575. return this;
  576. };
  577. // Statics
  578. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  579. var d0 = Vector3.Dot(vector0, axis) - size;
  580. var d1 = Vector3.Dot(vector1, axis) - size;
  581. var s = d0 / (d0 - d1);
  582. return s;
  583. };
  584. Vector3.FromArray = function (array, offset) {
  585. if (!offset) {
  586. offset = 0;
  587. }
  588. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  589. };
  590. Vector3.FromArrayToRef = function (array, offset, result) {
  591. result.x = array[offset];
  592. result.y = array[offset + 1];
  593. result.z = array[offset + 2];
  594. };
  595. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  596. result.x = array[offset];
  597. result.y = array[offset + 1];
  598. result.z = array[offset + 2];
  599. };
  600. Vector3.FromFloatsToRef = function (x, y, z, result) {
  601. result.x = x;
  602. result.y = y;
  603. result.z = z;
  604. };
  605. Vector3.Zero = function () {
  606. return new Vector3(0, 0, 0);
  607. };
  608. Vector3.Up = function () {
  609. return new Vector3(0, 1.0, 0);
  610. };
  611. Vector3.TransformCoordinates = function (vector, transformation) {
  612. var result = Vector3.Zero();
  613. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  614. return result;
  615. };
  616. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  617. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  618. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  619. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  620. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  621. result.x = x / w;
  622. result.y = y / w;
  623. result.z = z / w;
  624. };
  625. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  626. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  627. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  628. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  629. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  630. result.x = rx / rw;
  631. result.y = ry / rw;
  632. result.z = rz / rw;
  633. };
  634. Vector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  635. var v = SIMD.float32x4.loadXYZ(vector._data, 0);
  636. var m0 = SIMD.float32x4.load(transformation.m, 0);
  637. var m1 = SIMD.float32x4.load(transformation.m, 4);
  638. var m2 = SIMD.float32x4.load(transformation.m, 8);
  639. var m3 = SIMD.float32x4.load(transformation.m, 12);
  640. 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));
  641. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  642. SIMD.float32x4.storeXYZ(result._data, 0, r);
  643. };
  644. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  645. var v0 = SIMD.float32x4.splat(x);
  646. var v1 = SIMD.float32x4.splat(y);
  647. var v2 = SIMD.float32x4.splat(z);
  648. var m0 = SIMD.float32x4.load(transformation.m, 0);
  649. var m1 = SIMD.float32x4.load(transformation.m, 4);
  650. var m2 = SIMD.float32x4.load(transformation.m, 8);
  651. var m3 = SIMD.float32x4.load(transformation.m, 12);
  652. 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));
  653. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  654. SIMD.float32x4.storeXYZ(result._data, 0, r);
  655. };
  656. Vector3.TransformNormal = function (vector, transformation) {
  657. var result = Vector3.Zero();
  658. Vector3.TransformNormalToRef(vector, transformation, result);
  659. return result;
  660. };
  661. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  662. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  663. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  664. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  665. };
  666. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  667. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  668. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  669. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  670. };
  671. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  672. var squared = amount * amount;
  673. var cubed = amount * squared;
  674. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  675. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  676. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  677. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  678. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  679. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  680. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  681. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  682. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  683. return new Vector3(x, y, z);
  684. };
  685. Vector3.Clamp = function (value, min, max) {
  686. var x = value.x;
  687. x = (x > max.x) ? max.x : x;
  688. x = (x < min.x) ? min.x : x;
  689. var y = value.y;
  690. y = (y > max.y) ? max.y : y;
  691. y = (y < min.y) ? min.y : y;
  692. var z = value.z;
  693. z = (z > max.z) ? max.z : z;
  694. z = (z < min.z) ? min.z : z;
  695. return new Vector3(x, y, z);
  696. };
  697. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  698. var squared = amount * amount;
  699. var cubed = amount * squared;
  700. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  701. var part2 = (-2.0 * cubed) + (3.0 * squared);
  702. var part3 = (cubed - (2.0 * squared)) + amount;
  703. var part4 = cubed - squared;
  704. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  705. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  706. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  707. return new Vector3(x, y, z);
  708. };
  709. Vector3.Lerp = function (start, end, amount) {
  710. var x = start.x + ((end.x - start.x) * amount);
  711. var y = start.y + ((end.y - start.y) * amount);
  712. var z = start.z + ((end.z - start.z) * amount);
  713. return new Vector3(x, y, z);
  714. };
  715. Vector3.Dot = function (left, right) {
  716. return (left.x * right.x + left.y * right.y + left.z * right.z);
  717. };
  718. Vector3.Cross = function (left, right) {
  719. var result = Vector3.Zero();
  720. Vector3.CrossToRef(left, right, result);
  721. return result;
  722. };
  723. Vector3.CrossToRef = function (left, right, result) {
  724. result.x = left.y * right.z - left.z * right.y;
  725. result.y = left.z * right.x - left.x * right.z;
  726. result.z = left.x * right.y - left.y * right.x;
  727. };
  728. Vector3.Normalize = function (vector) {
  729. var result = Vector3.Zero();
  730. Vector3.NormalizeToRef(vector, result);
  731. return result;
  732. };
  733. Vector3.NormalizeToRef = function (vector, result) {
  734. result.copyFrom(vector);
  735. result.normalize();
  736. };
  737. Vector3.Project = function (vector, world, transform, viewport) {
  738. var cw = viewport.width;
  739. var ch = viewport.height;
  740. var cx = viewport.x;
  741. var cy = viewport.y;
  742. 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);
  743. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  744. return Vector3.TransformCoordinates(vector, finalMatrix);
  745. };
  746. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  747. var matrix = world.multiply(transform);
  748. matrix.invert();
  749. source.x = source.x / viewportWidth * 2 - 1;
  750. source.y = -(source.y / viewportHeight * 2 - 1);
  751. var vector = Vector3.TransformCoordinates(source, matrix);
  752. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  753. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  754. vector = vector.scale(1.0 / num);
  755. }
  756. return vector;
  757. };
  758. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  759. var matrix = world.multiply(view).multiply(projection);
  760. matrix.invert();
  761. source.x = source.x / viewportWidth * 2 - 1;
  762. source.y = -(source.y / viewportHeight * 2 - 1);
  763. var vector = Vector3.TransformCoordinates(source, matrix);
  764. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  765. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  766. vector = vector.scale(1.0 / num);
  767. }
  768. return vector;
  769. };
  770. Vector3.Minimize = function (left, right) {
  771. var min = left.clone();
  772. min.MinimizeInPlace(right);
  773. return min;
  774. };
  775. Vector3.Maximize = function (left, right) {
  776. var max = left.clone();
  777. max.MaximizeInPlace(right);
  778. return max;
  779. };
  780. Vector3.Distance = function (value1, value2) {
  781. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  782. };
  783. Vector3.DistanceSquared = function (value1, value2) {
  784. var x = value1.x - value2.x;
  785. var y = value1.y - value2.y;
  786. var z = value1.z - value2.z;
  787. return (x * x) + (y * y) + (z * z);
  788. };
  789. Vector3.Center = function (value1, value2) {
  790. var center = value1.add(value2);
  791. center.scaleInPlace(0.5);
  792. return center;
  793. };
  794. /**
  795. * Given three orthogonal left-handed oriented Vector3 axis in space (target system),
  796. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  797. * to something in order to rotate it from its local system to the given target system.
  798. */
  799. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  800. var u = Vector3.Normalize(axis1);
  801. var v = Vector3.Normalize(axis2);
  802. var w = Vector3.Normalize(axis3);
  803. // world axis
  804. var X = Axis.X;
  805. var Y = Axis.Y;
  806. var Z = Axis.Z;
  807. // equation unknowns and vars
  808. var yaw = 0.0;
  809. var pitch = 0.0;
  810. var roll = 0.0;
  811. var x = 0.0;
  812. var y = 0.0;
  813. var z = 0.0;
  814. var t = 0.0;
  815. var sign = -1.0;
  816. var pi = Math.PI;
  817. var nbRevert = 0;
  818. var cross;
  819. var dot = 0.0;
  820. // step 1 : rotation around w
  821. // Rv3(u) = u1, and u1 belongs to plane xOz
  822. // Rv3(w) = w1 = w invariant
  823. var u1;
  824. var v1;
  825. if (w.z == 0) {
  826. z = 1.0;
  827. }
  828. else if (w.x == 0) {
  829. x = 1.0;
  830. }
  831. else {
  832. t = w.z / w.x;
  833. x = -t * Math.sqrt(1 / (1 + t * t));
  834. z = Math.sqrt(1 / (1 + t * t));
  835. }
  836. u1 = new Vector3(x, y, z);
  837. v1 = Vector3.Cross(w, u1); // v1 image of v through rotation around w
  838. cross = Vector3.Cross(u, u1); // returns same direction as w (=local z) if positive angle : cross(source, image)
  839. if (Vector3.Dot(w, cross) < 0) {
  840. sign = 1;
  841. }
  842. dot = Vector3.Dot(u, u1);
  843. roll = Math.acos(dot) * sign;
  844. if (Vector3.Dot(u1, X) < 0) {
  845. roll = Math.PI + roll;
  846. u1 = u1.scaleInPlace(-1);
  847. v1 = v1.scaleInPlace(-1);
  848. nbRevert++;
  849. }
  850. // step 2 : rotate around u1
  851. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  852. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  853. var w2;
  854. var v2;
  855. x = 0.0;
  856. y = 0.0;
  857. z = 0.0;
  858. sign = -1;
  859. if (w.z == 0) {
  860. x = 1.0;
  861. }
  862. else {
  863. t = u1.z / u1.x;
  864. x = -t * Math.sqrt(1 / (1 + t * t));
  865. z = Math.sqrt(1 / (1 + t * t));
  866. }
  867. w2 = new Vector3(x, y, z);
  868. v2 = Vector3.Cross(w2, u1); // v2 image of v1 through rotation around u1
  869. cross = Vector3.Cross(w, w2); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  870. if (Vector3.Dot(u1, cross) < 0) {
  871. sign = 1;
  872. }
  873. dot = Vector3.Dot(w, w2);
  874. pitch = Math.acos(dot) * sign;
  875. if (Vector3.Dot(v2, Y) < 0) {
  876. pitch = Math.PI + pitch;
  877. v2 = v2.scaleInPlace(-1);
  878. w2 = w2.scaleInPlace(-1);
  879. nbRevert++;
  880. }
  881. // step 3 : rotate around v2
  882. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  883. sign = -1;
  884. cross = Vector3.Cross(X, u1); // returns same direction as Y if positive angle : cross(source, image)
  885. if (Vector3.Dot(cross, Y) < 0) {
  886. sign = 1;
  887. }
  888. dot = Vector3.Dot(u1, X);
  889. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  890. if (dot < 0 && nbRevert < 2) {
  891. yaw = Math.PI + yaw;
  892. }
  893. return new Vector3(pitch, yaw, roll);
  894. };
  895. return Vector3;
  896. })();
  897. BABYLON.Vector3 = Vector3;
  898. //Vector4 class created for EulerAngle class conversion to Quaternion
  899. var Vector4 = (function () {
  900. function Vector4(x, y, z, w) {
  901. this.x = x;
  902. this.y = y;
  903. this.z = z;
  904. this.w = w;
  905. }
  906. Vector4.prototype.toString = function () {
  907. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  908. };
  909. // Operators
  910. Vector4.prototype.asArray = function () {
  911. var result = [];
  912. this.toArray(result, 0);
  913. return result;
  914. };
  915. Vector4.prototype.toArray = function (array, index) {
  916. if (index === undefined) {
  917. index = 0;
  918. }
  919. array[index] = this.x;
  920. array[index + 1] = this.y;
  921. array[index + 2] = this.z;
  922. array[index + 3] = this.w;
  923. return this;
  924. };
  925. Vector4.prototype.addInPlace = function (otherVector) {
  926. this.x += otherVector.x;
  927. this.y += otherVector.y;
  928. this.z += otherVector.z;
  929. this.w += otherVector.w;
  930. return this;
  931. };
  932. Vector4.prototype.add = function (otherVector) {
  933. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  934. };
  935. Vector4.prototype.addToRef = function (otherVector, result) {
  936. result.x = this.x + otherVector.x;
  937. result.y = this.y + otherVector.y;
  938. result.z = this.z + otherVector.z;
  939. result.w = this.w + otherVector.w;
  940. return this;
  941. };
  942. Vector4.prototype.subtractInPlace = function (otherVector) {
  943. this.x -= otherVector.x;
  944. this.y -= otherVector.y;
  945. this.z -= otherVector.z;
  946. this.w -= otherVector.w;
  947. return this;
  948. };
  949. Vector4.prototype.subtract = function (otherVector) {
  950. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  951. };
  952. Vector4.prototype.subtractToRef = function (otherVector, result) {
  953. result.x = this.x - otherVector.x;
  954. result.y = this.y - otherVector.y;
  955. result.z = this.z - otherVector.z;
  956. result.w = this.w - otherVector.w;
  957. return this;
  958. };
  959. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  960. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  961. };
  962. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  963. result.x = this.x - x;
  964. result.y = this.y - y;
  965. result.z = this.z - z;
  966. result.w = this.w - w;
  967. return this;
  968. };
  969. Vector4.prototype.negate = function () {
  970. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  971. };
  972. Vector4.prototype.scaleInPlace = function (scale) {
  973. this.x *= scale;
  974. this.y *= scale;
  975. this.z *= scale;
  976. this.w *= scale;
  977. return this;
  978. };
  979. Vector4.prototype.scale = function (scale) {
  980. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  981. };
  982. Vector4.prototype.scaleToRef = function (scale, result) {
  983. result.x = this.x * scale;
  984. result.y = this.y * scale;
  985. result.z = this.z * scale;
  986. result.w = this.w * scale;
  987. };
  988. Vector4.prototype.equals = function (otherVector) {
  989. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  990. };
  991. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  992. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon &&
  993. Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon &&
  994. Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon &&
  995. Math.abs(this.w - otherVector.w) < BABYLON.Engine.Epsilon;
  996. };
  997. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  998. return this.x === x && this.y === y && this.z === z && this.w === w;
  999. };
  1000. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1001. this.x *= otherVector.x;
  1002. this.y *= otherVector.y;
  1003. this.z *= otherVector.z;
  1004. this.w *= otherVector.w;
  1005. return this;
  1006. };
  1007. Vector4.prototype.multiply = function (otherVector) {
  1008. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1009. };
  1010. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1011. result.x = this.x * otherVector.x;
  1012. result.y = this.y * otherVector.y;
  1013. result.z = this.z * otherVector.z;
  1014. result.w = this.w * otherVector.w;
  1015. return this;
  1016. };
  1017. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1018. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1019. };
  1020. Vector4.prototype.divide = function (otherVector) {
  1021. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1022. };
  1023. Vector4.prototype.divideToRef = function (otherVector, result) {
  1024. result.x = this.x / otherVector.x;
  1025. result.y = this.y / otherVector.y;
  1026. result.z = this.z / otherVector.z;
  1027. result.w = this.w / otherVector.w;
  1028. return this;
  1029. };
  1030. Vector4.prototype.MinimizeInPlace = function (other) {
  1031. if (other.x < this.x)
  1032. this.x = other.x;
  1033. if (other.y < this.y)
  1034. this.y = other.y;
  1035. if (other.z < this.z)
  1036. this.z = other.z;
  1037. if (other.w < this.w)
  1038. this.w = other.w;
  1039. return this;
  1040. };
  1041. Vector4.prototype.MaximizeInPlace = function (other) {
  1042. if (other.x > this.x)
  1043. this.x = other.x;
  1044. if (other.y > this.y)
  1045. this.y = other.y;
  1046. if (other.z > this.z)
  1047. this.z = other.z;
  1048. if (other.w > this.w)
  1049. this.w = other.w;
  1050. return this;
  1051. };
  1052. // Properties
  1053. Vector4.prototype.length = function () {
  1054. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1055. };
  1056. Vector4.prototype.lengthSquared = function () {
  1057. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1058. };
  1059. // Methods
  1060. Vector4.prototype.normalize = function () {
  1061. var len = this.length();
  1062. if (len === 0)
  1063. return this;
  1064. var num = 1.0 / len;
  1065. this.x *= num;
  1066. this.y *= num;
  1067. this.z *= num;
  1068. this.w *= num;
  1069. return this;
  1070. };
  1071. Vector4.prototype.clone = function () {
  1072. return new Vector4(this.x, this.y, this.z, this.w);
  1073. };
  1074. Vector4.prototype.copyFrom = function (source) {
  1075. this.x = source.x;
  1076. this.y = source.y;
  1077. this.z = source.z;
  1078. this.w = source.w;
  1079. return this;
  1080. };
  1081. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1082. this.x = x;
  1083. this.y = y;
  1084. this.z = z;
  1085. this.w = w;
  1086. return this;
  1087. };
  1088. // Statics
  1089. Vector4.FromArray = function (array, offset) {
  1090. if (!offset) {
  1091. offset = 0;
  1092. }
  1093. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1094. };
  1095. Vector4.FromArrayToRef = function (array, offset, result) {
  1096. result.x = array[offset];
  1097. result.y = array[offset + 1];
  1098. result.z = array[offset + 2];
  1099. result.w = array[offset + 3];
  1100. };
  1101. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1102. result.x = array[offset];
  1103. result.y = array[offset + 1];
  1104. result.z = array[offset + 2];
  1105. result.w = array[offset + 3];
  1106. };
  1107. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1108. result.x = x;
  1109. result.y = y;
  1110. result.z = z;
  1111. result.w = w;
  1112. };
  1113. Vector4.Zero = function () {
  1114. return new Vector4(0, 0, 0, 0);
  1115. };
  1116. Vector4.Normalize = function (vector) {
  1117. var result = Vector4.Zero();
  1118. Vector4.NormalizeToRef(vector, result);
  1119. return result;
  1120. };
  1121. Vector4.NormalizeToRef = function (vector, result) {
  1122. result.copyFrom(vector);
  1123. result.normalize();
  1124. };
  1125. Vector4.Minimize = function (left, right) {
  1126. var min = left.clone();
  1127. min.MinimizeInPlace(right);
  1128. return min;
  1129. };
  1130. Vector4.Maximize = function (left, right) {
  1131. var max = left.clone();
  1132. max.MaximizeInPlace(right);
  1133. return max;
  1134. };
  1135. Vector4.Distance = function (value1, value2) {
  1136. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1137. };
  1138. Vector4.DistanceSquared = function (value1, value2) {
  1139. var x = value1.x - value2.x;
  1140. var y = value1.y - value2.y;
  1141. var z = value1.z - value2.z;
  1142. var w = value1.w - value2.w;
  1143. return (x * x) + (y * y) + (z * z) + (w * w);
  1144. };
  1145. Vector4.Center = function (value1, value2) {
  1146. var center = value1.add(value2);
  1147. center.scaleInPlace(0.5);
  1148. return center;
  1149. };
  1150. return Vector4;
  1151. })();
  1152. BABYLON.Vector4 = Vector4;
  1153. var Quaternion = (function () {
  1154. function Quaternion(x, y, z, w) {
  1155. if (x === void 0) { x = 0; }
  1156. if (y === void 0) { y = 0; }
  1157. if (z === void 0) { z = 0; }
  1158. if (w === void 0) { w = 1; }
  1159. this.x = x;
  1160. this.y = y;
  1161. this.z = z;
  1162. this.w = w;
  1163. }
  1164. Quaternion.prototype.toString = function () {
  1165. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1166. };
  1167. Quaternion.prototype.asArray = function () {
  1168. return [this.x, this.y, this.z, this.w];
  1169. };
  1170. Quaternion.prototype.equals = function (otherQuaternion) {
  1171. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1172. };
  1173. Quaternion.prototype.clone = function () {
  1174. return new Quaternion(this.x, this.y, this.z, this.w);
  1175. };
  1176. Quaternion.prototype.copyFrom = function (other) {
  1177. this.x = other.x;
  1178. this.y = other.y;
  1179. this.z = other.z;
  1180. this.w = other.w;
  1181. return this;
  1182. };
  1183. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1184. this.x = x;
  1185. this.y = y;
  1186. this.z = z;
  1187. this.w = w;
  1188. return this;
  1189. };
  1190. Quaternion.prototype.add = function (other) {
  1191. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1192. };
  1193. Quaternion.prototype.subtract = function (other) {
  1194. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1195. };
  1196. Quaternion.prototype.scale = function (value) {
  1197. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1198. };
  1199. Quaternion.prototype.multiply = function (q1) {
  1200. var result = new Quaternion(0, 0, 0, 1.0);
  1201. this.multiplyToRef(q1, result);
  1202. return result;
  1203. };
  1204. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1205. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1206. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1207. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1208. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1209. result.copyFromFloats(x, y, z, w);
  1210. return this;
  1211. };
  1212. Quaternion.prototype.length = function () {
  1213. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1214. };
  1215. Quaternion.prototype.normalize = function () {
  1216. var length = 1.0 / this.length();
  1217. this.x *= length;
  1218. this.y *= length;
  1219. this.z *= length;
  1220. this.w *= length;
  1221. return this;
  1222. };
  1223. Quaternion.prototype.toEulerAngles = function () {
  1224. var result = Vector3.Zero();
  1225. this.toEulerAnglesToRef(result);
  1226. return result;
  1227. };
  1228. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1229. //result is an EulerAngles in the in the z-x-z convention
  1230. var qx = this.x;
  1231. var qy = this.y;
  1232. var qz = this.z;
  1233. var qw = this.w;
  1234. var qxy = qx * qy;
  1235. var qxz = qx * qz;
  1236. var qwy = qw * qy;
  1237. var qwz = qw * qz;
  1238. var qwx = qw * qx;
  1239. var qyz = qy * qz;
  1240. var sqx = qx * qx;
  1241. var sqy = qy * qy;
  1242. var determinant = sqx + sqy;
  1243. if (determinant !== 0.000 && determinant !== 1.000) {
  1244. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1245. result.y = Math.acos(1 - 2 * determinant);
  1246. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1247. }
  1248. else {
  1249. if (determinant === 0.0) {
  1250. result.x = 0.0;
  1251. result.y = 0.0;
  1252. 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)
  1253. }
  1254. else {
  1255. 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)
  1256. result.y = Math.PI;
  1257. result.z = 0.0;
  1258. }
  1259. }
  1260. return this;
  1261. };
  1262. Quaternion.prototype.toRotationMatrix = function (result) {
  1263. var xx = this.x * this.x;
  1264. var yy = this.y * this.y;
  1265. var zz = this.z * this.z;
  1266. var xy = this.x * this.y;
  1267. var zw = this.z * this.w;
  1268. var zx = this.z * this.x;
  1269. var yw = this.y * this.w;
  1270. var yz = this.y * this.z;
  1271. var xw = this.x * this.w;
  1272. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1273. result.m[1] = 2.0 * (xy + zw);
  1274. result.m[2] = 2.0 * (zx - yw);
  1275. result.m[3] = 0;
  1276. result.m[4] = 2.0 * (xy - zw);
  1277. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1278. result.m[6] = 2.0 * (yz + xw);
  1279. result.m[7] = 0;
  1280. result.m[8] = 2.0 * (zx + yw);
  1281. result.m[9] = 2.0 * (yz - xw);
  1282. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1283. result.m[11] = 0;
  1284. result.m[12] = 0;
  1285. result.m[13] = 0;
  1286. result.m[14] = 0;
  1287. result.m[15] = 1.0;
  1288. return this;
  1289. };
  1290. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1291. Quaternion.FromRotationMatrixToRef(matrix, this);
  1292. return this;
  1293. };
  1294. // Statics
  1295. Quaternion.FromRotationMatrix = function (matrix) {
  1296. var result = new Quaternion();
  1297. Quaternion.FromRotationMatrixToRef(matrix, result);
  1298. return result;
  1299. };
  1300. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1301. var data = matrix.m;
  1302. var m11 = data[0], m12 = data[4], m13 = data[8];
  1303. var m21 = data[1], m22 = data[5], m23 = data[9];
  1304. var m31 = data[2], m32 = data[6], m33 = data[10];
  1305. var trace = m11 + m22 + m33;
  1306. var s;
  1307. if (trace > 0) {
  1308. s = 0.5 / Math.sqrt(trace + 1.0);
  1309. result.w = 0.25 / s;
  1310. result.x = (m32 - m23) * s;
  1311. result.y = (m13 - m31) * s;
  1312. result.z = (m21 - m12) * s;
  1313. }
  1314. else if (m11 > m22 && m11 > m33) {
  1315. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1316. result.w = (m32 - m23) / s;
  1317. result.x = 0.25 * s;
  1318. result.y = (m12 + m21) / s;
  1319. result.z = (m13 + m31) / s;
  1320. }
  1321. else if (m22 > m33) {
  1322. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1323. result.w = (m13 - m31) / s;
  1324. result.x = (m12 + m21) / s;
  1325. result.y = 0.25 * s;
  1326. result.z = (m23 + m32) / s;
  1327. }
  1328. else {
  1329. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1330. result.w = (m21 - m12) / s;
  1331. result.x = (m13 + m31) / s;
  1332. result.y = (m23 + m32) / s;
  1333. result.z = 0.25 * s;
  1334. }
  1335. };
  1336. Quaternion.Inverse = function (q) {
  1337. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1338. };
  1339. Quaternion.Identity = function () {
  1340. return new Quaternion(0, 0, 0, 1);
  1341. };
  1342. Quaternion.RotationAxis = function (axis, angle) {
  1343. var result = new Quaternion();
  1344. var sin = Math.sin(angle / 2);
  1345. result.w = Math.cos(angle / 2);
  1346. result.x = axis.x * sin;
  1347. result.y = axis.y * sin;
  1348. result.z = axis.z * sin;
  1349. return result;
  1350. };
  1351. Quaternion.FromArray = function (array, offset) {
  1352. if (!offset) {
  1353. offset = 0;
  1354. }
  1355. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1356. };
  1357. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1358. var result = new Quaternion();
  1359. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1360. return result;
  1361. };
  1362. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1363. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1364. var halfRoll = roll * 0.5;
  1365. var halfPitch = pitch * 0.5;
  1366. var halfYaw = yaw * 0.5;
  1367. var sinRoll = Math.sin(halfRoll);
  1368. var cosRoll = Math.cos(halfRoll);
  1369. var sinPitch = Math.sin(halfPitch);
  1370. var cosPitch = Math.cos(halfPitch);
  1371. var sinYaw = Math.sin(halfYaw);
  1372. var cosYaw = Math.cos(halfYaw);
  1373. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1374. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1375. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1376. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1377. };
  1378. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1379. var result = new Quaternion();
  1380. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1381. return result;
  1382. };
  1383. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1384. // Produces a quaternion from Euler angles in the z-x-z orientation
  1385. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1386. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1387. var halfBeta = beta * 0.5;
  1388. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1389. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1390. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1391. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1392. };
  1393. Quaternion.Slerp = function (left, right, amount) {
  1394. var num2;
  1395. var num3;
  1396. var num = amount;
  1397. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1398. var flag = false;
  1399. if (num4 < 0) {
  1400. flag = true;
  1401. num4 = -num4;
  1402. }
  1403. if (num4 > 0.999999) {
  1404. num3 = 1 - num;
  1405. num2 = flag ? -num : num;
  1406. }
  1407. else {
  1408. var num5 = Math.acos(num4);
  1409. var num6 = (1.0 / Math.sin(num5));
  1410. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1411. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1412. }
  1413. 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));
  1414. };
  1415. return Quaternion;
  1416. })();
  1417. BABYLON.Quaternion = Quaternion;
  1418. var Matrix = (function () {
  1419. function Matrix() {
  1420. this.m = new Float32Array(16);
  1421. }
  1422. // Properties
  1423. Matrix.prototype.isIdentity = function () {
  1424. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1425. return false;
  1426. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1427. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1428. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1429. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1430. return false;
  1431. return true;
  1432. };
  1433. Matrix.prototype.determinant = function () {
  1434. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1435. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1436. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1437. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1438. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1439. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1440. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1441. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1442. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1443. };
  1444. // Methods
  1445. Matrix.prototype.toArray = function () {
  1446. return this.m;
  1447. };
  1448. Matrix.prototype.asArray = function () {
  1449. return this.toArray();
  1450. };
  1451. Matrix.prototype.invert = function () {
  1452. this.invertToRef(this);
  1453. return this;
  1454. };
  1455. Matrix.prototype.invertToRef = function (other) {
  1456. var l1 = this.m[0];
  1457. var l2 = this.m[1];
  1458. var l3 = this.m[2];
  1459. var l4 = this.m[3];
  1460. var l5 = this.m[4];
  1461. var l6 = this.m[5];
  1462. var l7 = this.m[6];
  1463. var l8 = this.m[7];
  1464. var l9 = this.m[8];
  1465. var l10 = this.m[9];
  1466. var l11 = this.m[10];
  1467. var l12 = this.m[11];
  1468. var l13 = this.m[12];
  1469. var l14 = this.m[13];
  1470. var l15 = this.m[14];
  1471. var l16 = this.m[15];
  1472. var l17 = (l11 * l16) - (l12 * l15);
  1473. var l18 = (l10 * l16) - (l12 * l14);
  1474. var l19 = (l10 * l15) - (l11 * l14);
  1475. var l20 = (l9 * l16) - (l12 * l13);
  1476. var l21 = (l9 * l15) - (l11 * l13);
  1477. var l22 = (l9 * l14) - (l10 * l13);
  1478. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1479. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1480. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1481. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1482. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1483. var l28 = (l7 * l16) - (l8 * l15);
  1484. var l29 = (l6 * l16) - (l8 * l14);
  1485. var l30 = (l6 * l15) - (l7 * l14);
  1486. var l31 = (l5 * l16) - (l8 * l13);
  1487. var l32 = (l5 * l15) - (l7 * l13);
  1488. var l33 = (l5 * l14) - (l6 * l13);
  1489. var l34 = (l7 * l12) - (l8 * l11);
  1490. var l35 = (l6 * l12) - (l8 * l10);
  1491. var l36 = (l6 * l11) - (l7 * l10);
  1492. var l37 = (l5 * l12) - (l8 * l9);
  1493. var l38 = (l5 * l11) - (l7 * l9);
  1494. var l39 = (l5 * l10) - (l6 * l9);
  1495. other.m[0] = l23 * l27;
  1496. other.m[4] = l24 * l27;
  1497. other.m[8] = l25 * l27;
  1498. other.m[12] = l26 * l27;
  1499. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1500. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1501. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1502. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1503. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1504. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1505. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1506. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1507. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1508. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1509. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1510. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1511. return this;
  1512. };
  1513. Matrix.prototype.invertToRefSIMD = function (other) {
  1514. var src = this.m;
  1515. var dest = other.m;
  1516. var row0, row1, row2, row3;
  1517. var tmp1;
  1518. var minor0, minor1, minor2, minor3;
  1519. var det;
  1520. // Load the 4 rows
  1521. var src0 = SIMD.float32x4.load(src, 0);
  1522. var src1 = SIMD.float32x4.load(src, 4);
  1523. var src2 = SIMD.float32x4.load(src, 8);
  1524. var src3 = SIMD.float32x4.load(src, 12);
  1525. // Transpose the source matrix. Sort of. Not a true transpose operation
  1526. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1527. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1528. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1529. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1530. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1531. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1532. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1533. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1534. // This is a true transposition, but it will lead to an incorrect result
  1535. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1536. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1537. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1538. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1539. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1540. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1541. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1542. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1543. // ----
  1544. tmp1 = SIMD.float32x4.mul(row2, row3);
  1545. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1546. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1547. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1548. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1549. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1550. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1551. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1552. // ----
  1553. tmp1 = SIMD.float32x4.mul(row1, row2);
  1554. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1555. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1556. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1557. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1558. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1559. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1560. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1561. // ----
  1562. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1563. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1564. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1565. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1566. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1567. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1568. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1569. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1570. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1571. // ----
  1572. tmp1 = SIMD.float32x4.mul(row0, row1);
  1573. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1574. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1575. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1576. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1577. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1578. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1579. // ----
  1580. tmp1 = SIMD.float32x4.mul(row0, row3);
  1581. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1582. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1583. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1584. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1585. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1586. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1587. // ----
  1588. tmp1 = SIMD.float32x4.mul(row0, row2);
  1589. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1590. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1591. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1592. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1593. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1594. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1595. // Compute determinant
  1596. det = SIMD.float32x4.mul(row0, minor0);
  1597. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1598. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1599. tmp1 = SIMD.float32x4.reciprocalApproximation(det);
  1600. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1601. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1602. // These shuffles aren't necessary if the faulty transposition is done
  1603. // up at the top of this function.
  1604. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1605. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1606. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1607. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1608. // Compute final values by multiplying with 1/det
  1609. minor0 = SIMD.float32x4.mul(det, minor0);
  1610. minor1 = SIMD.float32x4.mul(det, minor1);
  1611. minor2 = SIMD.float32x4.mul(det, minor2);
  1612. minor3 = SIMD.float32x4.mul(det, minor3);
  1613. SIMD.float32x4.store(dest, 0, minor0);
  1614. SIMD.float32x4.store(dest, 4, minor1);
  1615. SIMD.float32x4.store(dest, 8, minor2);
  1616. SIMD.float32x4.store(dest, 12, minor3);
  1617. return this;
  1618. };
  1619. Matrix.prototype.setTranslation = function (vector3) {
  1620. this.m[12] = vector3.x;
  1621. this.m[13] = vector3.y;
  1622. this.m[14] = vector3.z;
  1623. return this;
  1624. };
  1625. Matrix.prototype.multiply = function (other) {
  1626. var result = new Matrix();
  1627. this.multiplyToRef(other, result);
  1628. return result;
  1629. };
  1630. Matrix.prototype.copyFrom = function (other) {
  1631. for (var index = 0; index < 16; index++) {
  1632. this.m[index] = other.m[index];
  1633. }
  1634. return this;
  1635. };
  1636. Matrix.prototype.copyToArray = function (array, offset) {
  1637. if (offset === void 0) { offset = 0; }
  1638. for (var index = 0; index < 16; index++) {
  1639. array[offset + index] = this.m[index];
  1640. }
  1641. return this;
  1642. };
  1643. Matrix.prototype.multiplyToRef = function (other, result) {
  1644. this.multiplyToArray(other, result.m, 0);
  1645. return this;
  1646. };
  1647. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1648. var tm0 = this.m[0];
  1649. var tm1 = this.m[1];
  1650. var tm2 = this.m[2];
  1651. var tm3 = this.m[3];
  1652. var tm4 = this.m[4];
  1653. var tm5 = this.m[5];
  1654. var tm6 = this.m[6];
  1655. var tm7 = this.m[7];
  1656. var tm8 = this.m[8];
  1657. var tm9 = this.m[9];
  1658. var tm10 = this.m[10];
  1659. var tm11 = this.m[11];
  1660. var tm12 = this.m[12];
  1661. var tm13 = this.m[13];
  1662. var tm14 = this.m[14];
  1663. var tm15 = this.m[15];
  1664. var om0 = other.m[0];
  1665. var om1 = other.m[1];
  1666. var om2 = other.m[2];
  1667. var om3 = other.m[3];
  1668. var om4 = other.m[4];
  1669. var om5 = other.m[5];
  1670. var om6 = other.m[6];
  1671. var om7 = other.m[7];
  1672. var om8 = other.m[8];
  1673. var om9 = other.m[9];
  1674. var om10 = other.m[10];
  1675. var om11 = other.m[11];
  1676. var om12 = other.m[12];
  1677. var om13 = other.m[13];
  1678. var om14 = other.m[14];
  1679. var om15 = other.m[15];
  1680. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1681. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1682. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1683. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1684. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1685. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1686. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1687. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1688. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1689. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1690. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1691. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1692. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1693. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1694. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1695. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1696. return this;
  1697. };
  1698. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1699. if (offset === void 0) { offset = 0; }
  1700. var tm = this.m;
  1701. var om = other.m;
  1702. var om0 = SIMD.float32x4.load(om, 0);
  1703. var om1 = SIMD.float32x4.load(om, 4);
  1704. var om2 = SIMD.float32x4.load(om, 8);
  1705. var om3 = SIMD.float32x4.load(om, 12);
  1706. var tm0 = SIMD.float32x4.load(tm, 0);
  1707. 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)))));
  1708. var tm1 = SIMD.float32x4.load(tm, 4);
  1709. 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)))));
  1710. var tm2 = SIMD.float32x4.load(tm, 8);
  1711. 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)))));
  1712. var tm3 = SIMD.float32x4.load(tm, 12);
  1713. 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)))));
  1714. };
  1715. Matrix.prototype.equals = function (value) {
  1716. return value &&
  1717. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1718. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1719. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1720. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1721. };
  1722. Matrix.prototype.clone = function () {
  1723. 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]);
  1724. };
  1725. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1726. translation.x = this.m[12];
  1727. translation.y = this.m[13];
  1728. translation.z = this.m[14];
  1729. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1730. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1731. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1732. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1733. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1734. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1735. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1736. rotation.x = 0;
  1737. rotation.y = 0;
  1738. rotation.z = 0;
  1739. rotation.w = 1;
  1740. return false;
  1741. }
  1742. 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);
  1743. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1744. return true;
  1745. };
  1746. // Statics
  1747. Matrix.FromArray = function (array, offset) {
  1748. var result = new Matrix();
  1749. if (!offset) {
  1750. offset = 0;
  1751. }
  1752. Matrix.FromArrayToRef(array, offset, result);
  1753. return result;
  1754. };
  1755. Matrix.FromArrayToRef = function (array, offset, result) {
  1756. for (var index = 0; index < 16; index++) {
  1757. result.m[index] = array[index + offset];
  1758. }
  1759. };
  1760. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1761. result.m[0] = initialM11;
  1762. result.m[1] = initialM12;
  1763. result.m[2] = initialM13;
  1764. result.m[3] = initialM14;
  1765. result.m[4] = initialM21;
  1766. result.m[5] = initialM22;
  1767. result.m[6] = initialM23;
  1768. result.m[7] = initialM24;
  1769. result.m[8] = initialM31;
  1770. result.m[9] = initialM32;
  1771. result.m[10] = initialM33;
  1772. result.m[11] = initialM34;
  1773. result.m[12] = initialM41;
  1774. result.m[13] = initialM42;
  1775. result.m[14] = initialM43;
  1776. result.m[15] = initialM44;
  1777. };
  1778. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1779. var result = new Matrix();
  1780. result.m[0] = initialM11;
  1781. result.m[1] = initialM12;
  1782. result.m[2] = initialM13;
  1783. result.m[3] = initialM14;
  1784. result.m[4] = initialM21;
  1785. result.m[5] = initialM22;
  1786. result.m[6] = initialM23;
  1787. result.m[7] = initialM24;
  1788. result.m[8] = initialM31;
  1789. result.m[9] = initialM32;
  1790. result.m[10] = initialM33;
  1791. result.m[11] = initialM34;
  1792. result.m[12] = initialM41;
  1793. result.m[13] = initialM42;
  1794. result.m[14] = initialM43;
  1795. result.m[15] = initialM44;
  1796. return result;
  1797. };
  1798. Matrix.Compose = function (scale, rotation, translation) {
  1799. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1800. var rotationMatrix = Matrix.Identity();
  1801. rotation.toRotationMatrix(rotationMatrix);
  1802. result = result.multiply(rotationMatrix);
  1803. result.setTranslation(translation);
  1804. return result;
  1805. };
  1806. Matrix.Identity = function () {
  1807. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1808. };
  1809. Matrix.IdentityToRef = function (result) {
  1810. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1811. };
  1812. Matrix.Zero = function () {
  1813. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1814. };
  1815. Matrix.RotationX = function (angle) {
  1816. var result = new Matrix();
  1817. Matrix.RotationXToRef(angle, result);
  1818. return result;
  1819. };
  1820. Matrix.Invert = function (source) {
  1821. var result = new Matrix();
  1822. source.invertToRef(result);
  1823. return result;
  1824. };
  1825. Matrix.RotationXToRef = function (angle, result) {
  1826. var s = Math.sin(angle);
  1827. var c = Math.cos(angle);
  1828. result.m[0] = 1.0;
  1829. result.m[15] = 1.0;
  1830. result.m[5] = c;
  1831. result.m[10] = c;
  1832. result.m[9] = -s;
  1833. result.m[6] = s;
  1834. result.m[1] = 0;
  1835. result.m[2] = 0;
  1836. result.m[3] = 0;
  1837. result.m[4] = 0;
  1838. result.m[7] = 0;
  1839. result.m[8] = 0;
  1840. result.m[11] = 0;
  1841. result.m[12] = 0;
  1842. result.m[13] = 0;
  1843. result.m[14] = 0;
  1844. };
  1845. Matrix.RotationY = function (angle) {
  1846. var result = new Matrix();
  1847. Matrix.RotationYToRef(angle, result);
  1848. return result;
  1849. };
  1850. Matrix.RotationYToRef = function (angle, result) {
  1851. var s = Math.sin(angle);
  1852. var c = Math.cos(angle);
  1853. result.m[5] = 1.0;
  1854. result.m[15] = 1.0;
  1855. result.m[0] = c;
  1856. result.m[2] = -s;
  1857. result.m[8] = s;
  1858. result.m[10] = c;
  1859. result.m[1] = 0;
  1860. result.m[3] = 0;
  1861. result.m[4] = 0;
  1862. result.m[6] = 0;
  1863. result.m[7] = 0;
  1864. result.m[9] = 0;
  1865. result.m[11] = 0;
  1866. result.m[12] = 0;
  1867. result.m[13] = 0;
  1868. result.m[14] = 0;
  1869. };
  1870. Matrix.RotationZ = function (angle) {
  1871. var result = new Matrix();
  1872. Matrix.RotationZToRef(angle, result);
  1873. return result;
  1874. };
  1875. Matrix.RotationZToRef = function (angle, result) {
  1876. var s = Math.sin(angle);
  1877. var c = Math.cos(angle);
  1878. result.m[10] = 1.0;
  1879. result.m[15] = 1.0;
  1880. result.m[0] = c;
  1881. result.m[1] = s;
  1882. result.m[4] = -s;
  1883. result.m[5] = c;
  1884. result.m[2] = 0;
  1885. result.m[3] = 0;
  1886. result.m[6] = 0;
  1887. result.m[7] = 0;
  1888. result.m[8] = 0;
  1889. result.m[9] = 0;
  1890. result.m[11] = 0;
  1891. result.m[12] = 0;
  1892. result.m[13] = 0;
  1893. result.m[14] = 0;
  1894. };
  1895. Matrix.RotationAxis = function (axis, angle) {
  1896. var s = Math.sin(-angle);
  1897. var c = Math.cos(-angle);
  1898. var c1 = 1 - c;
  1899. axis.normalize();
  1900. var result = Matrix.Zero();
  1901. result.m[0] = (axis.x * axis.x) * c1 + c;
  1902. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1903. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1904. result.m[3] = 0.0;
  1905. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1906. result.m[5] = (axis.y * axis.y) * c1 + c;
  1907. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1908. result.m[7] = 0.0;
  1909. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1910. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1911. result.m[10] = (axis.z * axis.z) * c1 + c;
  1912. result.m[11] = 0.0;
  1913. result.m[15] = 1.0;
  1914. return result;
  1915. };
  1916. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1917. var result = new Matrix();
  1918. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1919. return result;
  1920. };
  1921. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1922. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1923. this._tempQuaternion.toRotationMatrix(result);
  1924. };
  1925. Matrix.Scaling = function (x, y, z) {
  1926. var result = Matrix.Zero();
  1927. Matrix.ScalingToRef(x, y, z, result);
  1928. return result;
  1929. };
  1930. Matrix.ScalingToRef = function (x, y, z, result) {
  1931. result.m[0] = x;
  1932. result.m[1] = 0;
  1933. result.m[2] = 0;
  1934. result.m[3] = 0;
  1935. result.m[4] = 0;
  1936. result.m[5] = y;
  1937. result.m[6] = 0;
  1938. result.m[7] = 0;
  1939. result.m[8] = 0;
  1940. result.m[9] = 0;
  1941. result.m[10] = z;
  1942. result.m[11] = 0;
  1943. result.m[12] = 0;
  1944. result.m[13] = 0;
  1945. result.m[14] = 0;
  1946. result.m[15] = 1.0;
  1947. };
  1948. Matrix.Translation = function (x, y, z) {
  1949. var result = Matrix.Identity();
  1950. Matrix.TranslationToRef(x, y, z, result);
  1951. return result;
  1952. };
  1953. Matrix.TranslationToRef = function (x, y, z, result) {
  1954. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1955. };
  1956. Matrix.LookAtLH = function (eye, target, up) {
  1957. var result = Matrix.Zero();
  1958. Matrix.LookAtLHToRef(eye, target, up, result);
  1959. return result;
  1960. };
  1961. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1962. // Z axis
  1963. target.subtractToRef(eye, this._zAxis);
  1964. this._zAxis.normalize();
  1965. // X axis
  1966. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1967. this._xAxis.normalize();
  1968. // Y axis
  1969. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1970. this._yAxis.normalize();
  1971. // Eye angles
  1972. var ex = -Vector3.Dot(this._xAxis, eye);
  1973. var ey = -Vector3.Dot(this._yAxis, eye);
  1974. var ez = -Vector3.Dot(this._zAxis, eye);
  1975. 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);
  1976. };
  1977. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  1978. var out = result.m;
  1979. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  1980. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  1981. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  1982. // cc.kmVec3Subtract(f, pCenter, pEye);
  1983. var f = SIMD.float32x4.sub(center, eye);
  1984. // cc.kmVec3Normalize(f, f);
  1985. var tmp = SIMD.float32x4.mul(f, f);
  1986. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1987. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1988. // cc.kmVec3Assign(up, pUp);
  1989. // cc.kmVec3Normalize(up, up);
  1990. tmp = SIMD.float32x4.mul(up, up);
  1991. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1992. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1993. // cc.kmVec3Cross(s, f, up);
  1994. 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)));
  1995. // cc.kmVec3Normalize(s, s);
  1996. tmp = SIMD.float32x4.mul(s, s);
  1997. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1998. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  1999. // cc.kmVec3Cross(u, s, f);
  2000. 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)));
  2001. // cc.kmVec3Normalize(s, s);
  2002. tmp = SIMD.float32x4.mul(s, s);
  2003. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  2004. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
  2005. var zero = SIMD.float32x4.splat(0.0);
  2006. s = SIMD.float32x4.neg(s);
  2007. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  2008. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  2009. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2010. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  2011. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  2012. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  2013. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  2014. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  2015. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  2016. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  2017. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  2018. var b3 = SIMD.float32x4.neg(eye);
  2019. b3 = SIMD.float32x4.withW(b3, 1.0);
  2020. 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)))));
  2021. 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)))));
  2022. 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)))));
  2023. 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)))));
  2024. };
  2025. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2026. var matrix = Matrix.Zero();
  2027. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2028. return matrix;
  2029. };
  2030. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2031. var hw = 2.0 / width;
  2032. var hh = 2.0 / height;
  2033. var id = 1.0 / (zfar - znear);
  2034. var nid = znear / (znear - zfar);
  2035. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  2036. };
  2037. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2038. var matrix = Matrix.Zero();
  2039. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2040. return matrix;
  2041. };
  2042. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2043. result.m[0] = 2.0 / (right - left);
  2044. result.m[1] = result.m[2] = result.m[3] = 0;
  2045. result.m[5] = 2.0 / (top - bottom);
  2046. result.m[4] = result.m[6] = result.m[7] = 0;
  2047. result.m[10] = -1.0 / (znear - zfar);
  2048. result.m[8] = result.m[9] = result.m[11] = 0;
  2049. result.m[12] = (left + right) / (left - right);
  2050. result.m[13] = (top + bottom) / (bottom - top);
  2051. result.m[14] = znear / (znear - zfar);
  2052. result.m[15] = 1.0;
  2053. };
  2054. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2055. var matrix = Matrix.Zero();
  2056. matrix.m[0] = (2.0 * znear) / width;
  2057. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  2058. matrix.m[5] = (2.0 * znear) / height;
  2059. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  2060. matrix.m[10] = -zfar / (znear - zfar);
  2061. matrix.m[8] = matrix.m[9] = 0.0;
  2062. matrix.m[11] = 1.0;
  2063. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  2064. matrix.m[14] = (znear * zfar) / (znear - zfar);
  2065. return matrix;
  2066. };
  2067. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2068. var matrix = Matrix.Zero();
  2069. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2070. return matrix;
  2071. };
  2072. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  2073. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  2074. var tan = 1.0 / (Math.tan(fov * 0.5));
  2075. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  2076. if (v_fixed) {
  2077. result.m[0] = tan / aspect;
  2078. }
  2079. else {
  2080. result.m[0] = tan;
  2081. }
  2082. result.m[1] = result.m[2] = result.m[3] = 0.0;
  2083. if (v_fixed) {
  2084. result.m[5] = tan;
  2085. }
  2086. else {
  2087. result.m[5] = tan * aspect;
  2088. }
  2089. result.m[4] = result.m[6] = result.m[7] = 0.0;
  2090. result.m[8] = result.m[9] = 0.0;
  2091. result.m[10] = -zfar / (znear - zfar);
  2092. result.m[11] = 1.0;
  2093. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2094. result.m[14] = (znear * zfar) / (znear - zfar);
  2095. };
  2096. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2097. var cw = viewport.width;
  2098. var ch = viewport.height;
  2099. var cx = viewport.x;
  2100. var cy = viewport.y;
  2101. 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);
  2102. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2103. };
  2104. Matrix.Transpose = function (matrix) {
  2105. var result = new Matrix();
  2106. result.m[0] = matrix.m[0];
  2107. result.m[1] = matrix.m[4];
  2108. result.m[2] = matrix.m[8];
  2109. result.m[3] = matrix.m[12];
  2110. result.m[4] = matrix.m[1];
  2111. result.m[5] = matrix.m[5];
  2112. result.m[6] = matrix.m[9];
  2113. result.m[7] = matrix.m[13];
  2114. result.m[8] = matrix.m[2];
  2115. result.m[9] = matrix.m[6];
  2116. result.m[10] = matrix.m[10];
  2117. result.m[11] = matrix.m[14];
  2118. result.m[12] = matrix.m[3];
  2119. result.m[13] = matrix.m[7];
  2120. result.m[14] = matrix.m[11];
  2121. result.m[15] = matrix.m[15];
  2122. return result;
  2123. };
  2124. Matrix.Reflection = function (plane) {
  2125. var matrix = new Matrix();
  2126. Matrix.ReflectionToRef(plane, matrix);
  2127. return matrix;
  2128. };
  2129. Matrix.ReflectionToRef = function (plane, result) {
  2130. plane.normalize();
  2131. var x = plane.normal.x;
  2132. var y = plane.normal.y;
  2133. var z = plane.normal.z;
  2134. var temp = -2 * x;
  2135. var temp2 = -2 * y;
  2136. var temp3 = -2 * z;
  2137. result.m[0] = (temp * x) + 1;
  2138. result.m[1] = temp2 * x;
  2139. result.m[2] = temp3 * x;
  2140. result.m[3] = 0.0;
  2141. result.m[4] = temp * y;
  2142. result.m[5] = (temp2 * y) + 1;
  2143. result.m[6] = temp3 * y;
  2144. result.m[7] = 0.0;
  2145. result.m[8] = temp * z;
  2146. result.m[9] = temp2 * z;
  2147. result.m[10] = (temp3 * z) + 1;
  2148. result.m[11] = 0.0;
  2149. result.m[12] = temp * plane.d;
  2150. result.m[13] = temp2 * plane.d;
  2151. result.m[14] = temp3 * plane.d;
  2152. result.m[15] = 1.0;
  2153. };
  2154. Matrix._tempQuaternion = new Quaternion();
  2155. Matrix._xAxis = Vector3.Zero();
  2156. Matrix._yAxis = Vector3.Zero();
  2157. Matrix._zAxis = Vector3.Zero();
  2158. return Matrix;
  2159. })();
  2160. BABYLON.Matrix = Matrix;
  2161. var Plane = (function () {
  2162. function Plane(a, b, c, d) {
  2163. this.normal = new Vector3(a, b, c);
  2164. this.d = d;
  2165. }
  2166. Plane.prototype.asArray = function () {
  2167. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2168. };
  2169. // Methods
  2170. Plane.prototype.clone = function () {
  2171. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2172. };
  2173. Plane.prototype.normalize = function () {
  2174. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2175. var magnitude = 0;
  2176. if (norm !== 0) {
  2177. magnitude = 1.0 / norm;
  2178. }
  2179. this.normal.x *= magnitude;
  2180. this.normal.y *= magnitude;
  2181. this.normal.z *= magnitude;
  2182. this.d *= magnitude;
  2183. return this;
  2184. };
  2185. Plane.prototype.transform = function (transformation) {
  2186. var transposedMatrix = Matrix.Transpose(transformation);
  2187. var x = this.normal.x;
  2188. var y = this.normal.y;
  2189. var z = this.normal.z;
  2190. var d = this.d;
  2191. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2192. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2193. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2194. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2195. return new Plane(normalX, normalY, normalZ, finalD);
  2196. };
  2197. Plane.prototype.dotCoordinate = function (point) {
  2198. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2199. };
  2200. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2201. var x1 = point2.x - point1.x;
  2202. var y1 = point2.y - point1.y;
  2203. var z1 = point2.z - point1.z;
  2204. var x2 = point3.x - point1.x;
  2205. var y2 = point3.y - point1.y;
  2206. var z2 = point3.z - point1.z;
  2207. var yz = (y1 * z2) - (z1 * y2);
  2208. var xz = (z1 * x2) - (x1 * z2);
  2209. var xy = (x1 * y2) - (y1 * x2);
  2210. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2211. var invPyth;
  2212. if (pyth !== 0) {
  2213. invPyth = 1.0 / pyth;
  2214. }
  2215. else {
  2216. invPyth = 0;
  2217. }
  2218. this.normal.x = yz * invPyth;
  2219. this.normal.y = xz * invPyth;
  2220. this.normal.z = xy * invPyth;
  2221. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2222. return this;
  2223. };
  2224. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2225. var dot = Vector3.Dot(this.normal, direction);
  2226. return (dot <= epsilon);
  2227. };
  2228. Plane.prototype.signedDistanceTo = function (point) {
  2229. return Vector3.Dot(point, this.normal) + this.d;
  2230. };
  2231. // Statics
  2232. Plane.FromArray = function (array) {
  2233. return new Plane(array[0], array[1], array[2], array[3]);
  2234. };
  2235. Plane.FromPoints = function (point1, point2, point3) {
  2236. var result = new Plane(0, 0, 0, 0);
  2237. result.copyFromPoints(point1, point2, point3);
  2238. return result;
  2239. };
  2240. Plane.FromPositionAndNormal = function (origin, normal) {
  2241. var result = new Plane(0, 0, 0, 0);
  2242. normal.normalize();
  2243. result.normal = normal;
  2244. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2245. return result;
  2246. };
  2247. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2248. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2249. return Vector3.Dot(point, normal) + d;
  2250. };
  2251. return Plane;
  2252. })();
  2253. BABYLON.Plane = Plane;
  2254. var Viewport = (function () {
  2255. function Viewport(x, y, width, height) {
  2256. this.x = x;
  2257. this.y = y;
  2258. this.width = width;
  2259. this.height = height;
  2260. }
  2261. Viewport.prototype.toGlobal = function (engine) {
  2262. var width = engine.getRenderWidth();
  2263. var height = engine.getRenderHeight();
  2264. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2265. };
  2266. return Viewport;
  2267. })();
  2268. BABYLON.Viewport = Viewport;
  2269. var Frustum = (function () {
  2270. function Frustum() {
  2271. }
  2272. Frustum.GetPlanes = function (transform) {
  2273. var frustumPlanes = [];
  2274. for (var index = 0; index < 6; index++) {
  2275. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2276. }
  2277. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2278. return frustumPlanes;
  2279. };
  2280. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2281. // Near
  2282. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2283. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2284. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  2285. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2286. frustumPlanes[0].normalize();
  2287. // Far
  2288. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2289. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2290. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2291. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2292. frustumPlanes[1].normalize();
  2293. // Left
  2294. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2295. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2296. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2297. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2298. frustumPlanes[2].normalize();
  2299. // Right
  2300. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2301. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2302. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2303. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2304. frustumPlanes[3].normalize();
  2305. // Top
  2306. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2307. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2308. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2309. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2310. frustumPlanes[4].normalize();
  2311. // Bottom
  2312. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2313. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2314. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2315. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2316. frustumPlanes[5].normalize();
  2317. };
  2318. return Frustum;
  2319. })();
  2320. BABYLON.Frustum = Frustum;
  2321. var Ray = (function () {
  2322. function Ray(origin, direction, length) {
  2323. if (length === void 0) { length = Number.MAX_VALUE; }
  2324. this.origin = origin;
  2325. this.direction = direction;
  2326. this.length = length;
  2327. }
  2328. // Methods
  2329. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2330. var d = 0.0;
  2331. var maxValue = Number.MAX_VALUE;
  2332. if (Math.abs(this.direction.x) < 0.0000001) {
  2333. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2334. return false;
  2335. }
  2336. }
  2337. else {
  2338. var inv = 1.0 / this.direction.x;
  2339. var min = (minimum.x - this.origin.x) * inv;
  2340. var max = (maximum.x - this.origin.x) * inv;
  2341. if (max === -Infinity) {
  2342. max = Infinity;
  2343. }
  2344. if (min > max) {
  2345. var temp = min;
  2346. min = max;
  2347. max = temp;
  2348. }
  2349. d = Math.max(min, d);
  2350. maxValue = Math.min(max, maxValue);
  2351. if (d > maxValue) {
  2352. return false;
  2353. }
  2354. }
  2355. if (Math.abs(this.direction.y) < 0.0000001) {
  2356. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2357. return false;
  2358. }
  2359. }
  2360. else {
  2361. inv = 1.0 / this.direction.y;
  2362. min = (minimum.y - this.origin.y) * inv;
  2363. max = (maximum.y - this.origin.y) * inv;
  2364. if (max === -Infinity) {
  2365. max = Infinity;
  2366. }
  2367. if (min > max) {
  2368. temp = min;
  2369. min = max;
  2370. max = temp;
  2371. }
  2372. d = Math.max(min, d);
  2373. maxValue = Math.min(max, maxValue);
  2374. if (d > maxValue) {
  2375. return false;
  2376. }
  2377. }
  2378. if (Math.abs(this.direction.z) < 0.0000001) {
  2379. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2380. return false;
  2381. }
  2382. }
  2383. else {
  2384. inv = 1.0 / this.direction.z;
  2385. min = (minimum.z - this.origin.z) * inv;
  2386. max = (maximum.z - this.origin.z) * inv;
  2387. if (max === -Infinity) {
  2388. max = Infinity;
  2389. }
  2390. if (min > max) {
  2391. temp = min;
  2392. min = max;
  2393. max = temp;
  2394. }
  2395. d = Math.max(min, d);
  2396. maxValue = Math.min(max, maxValue);
  2397. if (d > maxValue) {
  2398. return false;
  2399. }
  2400. }
  2401. return true;
  2402. };
  2403. Ray.prototype.intersectsBox = function (box) {
  2404. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2405. };
  2406. Ray.prototype.intersectsSphere = function (sphere) {
  2407. var x = sphere.center.x - this.origin.x;
  2408. var y = sphere.center.y - this.origin.y;
  2409. var z = sphere.center.z - this.origin.z;
  2410. var pyth = (x * x) + (y * y) + (z * z);
  2411. var rr = sphere.radius * sphere.radius;
  2412. if (pyth <= rr) {
  2413. return true;
  2414. }
  2415. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2416. if (dot < 0.0) {
  2417. return false;
  2418. }
  2419. var temp = pyth - (dot * dot);
  2420. return temp <= rr;
  2421. };
  2422. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2423. if (!this._edge1) {
  2424. this._edge1 = Vector3.Zero();
  2425. this._edge2 = Vector3.Zero();
  2426. this._pvec = Vector3.Zero();
  2427. this._tvec = Vector3.Zero();
  2428. this._qvec = Vector3.Zero();
  2429. }
  2430. vertex1.subtractToRef(vertex0, this._edge1);
  2431. vertex2.subtractToRef(vertex0, this._edge2);
  2432. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2433. var det = Vector3.Dot(this._edge1, this._pvec);
  2434. if (det === 0) {
  2435. return null;
  2436. }
  2437. var invdet = 1 / det;
  2438. this.origin.subtractToRef(vertex0, this._tvec);
  2439. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2440. if (bu < 0 || bu > 1.0) {
  2441. return null;
  2442. }
  2443. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2444. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2445. if (bv < 0 || bu + bv > 1.0) {
  2446. return null;
  2447. }
  2448. //check if the distance is longer than the predefined length.
  2449. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2450. if (distance > this.length) {
  2451. return null;
  2452. }
  2453. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2454. };
  2455. // Statics
  2456. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2457. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2458. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2459. var direction = end.subtract(start);
  2460. direction.normalize();
  2461. return new Ray(start, direction);
  2462. };
  2463. /**
  2464. * 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
  2465. * transformed to the given world matrix.
  2466. * @param origin The origin point
  2467. * @param end The end point
  2468. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2469. */
  2470. Ray.CreateNewFromTo = function (origin, end, world) {
  2471. if (world === void 0) { world = Matrix.Identity(); }
  2472. var direction = end.subtract(origin);
  2473. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2474. direction.normalize();
  2475. return Ray.Transform(new Ray(origin, direction, length), world);
  2476. };
  2477. Ray.Transform = function (ray, matrix) {
  2478. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2479. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2480. return new Ray(newOrigin, newDirection, ray.length);
  2481. };
  2482. return Ray;
  2483. })();
  2484. BABYLON.Ray = Ray;
  2485. (function (Space) {
  2486. Space[Space["LOCAL"] = 0] = "LOCAL";
  2487. Space[Space["WORLD"] = 1] = "WORLD";
  2488. })(BABYLON.Space || (BABYLON.Space = {}));
  2489. var Space = BABYLON.Space;
  2490. var Axis = (function () {
  2491. function Axis() {
  2492. }
  2493. Axis.X = new Vector3(1, 0, 0);
  2494. Axis.Y = new Vector3(0, 1, 0);
  2495. Axis.Z = new Vector3(0, 0, 1);
  2496. return Axis;
  2497. })();
  2498. BABYLON.Axis = Axis;
  2499. ;
  2500. var BezierCurve = (function () {
  2501. function BezierCurve() {
  2502. }
  2503. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2504. // Extract X (which is equal to time here)
  2505. var f0 = 1 - 3 * x2 + 3 * x1;
  2506. var f1 = 3 * x2 - 6 * x1;
  2507. var f2 = 3 * x1;
  2508. var refinedT = t;
  2509. for (var i = 0; i < 5; i++) {
  2510. var refinedT2 = refinedT * refinedT;
  2511. var refinedT3 = refinedT2 * refinedT;
  2512. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2513. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2514. refinedT -= (x - t) * slope;
  2515. refinedT = Math.min(1, Math.max(0, refinedT));
  2516. }
  2517. // Resolve cubic bezier for the given x
  2518. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2519. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2520. Math.pow(refinedT, 3);
  2521. };
  2522. return BezierCurve;
  2523. })();
  2524. BABYLON.BezierCurve = BezierCurve;
  2525. (function (Orientation) {
  2526. Orientation[Orientation["CW"] = 0] = "CW";
  2527. Orientation[Orientation["CCW"] = 1] = "CCW";
  2528. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2529. var Orientation = BABYLON.Orientation;
  2530. var Angle = (function () {
  2531. function Angle(radians) {
  2532. var _this = this;
  2533. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2534. this.radians = function () { return _this._radians; };
  2535. this._radians = radians;
  2536. if (this._radians < 0)
  2537. this._radians += (2 * Math.PI);
  2538. }
  2539. Angle.BetweenTwoPoints = function (a, b) {
  2540. var delta = b.subtract(a);
  2541. var theta = Math.atan2(delta.y, delta.x);
  2542. return new Angle(theta);
  2543. };
  2544. Angle.FromRadians = function (radians) {
  2545. return new Angle(radians);
  2546. };
  2547. Angle.FromDegrees = function (degrees) {
  2548. return new Angle(degrees * Math.PI / 180);
  2549. };
  2550. return Angle;
  2551. })();
  2552. BABYLON.Angle = Angle;
  2553. var Arc2 = (function () {
  2554. function Arc2(startPoint, midPoint, endPoint) {
  2555. this.startPoint = startPoint;
  2556. this.midPoint = midPoint;
  2557. this.endPoint = endPoint;
  2558. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2559. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2560. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2561. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2562. 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);
  2563. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2564. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2565. var a1 = this.startAngle.degrees();
  2566. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2567. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2568. // angles correction
  2569. if (a2 - a1 > +180.0)
  2570. a2 -= 360.0;
  2571. if (a2 - a1 < -180.0)
  2572. a2 += 360.0;
  2573. if (a3 - a2 > +180.0)
  2574. a3 -= 360.0;
  2575. if (a3 - a2 < -180.0)
  2576. a3 += 360.0;
  2577. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2578. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2579. }
  2580. return Arc2;
  2581. })();
  2582. BABYLON.Arc2 = Arc2;
  2583. var PathCursor = (function () {
  2584. function PathCursor(path) {
  2585. this.path = path;
  2586. this._onchange = new Array();
  2587. this.value = 0;
  2588. this.animations = new Array();
  2589. }
  2590. PathCursor.prototype.getPoint = function () {
  2591. var point = this.path.getPointAtLengthPosition(this.value);
  2592. return new Vector3(point.x, 0, point.y);
  2593. };
  2594. PathCursor.prototype.moveAhead = function (step) {
  2595. if (step === void 0) { step = 0.002; }
  2596. this.move(step);
  2597. return this;
  2598. };
  2599. PathCursor.prototype.moveBack = function (step) {
  2600. if (step === void 0) { step = 0.002; }
  2601. this.move(-step);
  2602. return this;
  2603. };
  2604. PathCursor.prototype.move = function (step) {
  2605. if (Math.abs(step) > 1) {
  2606. throw "step size should be less than 1.";
  2607. }
  2608. this.value += step;
  2609. this.ensureLimits();
  2610. this.raiseOnChange();
  2611. return this;
  2612. };
  2613. PathCursor.prototype.ensureLimits = function () {
  2614. while (this.value > 1) {
  2615. this.value -= 1;
  2616. }
  2617. while (this.value < 0) {
  2618. this.value += 1;
  2619. }
  2620. return this;
  2621. };
  2622. // used by animation engine
  2623. PathCursor.prototype.markAsDirty = function (propertyName) {
  2624. this.ensureLimits();
  2625. this.raiseOnChange();
  2626. return this;
  2627. };
  2628. PathCursor.prototype.raiseOnChange = function () {
  2629. var _this = this;
  2630. this._onchange.forEach(function (f) { return f(_this); });
  2631. return this;
  2632. };
  2633. PathCursor.prototype.onchange = function (f) {
  2634. this._onchange.push(f);
  2635. return this;
  2636. };
  2637. return PathCursor;
  2638. })();
  2639. BABYLON.PathCursor = PathCursor;
  2640. var Path2 = (function () {
  2641. function Path2(x, y) {
  2642. this._points = new Array();
  2643. this._length = 0;
  2644. this.closed = false;
  2645. this._points.push(new Vector2(x, y));
  2646. }
  2647. Path2.prototype.addLineTo = function (x, y) {
  2648. if (closed) {
  2649. BABYLON.Tools.Error("cannot add lines to closed paths");
  2650. return this;
  2651. }
  2652. var newPoint = new Vector2(x, y);
  2653. var previousPoint = this._points[this._points.length - 1];
  2654. this._points.push(newPoint);
  2655. this._length += newPoint.subtract(previousPoint).length();
  2656. return this;
  2657. };
  2658. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2659. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2660. if (closed) {
  2661. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2662. return this;
  2663. }
  2664. var startPoint = this._points[this._points.length - 1];
  2665. var midPoint = new Vector2(midX, midY);
  2666. var endPoint = new Vector2(endX, endY);
  2667. var arc = new Arc2(startPoint, midPoint, endPoint);
  2668. var increment = arc.angle.radians() / numberOfSegments;
  2669. if (arc.orientation === Orientation.CW)
  2670. increment *= -1;
  2671. var currentAngle = arc.startAngle.radians() + increment;
  2672. for (var i = 0; i < numberOfSegments; i++) {
  2673. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2674. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2675. this.addLineTo(x, y);
  2676. currentAngle += increment;
  2677. }
  2678. return this;
  2679. };
  2680. Path2.prototype.close = function () {
  2681. this.closed = true;
  2682. return this;
  2683. };
  2684. Path2.prototype.length = function () {
  2685. var result = this._length;
  2686. if (!this.closed) {
  2687. var lastPoint = this._points[this._points.length - 1];
  2688. var firstPoint = this._points[0];
  2689. result += (firstPoint.subtract(lastPoint).length());
  2690. }
  2691. return result;
  2692. };
  2693. Path2.prototype.getPoints = function () {
  2694. return this._points;
  2695. };
  2696. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2697. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2698. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2699. return Vector2.Zero();
  2700. }
  2701. var lengthPosition = normalizedLengthPosition * this.length();
  2702. var previousOffset = 0;
  2703. for (var i = 0; i < this._points.length; i++) {
  2704. var j = (i + 1) % this._points.length;
  2705. var a = this._points[i];
  2706. var b = this._points[j];
  2707. var bToA = b.subtract(a);
  2708. var nextOffset = (bToA.length() + previousOffset);
  2709. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2710. var dir = bToA.normalize();
  2711. var localOffset = lengthPosition - previousOffset;
  2712. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2713. }
  2714. previousOffset = nextOffset;
  2715. }
  2716. BABYLON.Tools.Error("internal error");
  2717. return Vector2.Zero();
  2718. };
  2719. Path2.StartingAt = function (x, y) {
  2720. return new Path2(x, y);
  2721. };
  2722. return Path2;
  2723. })();
  2724. BABYLON.Path2 = Path2;
  2725. var Path3D = (function () {
  2726. function Path3D(path, firstNormal) {
  2727. this.path = path;
  2728. this._curve = new Array();
  2729. this._distances = new Array();
  2730. this._tangents = new Array();
  2731. this._normals = new Array();
  2732. this._binormals = new Array();
  2733. for (var p = 0; p < path.length; p++) {
  2734. this._curve[p] = path[p].clone(); // hard copy
  2735. }
  2736. this._compute(firstNormal);
  2737. }
  2738. Path3D.prototype.getCurve = function () {
  2739. return this._curve;
  2740. };
  2741. Path3D.prototype.getTangents = function () {
  2742. return this._tangents;
  2743. };
  2744. Path3D.prototype.getNormals = function () {
  2745. return this._normals;
  2746. };
  2747. Path3D.prototype.getBinormals = function () {
  2748. return this._binormals;
  2749. };
  2750. Path3D.prototype.getDistances = function () {
  2751. return this._distances;
  2752. };
  2753. Path3D.prototype.update = function (path, firstNormal) {
  2754. for (var p = 0; p < path.length; p++) {
  2755. this._curve[p].x = path[p].x;
  2756. this._curve[p].y = path[p].y;
  2757. this._curve[p].z = path[p].z;
  2758. }
  2759. this._compute(firstNormal);
  2760. return this;
  2761. };
  2762. // private function compute() : computes tangents, normals and binormals
  2763. Path3D.prototype._compute = function (firstNormal) {
  2764. var l = this._curve.length;
  2765. // first and last tangents
  2766. this._tangents[0] = this._getFirstNonNullVector(0);
  2767. this._tangents[0].normalize();
  2768. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2769. this._tangents[l - 1].normalize();
  2770. // normals and binormals at first point : arbitrary vector with _normalVector()
  2771. var tg0 = this._tangents[0];
  2772. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2773. this._normals[0] = pp0;
  2774. this._normals[0].normalize();
  2775. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2776. this._binormals[0].normalize();
  2777. this._distances[0] = 0;
  2778. // normals and binormals : next points
  2779. var prev; // previous vector (segment)
  2780. var cur; // current vector (segment)
  2781. var curTang; // current tangent
  2782. var prevNorm; // previous normal
  2783. var prevBinor; // previous binormal
  2784. for (var i = 1; i < l; i++) {
  2785. // tangents
  2786. prev = this._getLastNonNullVector(i);
  2787. if (i < l - 1) {
  2788. cur = this._getFirstNonNullVector(i);
  2789. this._tangents[i] = prev.add(cur);
  2790. this._tangents[i].normalize();
  2791. }
  2792. this._distances[i] = this._distances[i - 1] + prev.length();
  2793. // normals and binormals
  2794. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2795. curTang = this._tangents[i];
  2796. prevNorm = this._normals[i - 1];
  2797. prevBinor = this._binormals[i - 1];
  2798. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2799. this._normals[i].normalize();
  2800. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2801. this._binormals[i].normalize();
  2802. }
  2803. };
  2804. // private function getFirstNonNullVector(index)
  2805. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2806. Path3D.prototype._getFirstNonNullVector = function (index) {
  2807. var i = 1;
  2808. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2809. while (nNVector.length() == 0 && index + i + 1 < this._curve.length) {
  2810. i++;
  2811. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2812. }
  2813. return nNVector;
  2814. };
  2815. // private function getLastNonNullVector(index)
  2816. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2817. Path3D.prototype._getLastNonNullVector = function (index) {
  2818. var i = 1;
  2819. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2820. while (nLVector.length() == 0 && index > i + 1) {
  2821. i++;
  2822. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2823. }
  2824. return nLVector;
  2825. };
  2826. // private function normalVector(v0, vt, va) :
  2827. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2828. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2829. Path3D.prototype._normalVector = function (v0, vt, va) {
  2830. var normal0;
  2831. if (va === undefined || va === null) {
  2832. var point;
  2833. if (vt.y !== 1) {
  2834. point = new Vector3(0, -1, 0);
  2835. }
  2836. else if (vt.x !== 1) {
  2837. point = new Vector3(1, 0, 0);
  2838. }
  2839. else if (vt.z !== 1) {
  2840. point = new Vector3(0, 0, 1);
  2841. }
  2842. normal0 = Vector3.Cross(vt, point);
  2843. }
  2844. else {
  2845. normal0 = Vector3.Cross(vt, va);
  2846. Vector3.CrossToRef(normal0, vt, normal0);
  2847. }
  2848. normal0.normalize();
  2849. return normal0;
  2850. };
  2851. return Path3D;
  2852. })();
  2853. BABYLON.Path3D = Path3D;
  2854. var Curve3 = (function () {
  2855. function Curve3(points) {
  2856. this._length = 0;
  2857. this._points = points;
  2858. this._length = this._computeLength(points);
  2859. }
  2860. // QuadraticBezier(origin_V3, control_V3, destination_V3, nbPoints)
  2861. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2862. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2863. var bez = new Array();
  2864. var equation = function (t, val0, val1, val2) {
  2865. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2866. return res;
  2867. };
  2868. for (var i = 0; i <= nbPoints; i++) {
  2869. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  2870. }
  2871. return new Curve3(bez);
  2872. };
  2873. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3, nbPoints)
  2874. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2875. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2876. var bez = new Array();
  2877. var equation = function (t, val0, val1, val2, val3) {
  2878. 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;
  2879. return res;
  2880. };
  2881. for (var i = 0; i <= nbPoints; i++) {
  2882. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  2883. }
  2884. return new Curve3(bez);
  2885. };
  2886. // HermiteSpline(origin_V3, originTangent_V3, destination_V3, destinationTangent_V3, nbPoints)
  2887. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  2888. var hermite = new Array();
  2889. var step = 1 / nbPoints;
  2890. for (var i = 0; i <= nbPoints; i++) {
  2891. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  2892. }
  2893. return new Curve3(hermite);
  2894. };
  2895. Curve3.prototype.getPoints = function () {
  2896. return this._points;
  2897. };
  2898. Curve3.prototype.length = function () {
  2899. return this._length;
  2900. };
  2901. Curve3.prototype.continue = function (curve) {
  2902. var lastPoint = this._points[this._points.length - 1];
  2903. var continuedPoints = this._points.slice();
  2904. var curvePoints = curve.getPoints();
  2905. for (var i = 1; i < curvePoints.length; i++) {
  2906. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  2907. }
  2908. var continuedCurve = new Curve3(continuedPoints);
  2909. return continuedCurve;
  2910. };
  2911. Curve3.prototype._computeLength = function (path) {
  2912. var l = 0;
  2913. for (var i = 1; i < path.length; i++) {
  2914. l += (path[i].subtract(path[i - 1])).length();
  2915. }
  2916. return l;
  2917. };
  2918. return Curve3;
  2919. })();
  2920. BABYLON.Curve3 = Curve3;
  2921. // Vertex formats
  2922. var PositionNormalVertex = (function () {
  2923. function PositionNormalVertex(position, normal) {
  2924. if (position === void 0) { position = Vector3.Zero(); }
  2925. if (normal === void 0) { normal = Vector3.Up(); }
  2926. this.position = position;
  2927. this.normal = normal;
  2928. }
  2929. PositionNormalVertex.prototype.clone = function () {
  2930. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  2931. };
  2932. return PositionNormalVertex;
  2933. })();
  2934. BABYLON.PositionNormalVertex = PositionNormalVertex;
  2935. var PositionNormalTextureVertex = (function () {
  2936. function PositionNormalTextureVertex(position, normal, uv) {
  2937. if (position === void 0) { position = Vector3.Zero(); }
  2938. if (normal === void 0) { normal = Vector3.Up(); }
  2939. if (uv === void 0) { uv = Vector2.Zero(); }
  2940. this.position = position;
  2941. this.normal = normal;
  2942. this.uv = uv;
  2943. }
  2944. PositionNormalTextureVertex.prototype.clone = function () {
  2945. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  2946. };
  2947. return PositionNormalTextureVertex;
  2948. })();
  2949. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  2950. // SIMD
  2951. var previousMultiplyToArray = Matrix.prototype.multiplyToArray;
  2952. var previousInvertToRef = Matrix.prototype.invertToRef;
  2953. var previousLookAtLHToRef = Matrix.LookAtLHToRef;
  2954. var previousTransformCoordinatesToRef = Vector3.TransformCoordinatesToRef;
  2955. var previousTransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRef;
  2956. var SIMDHelper = (function () {
  2957. function SIMDHelper() {
  2958. }
  2959. Object.defineProperty(SIMDHelper, "IsEnabled", {
  2960. get: function () {
  2961. return SIMDHelper._isEnabled;
  2962. },
  2963. enumerable: true,
  2964. configurable: true
  2965. });
  2966. SIMDHelper.DisableSIMD = function () {
  2967. // Replace functions
  2968. Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  2969. Matrix.prototype.invertToRef = previousInvertToRef;
  2970. Matrix.LookAtLHToRef = previousLookAtLHToRef;
  2971. Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  2972. Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  2973. SIMDHelper._isEnabled = false;
  2974. };
  2975. SIMDHelper.EnableSIMD = function () {
  2976. if (window.SIMD === undefined) {
  2977. return;
  2978. }
  2979. // Replace functions
  2980. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  2981. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  2982. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  2983. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  2984. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  2985. Object.defineProperty(Vector3.prototype, "x", {
  2986. get: function () { return this._data[0]; },
  2987. set: function (value) {
  2988. if (!this._data) {
  2989. this._data = new Float32Array(3);
  2990. }
  2991. this._data[0] = value;
  2992. }
  2993. });
  2994. Object.defineProperty(Vector3.prototype, "y", {
  2995. get: function () { return this._data[1]; },
  2996. set: function (value) {
  2997. this._data[1] = value;
  2998. }
  2999. });
  3000. Object.defineProperty(Vector3.prototype, "z", {
  3001. get: function () { return this._data[2]; },
  3002. set: function (value) {
  3003. this._data[2] = value;
  3004. }
  3005. });
  3006. SIMDHelper._isEnabled = true;
  3007. };
  3008. SIMDHelper._isEnabled = false;
  3009. return SIMDHelper;
  3010. })();
  3011. BABYLON.SIMDHelper = SIMDHelper;
  3012. if (window.SIMD !== undefined && window.SIMD.float32x4 && window.SIMD.float32x4.swizzle) {
  3013. SIMDHelper.EnableSIMD();
  3014. }
  3015. })(BABYLON || (BABYLON = {}));
  3016. //# sourceMappingURL=babylon.math.js.map
  3017. var BABYLON;
  3018. (function (BABYLON) {
  3019. var Database = (function () {
  3020. function Database(urlToScene, callbackManifestChecked) {
  3021. // Handling various flavors of prefixed version of IndexedDB
  3022. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3023. this.callbackManifestChecked = callbackManifestChecked;
  3024. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3025. this.db = null;
  3026. this.enableSceneOffline = false;
  3027. this.enableTexturesOffline = false;
  3028. this.manifestVersionFound = 0;
  3029. this.mustUpdateRessources = false;
  3030. this.hasReachedQuota = false;
  3031. if (!Database.IDBStorageEnabled) {
  3032. this.callbackManifestChecked(true);
  3033. }
  3034. else {
  3035. this.checkManifestFile();
  3036. }
  3037. }
  3038. Database.prototype.checkManifestFile = function () {
  3039. var _this = this;
  3040. function noManifestFile() {
  3041. that.enableSceneOffline = false;
  3042. that.enableTexturesOffline = false;
  3043. that.callbackManifestChecked(false);
  3044. }
  3045. var that = this;
  3046. var manifestURL = this.currentSceneUrl + ".manifest";
  3047. var xhr = new XMLHttpRequest();
  3048. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3049. xhr.open("GET", manifestURLTimeStamped, true);
  3050. xhr.addEventListener("load", function () {
  3051. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3052. try {
  3053. var manifestFile = JSON.parse(xhr.response);
  3054. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3055. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3056. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3057. _this.manifestVersionFound = manifestFile.version;
  3058. }
  3059. if (_this.callbackManifestChecked) {
  3060. _this.callbackManifestChecked(true);
  3061. }
  3062. }
  3063. catch (ex) {
  3064. noManifestFile();
  3065. }
  3066. }
  3067. else {
  3068. noManifestFile();
  3069. }
  3070. }, false);
  3071. xhr.addEventListener("error", function (event) {
  3072. noManifestFile();
  3073. }, false);
  3074. try {
  3075. xhr.send();
  3076. }
  3077. catch (ex) {
  3078. BABYLON.Tools.Error("Error on XHR send request.");
  3079. that.callbackManifestChecked(false);
  3080. }
  3081. };
  3082. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3083. var _this = this;
  3084. function handleError() {
  3085. that.isSupported = false;
  3086. if (errorCallback)
  3087. errorCallback();
  3088. }
  3089. var that = this;
  3090. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3091. // Your browser doesn't support IndexedDB
  3092. this.isSupported = false;
  3093. if (errorCallback)
  3094. errorCallback();
  3095. }
  3096. else {
  3097. // If the DB hasn't been opened or created yet
  3098. if (!this.db) {
  3099. this.hasReachedQuota = false;
  3100. this.isSupported = true;
  3101. var request = this.idbFactory.open("babylonjs", 1);
  3102. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3103. request.onerror = function (event) {
  3104. handleError();
  3105. };
  3106. // executes when a version change transaction cannot complete due to other active transactions
  3107. request.onblocked = function (event) {
  3108. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3109. handleError();
  3110. };
  3111. // DB has been opened successfully
  3112. request.onsuccess = function (event) {
  3113. _this.db = request.result;
  3114. successCallback();
  3115. };
  3116. // Initialization of the DB. Creating Scenes & Textures stores
  3117. request.onupgradeneeded = function (event) {
  3118. _this.db = (event.target).result;
  3119. try {
  3120. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3121. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3122. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3123. }
  3124. catch (ex) {
  3125. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3126. handleError();
  3127. }
  3128. };
  3129. }
  3130. else {
  3131. if (successCallback)
  3132. successCallback();
  3133. }
  3134. }
  3135. };
  3136. Database.prototype.loadImageFromDB = function (url, image) {
  3137. var _this = this;
  3138. var completeURL = Database.ReturnFullUrlLocation(url);
  3139. var saveAndLoadImage = function () {
  3140. if (!_this.hasReachedQuota && _this.db !== null) {
  3141. // the texture is not yet in the DB, let's try to save it
  3142. _this._saveImageIntoDBAsync(completeURL, image);
  3143. }
  3144. else {
  3145. image.src = url;
  3146. }
  3147. };
  3148. if (!this.mustUpdateRessources) {
  3149. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3150. }
  3151. else {
  3152. saveAndLoadImage();
  3153. }
  3154. };
  3155. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3156. if (this.isSupported && this.db !== null) {
  3157. var texture;
  3158. var transaction = this.db.transaction(["textures"]);
  3159. transaction.onabort = function (event) {
  3160. image.src = url;
  3161. };
  3162. transaction.oncomplete = function (event) {
  3163. var blobTextureURL;
  3164. if (texture) {
  3165. var URL = window.URL || window.webkitURL;
  3166. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3167. image.onerror = function () {
  3168. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3169. image.src = url;
  3170. };
  3171. image.src = blobTextureURL;
  3172. }
  3173. else {
  3174. notInDBCallback();
  3175. }
  3176. };
  3177. var getRequest = transaction.objectStore("textures").get(url);
  3178. getRequest.onsuccess = function (event) {
  3179. texture = (event.target).result;
  3180. };
  3181. getRequest.onerror = function (event) {
  3182. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3183. image.src = url;
  3184. };
  3185. }
  3186. else {
  3187. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3188. image.src = url;
  3189. }
  3190. };
  3191. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3192. var _this = this;
  3193. if (this.isSupported) {
  3194. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3195. var generateBlobUrl = function () {
  3196. var blobTextureURL;
  3197. if (blob) {
  3198. var URL = window.URL || window.webkitURL;
  3199. try {
  3200. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3201. }
  3202. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3203. catch (ex) {
  3204. blobTextureURL = URL.createObjectURL(blob);
  3205. }
  3206. }
  3207. image.src = blobTextureURL;
  3208. };
  3209. if (Database.IsUASupportingBlobStorage) {
  3210. var xhr = new XMLHttpRequest(), blob;
  3211. xhr.open("GET", url, true);
  3212. xhr.responseType = "blob";
  3213. xhr.addEventListener("load", function () {
  3214. if (xhr.status === 200) {
  3215. // Blob as response (XHR2)
  3216. blob = xhr.response;
  3217. var transaction = _this.db.transaction(["textures"], "readwrite");
  3218. // the transaction could abort because of a QuotaExceededError error
  3219. transaction.onabort = function (event) {
  3220. try {
  3221. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3222. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3223. this.hasReachedQuota = true;
  3224. }
  3225. }
  3226. catch (ex) { }
  3227. generateBlobUrl();
  3228. };
  3229. transaction.oncomplete = function (event) {
  3230. generateBlobUrl();
  3231. };
  3232. var newTexture = { textureUrl: url, data: blob };
  3233. try {
  3234. // Put the blob into the dabase
  3235. var addRequest = transaction.objectStore("textures").put(newTexture);
  3236. addRequest.onsuccess = function (event) {
  3237. };
  3238. addRequest.onerror = function (event) {
  3239. generateBlobUrl();
  3240. };
  3241. }
  3242. catch (ex) {
  3243. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3244. if (ex.code === 25) {
  3245. Database.IsUASupportingBlobStorage = false;
  3246. }
  3247. image.src = url;
  3248. }
  3249. }
  3250. else {
  3251. image.src = url;
  3252. }
  3253. }, false);
  3254. xhr.addEventListener("error", function (event) {
  3255. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3256. image.src = url;
  3257. }, false);
  3258. xhr.send();
  3259. }
  3260. else {
  3261. image.src = url;
  3262. }
  3263. }
  3264. else {
  3265. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3266. image.src = url;
  3267. }
  3268. };
  3269. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3270. var _this = this;
  3271. var updateVersion = function (event) {
  3272. // the version is not yet in the DB or we need to update it
  3273. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3274. };
  3275. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3276. };
  3277. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3278. var _this = this;
  3279. if (this.isSupported) {
  3280. var version;
  3281. try {
  3282. var transaction = this.db.transaction(["versions"]);
  3283. transaction.oncomplete = function (event) {
  3284. if (version) {
  3285. // If the version in the JSON file is > than the version in DB
  3286. if (_this.manifestVersionFound > version.data) {
  3287. _this.mustUpdateRessources = true;
  3288. updateInDBCallback();
  3289. }
  3290. else {
  3291. callback(version.data);
  3292. }
  3293. }
  3294. else {
  3295. _this.mustUpdateRessources = true;
  3296. updateInDBCallback();
  3297. }
  3298. };
  3299. transaction.onabort = function (event) {
  3300. callback(-1);
  3301. };
  3302. var getRequest = transaction.objectStore("versions").get(url);
  3303. getRequest.onsuccess = function (event) {
  3304. version = (event.target).result;
  3305. };
  3306. getRequest.onerror = function (event) {
  3307. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3308. callback(-1);
  3309. };
  3310. }
  3311. catch (ex) {
  3312. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3313. callback(-1);
  3314. }
  3315. }
  3316. else {
  3317. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3318. callback(-1);
  3319. }
  3320. };
  3321. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3322. var _this = this;
  3323. if (this.isSupported && !this.hasReachedQuota) {
  3324. try {
  3325. // Open a transaction to the database
  3326. var transaction = this.db.transaction(["versions"], "readwrite");
  3327. // the transaction could abort because of a QuotaExceededError error
  3328. transaction.onabort = function (event) {
  3329. try {
  3330. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3331. _this.hasReachedQuota = true;
  3332. }
  3333. }
  3334. catch (ex) { }
  3335. callback(-1);
  3336. };
  3337. transaction.oncomplete = function (event) {
  3338. callback(_this.manifestVersionFound);
  3339. };
  3340. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3341. // Put the scene into the database
  3342. var addRequest = transaction.objectStore("versions").put(newVersion);
  3343. addRequest.onsuccess = function (event) {
  3344. };
  3345. addRequest.onerror = function (event) {
  3346. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3347. };
  3348. }
  3349. catch (ex) {
  3350. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3351. callback(-1);
  3352. }
  3353. }
  3354. else {
  3355. callback(-1);
  3356. }
  3357. };
  3358. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3359. var _this = this;
  3360. var completeUrl = Database.ReturnFullUrlLocation(url);
  3361. var saveAndLoadFile = function (event) {
  3362. // the scene is not yet in the DB, let's try to save it
  3363. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3364. };
  3365. this._checkVersionFromDB(completeUrl, function (version) {
  3366. if (version !== -1) {
  3367. if (!_this.mustUpdateRessources) {
  3368. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3369. }
  3370. else {
  3371. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3372. }
  3373. }
  3374. else {
  3375. errorCallback();
  3376. }
  3377. });
  3378. };
  3379. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3380. if (this.isSupported) {
  3381. var targetStore;
  3382. if (url.indexOf(".babylon") !== -1) {
  3383. targetStore = "scenes";
  3384. }
  3385. else {
  3386. targetStore = "textures";
  3387. }
  3388. var file;
  3389. var transaction = this.db.transaction([targetStore]);
  3390. transaction.oncomplete = function (event) {
  3391. if (file) {
  3392. callback(file.data);
  3393. }
  3394. else {
  3395. notInDBCallback();
  3396. }
  3397. };
  3398. transaction.onabort = function (event) {
  3399. notInDBCallback();
  3400. };
  3401. var getRequest = transaction.objectStore(targetStore).get(url);
  3402. getRequest.onsuccess = function (event) {
  3403. file = (event.target).result;
  3404. };
  3405. getRequest.onerror = function (event) {
  3406. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3407. notInDBCallback();
  3408. };
  3409. }
  3410. else {
  3411. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3412. callback();
  3413. }
  3414. };
  3415. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3416. var _this = this;
  3417. if (this.isSupported) {
  3418. var targetStore;
  3419. if (url.indexOf(".babylon") !== -1) {
  3420. targetStore = "scenes";
  3421. }
  3422. else {
  3423. targetStore = "textures";
  3424. }
  3425. // Create XHR
  3426. var xhr = new XMLHttpRequest(), fileData;
  3427. xhr.open("GET", url, true);
  3428. if (useArrayBuffer) {
  3429. xhr.responseType = "arraybuffer";
  3430. }
  3431. xhr.onprogress = progressCallback;
  3432. xhr.addEventListener("load", function () {
  3433. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3434. // Blob as response (XHR2)
  3435. //fileData = xhr.responseText;
  3436. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3437. if (!_this.hasReachedQuota) {
  3438. // Open a transaction to the database
  3439. var transaction = _this.db.transaction([targetStore], "readwrite");
  3440. // the transaction could abort because of a QuotaExceededError error
  3441. transaction.onabort = function (event) {
  3442. try {
  3443. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3444. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3445. this.hasReachedQuota = true;
  3446. }
  3447. }
  3448. catch (ex) { }
  3449. callback(fileData);
  3450. };
  3451. transaction.oncomplete = function (event) {
  3452. callback(fileData);
  3453. };
  3454. var newFile;
  3455. if (targetStore === "scenes") {
  3456. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3457. }
  3458. else {
  3459. newFile = { textureUrl: url, data: fileData };
  3460. }
  3461. try {
  3462. // Put the scene into the database
  3463. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3464. addRequest.onsuccess = function (event) {
  3465. };
  3466. addRequest.onerror = function (event) {
  3467. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3468. };
  3469. }
  3470. catch (ex) {
  3471. callback(fileData);
  3472. }
  3473. }
  3474. else {
  3475. callback(fileData);
  3476. }
  3477. }
  3478. else {
  3479. callback();
  3480. }
  3481. }, false);
  3482. xhr.addEventListener("error", function (event) {
  3483. BABYLON.Tools.Error("error on XHR request.");
  3484. callback();
  3485. }, false);
  3486. xhr.send();
  3487. }
  3488. else {
  3489. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3490. callback();
  3491. }
  3492. };
  3493. Database.IsUASupportingBlobStorage = true;
  3494. Database.IDBStorageEnabled = true;
  3495. Database.parseURL = function (url) {
  3496. var a = document.createElement('a');
  3497. a.href = url;
  3498. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3499. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3500. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3501. return absLocation;
  3502. };
  3503. Database.ReturnFullUrlLocation = function (url) {
  3504. if (url.indexOf("http:/") === -1) {
  3505. return (Database.parseURL(window.location.href) + url);
  3506. }
  3507. else {
  3508. return url;
  3509. }
  3510. };
  3511. return Database;
  3512. })();
  3513. BABYLON.Database = Database;
  3514. })(BABYLON || (BABYLON = {}));
  3515. //# sourceMappingURL=babylon.database.js.map
  3516. var BABYLON;
  3517. (function (BABYLON) {
  3518. var Internals;
  3519. (function (Internals) {
  3520. /*
  3521. * Based on jsTGALoader - Javascript loader for TGA file
  3522. * By Vincent Thibault
  3523. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3524. */
  3525. var TGATools = (function () {
  3526. function TGATools() {
  3527. }
  3528. TGATools.GetTGAHeader = function (data) {
  3529. var offset = 0;
  3530. var header = {
  3531. id_length: data[offset++],
  3532. colormap_type: data[offset++],
  3533. image_type: data[offset++],
  3534. colormap_index: data[offset++] | data[offset++] << 8,
  3535. colormap_length: data[offset++] | data[offset++] << 8,
  3536. colormap_size: data[offset++],
  3537. origin: [
  3538. data[offset++] | data[offset++] << 8,
  3539. data[offset++] | data[offset++] << 8
  3540. ],
  3541. width: data[offset++] | data[offset++] << 8,
  3542. height: data[offset++] | data[offset++] << 8,
  3543. pixel_size: data[offset++],
  3544. flags: data[offset++]
  3545. };
  3546. return header;
  3547. };
  3548. TGATools.UploadContent = function (gl, data) {
  3549. // Not enough data to contain header ?
  3550. if (data.length < 19) {
  3551. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3552. return;
  3553. }
  3554. // Read Header
  3555. var offset = 18;
  3556. var header = TGATools.GetTGAHeader(data);
  3557. // Assume it's a valid Targa file.
  3558. if (header.id_length + offset > data.length) {
  3559. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3560. return;
  3561. }
  3562. // Skip not needed data
  3563. offset += header.id_length;
  3564. var use_rle = false;
  3565. var use_pal = false;
  3566. var use_rgb = false;
  3567. var use_grey = false;
  3568. // Get some informations.
  3569. switch (header.image_type) {
  3570. case TGATools._TYPE_RLE_INDEXED:
  3571. use_rle = true;
  3572. case TGATools._TYPE_INDEXED:
  3573. use_pal = true;
  3574. break;
  3575. case TGATools._TYPE_RLE_RGB:
  3576. use_rle = true;
  3577. case TGATools._TYPE_RGB:
  3578. use_rgb = true;
  3579. break;
  3580. case TGATools._TYPE_RLE_GREY:
  3581. use_rle = true;
  3582. case TGATools._TYPE_GREY:
  3583. use_grey = true;
  3584. break;
  3585. }
  3586. var pixel_data;
  3587. var numAlphaBits = header.flags & 0xf;
  3588. var pixel_size = header.pixel_size >> 3;
  3589. var pixel_total = header.width * header.height * pixel_size;
  3590. // Read palettes
  3591. var palettes;
  3592. if (use_pal) {
  3593. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3594. }
  3595. // Read LRE
  3596. if (use_rle) {
  3597. pixel_data = new Uint8Array(pixel_total);
  3598. var c, count, i;
  3599. var localOffset = 0;
  3600. var pixels = new Uint8Array(pixel_size);
  3601. while (offset < pixel_total && localOffset < pixel_total) {
  3602. c = data[offset++];
  3603. count = (c & 0x7f) + 1;
  3604. // RLE pixels
  3605. if (c & 0x80) {
  3606. // Bind pixel tmp array
  3607. for (i = 0; i < pixel_size; ++i) {
  3608. pixels[i] = data[offset++];
  3609. }
  3610. // Copy pixel array
  3611. for (i = 0; i < count; ++i) {
  3612. pixel_data.set(pixels, localOffset + i * pixel_size);
  3613. }
  3614. localOffset += pixel_size * count;
  3615. }
  3616. else {
  3617. count *= pixel_size;
  3618. for (i = 0; i < count; ++i) {
  3619. pixel_data[localOffset + i] = data[offset++];
  3620. }
  3621. localOffset += count;
  3622. }
  3623. }
  3624. }
  3625. else {
  3626. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3627. }
  3628. // Load to texture
  3629. var x_start, y_start, x_step, y_step, y_end, x_end;
  3630. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3631. default:
  3632. case TGATools._ORIGIN_UL:
  3633. x_start = 0;
  3634. x_step = 1;
  3635. x_end = header.width;
  3636. y_start = 0;
  3637. y_step = 1;
  3638. y_end = header.height;
  3639. break;
  3640. case TGATools._ORIGIN_BL:
  3641. x_start = 0;
  3642. x_step = 1;
  3643. x_end = header.width;
  3644. y_start = header.height - 1;
  3645. y_step = -1;
  3646. y_end = -1;
  3647. break;
  3648. case TGATools._ORIGIN_UR:
  3649. x_start = header.width - 1;
  3650. x_step = -1;
  3651. x_end = -1;
  3652. y_start = 0;
  3653. y_step = 1;
  3654. y_end = header.height;
  3655. break;
  3656. case TGATools._ORIGIN_BR:
  3657. x_start = header.width - 1;
  3658. x_step = -1;
  3659. x_end = -1;
  3660. y_start = header.height - 1;
  3661. y_step = -1;
  3662. y_end = -1;
  3663. break;
  3664. }
  3665. // Load the specify method
  3666. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3667. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3668. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3669. };
  3670. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3671. var image = pixel_data, colormap = palettes;
  3672. var width = header.width, height = header.height;
  3673. var color, i = 0, x, y;
  3674. var imageData = new Uint8Array(width * height * 4);
  3675. for (y = y_start; y !== y_end; y += y_step) {
  3676. for (x = x_start; x !== x_end; x += x_step, i++) {
  3677. color = image[i];
  3678. imageData[(x + width * y) * 4 + 3] = 255;
  3679. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3680. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3681. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3682. }
  3683. }
  3684. return imageData;
  3685. };
  3686. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3687. var image = pixel_data;
  3688. var width = header.width, height = header.height;
  3689. var color, i = 0, x, y;
  3690. var imageData = new Uint8Array(width * height * 4);
  3691. for (y = y_start; y !== y_end; y += y_step) {
  3692. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3693. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3694. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3695. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3696. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3697. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3698. }
  3699. }
  3700. return imageData;
  3701. };
  3702. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3703. var image = pixel_data;
  3704. var width = header.width, height = header.height;
  3705. var i = 0, x, y;
  3706. var imageData = new Uint8Array(width * height * 4);
  3707. for (y = y_start; y !== y_end; y += y_step) {
  3708. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3709. imageData[(x + width * y) * 4 + 3] = 255;
  3710. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3711. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3712. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3713. }
  3714. }
  3715. return imageData;
  3716. };
  3717. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3718. var image = pixel_data;
  3719. var width = header.width, height = header.height;
  3720. var i = 0, x, y;
  3721. var imageData = new Uint8Array(width * height * 4);
  3722. for (y = y_start; y !== y_end; y += y_step) {
  3723. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3724. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3725. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3726. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3727. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3728. }
  3729. }
  3730. return imageData;
  3731. };
  3732. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3733. var image = pixel_data;
  3734. var width = header.width, height = header.height;
  3735. var color, i = 0, x, y;
  3736. var imageData = new Uint8Array(width * height * 4);
  3737. for (y = y_start; y !== y_end; y += y_step) {
  3738. for (x = x_start; x !== x_end; x += x_step, i++) {
  3739. color = image[i];
  3740. imageData[(x + width * y) * 4 + 0] = color;
  3741. imageData[(x + width * y) * 4 + 1] = color;
  3742. imageData[(x + width * y) * 4 + 2] = color;
  3743. imageData[(x + width * y) * 4 + 3] = 255;
  3744. }
  3745. }
  3746. return imageData;
  3747. };
  3748. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3749. var image = pixel_data;
  3750. var width = header.width, height = header.height;
  3751. var i = 0, x, y;
  3752. var imageData = new Uint8Array(width * height * 4);
  3753. for (y = y_start; y !== y_end; y += y_step) {
  3754. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3755. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3756. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3757. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3758. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3759. }
  3760. }
  3761. return imageData;
  3762. };
  3763. TGATools._TYPE_NO_DATA = 0;
  3764. TGATools._TYPE_INDEXED = 1;
  3765. TGATools._TYPE_RGB = 2;
  3766. TGATools._TYPE_GREY = 3;
  3767. TGATools._TYPE_RLE_INDEXED = 9;
  3768. TGATools._TYPE_RLE_RGB = 10;
  3769. TGATools._TYPE_RLE_GREY = 11;
  3770. TGATools._ORIGIN_MASK = 0x30;
  3771. TGATools._ORIGIN_SHIFT = 0x04;
  3772. TGATools._ORIGIN_BL = 0x00;
  3773. TGATools._ORIGIN_BR = 0x01;
  3774. TGATools._ORIGIN_UL = 0x02;
  3775. TGATools._ORIGIN_UR = 0x03;
  3776. return TGATools;
  3777. })();
  3778. Internals.TGATools = TGATools;
  3779. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3780. })(BABYLON || (BABYLON = {}));
  3781. //# sourceMappingURL=babylon.tools.tga.js.map
  3782. var BABYLON;
  3783. (function (BABYLON) {
  3784. var Internals;
  3785. (function (Internals) {
  3786. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  3787. // All values and structures referenced from:
  3788. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  3789. var DDS_MAGIC = 0x20534444;
  3790. 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;
  3791. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  3792. 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;
  3793. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  3794. function FourCCToInt32(value) {
  3795. return value.charCodeAt(0) +
  3796. (value.charCodeAt(1) << 8) +
  3797. (value.charCodeAt(2) << 16) +
  3798. (value.charCodeAt(3) << 24);
  3799. }
  3800. function Int32ToFourCC(value) {
  3801. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  3802. }
  3803. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  3804. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  3805. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  3806. var headerLengthInt = 31; // The header length in 32 bit ints
  3807. // Offsets into the header array
  3808. var off_magic = 0;
  3809. var off_size = 1;
  3810. var off_flags = 2;
  3811. var off_height = 3;
  3812. var off_width = 4;
  3813. var off_mipmapCount = 7;
  3814. var off_pfFlags = 20;
  3815. var off_pfFourCC = 21;
  3816. var off_RGBbpp = 22;
  3817. var off_RMask = 23;
  3818. var off_GMask = 24;
  3819. var off_BMask = 25;
  3820. var off_AMask = 26;
  3821. var off_caps1 = 27;
  3822. var off_caps2 = 28;
  3823. ;
  3824. var DDSTools = (function () {
  3825. function DDSTools() {
  3826. }
  3827. DDSTools.GetDDSInfo = function (arrayBuffer) {
  3828. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  3829. var mipmapCount = 1;
  3830. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  3831. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3832. }
  3833. return {
  3834. width: header[off_width],
  3835. height: header[off_height],
  3836. mipmapCount: mipmapCount,
  3837. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  3838. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  3839. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  3840. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  3841. };
  3842. };
  3843. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3844. var byteArray = new Uint8Array(dataLength);
  3845. var srcData = new Uint8Array(arrayBuffer);
  3846. var index = 0;
  3847. for (var y = height - 1; y >= 0; y--) {
  3848. for (var x = 0; x < width; x++) {
  3849. var srcPos = dataOffset + (x + y * width) * 4;
  3850. byteArray[index + 2] = srcData[srcPos];
  3851. byteArray[index + 1] = srcData[srcPos + 1];
  3852. byteArray[index] = srcData[srcPos + 2];
  3853. byteArray[index + 3] = srcData[srcPos + 3];
  3854. index += 4;
  3855. }
  3856. }
  3857. return byteArray;
  3858. };
  3859. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3860. var byteArray = new Uint8Array(dataLength);
  3861. var srcData = new Uint8Array(arrayBuffer);
  3862. var index = 0;
  3863. for (var y = height - 1; y >= 0; y--) {
  3864. for (var x = 0; x < width; x++) {
  3865. var srcPos = dataOffset + (x + y * width) * 3;
  3866. byteArray[index + 2] = srcData[srcPos];
  3867. byteArray[index + 1] = srcData[srcPos + 1];
  3868. byteArray[index] = srcData[srcPos + 2];
  3869. index += 3;
  3870. }
  3871. }
  3872. return byteArray;
  3873. };
  3874. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3875. var byteArray = new Uint8Array(dataLength);
  3876. var srcData = new Uint8Array(arrayBuffer);
  3877. var index = 0;
  3878. for (var y = height - 1; y >= 0; y--) {
  3879. for (var x = 0; x < width; x++) {
  3880. var srcPos = dataOffset + (x + y * width);
  3881. byteArray[index] = srcData[srcPos];
  3882. index++;
  3883. }
  3884. }
  3885. return byteArray;
  3886. };
  3887. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  3888. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  3889. if (header[off_magic] != DDS_MAGIC) {
  3890. BABYLON.Tools.Error("Invalid magic number in DDS header");
  3891. return;
  3892. }
  3893. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  3894. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  3895. return;
  3896. }
  3897. if (info.isFourCC) {
  3898. fourCC = header[off_pfFourCC];
  3899. switch (fourCC) {
  3900. case FOURCC_DXT1:
  3901. blockBytes = 8;
  3902. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  3903. break;
  3904. case FOURCC_DXT3:
  3905. blockBytes = 16;
  3906. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  3907. break;
  3908. case FOURCC_DXT5:
  3909. blockBytes = 16;
  3910. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  3911. break;
  3912. default:
  3913. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  3914. return;
  3915. }
  3916. }
  3917. mipmapCount = 1;
  3918. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  3919. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3920. }
  3921. var bpp = header[off_RGBbpp];
  3922. for (var face = 0; face < faces; face++) {
  3923. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  3924. width = header[off_width];
  3925. height = header[off_height];
  3926. dataOffset = header[off_size] + 4;
  3927. for (i = 0; i < mipmapCount; ++i) {
  3928. if (info.isRGB) {
  3929. if (bpp == 24) {
  3930. dataLength = width * height * 3;
  3931. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3932. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  3933. }
  3934. else {
  3935. dataLength = width * height * 4;
  3936. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3937. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  3938. }
  3939. }
  3940. else if (info.isLuminance) {
  3941. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  3942. var unpaddedRowSize = width;
  3943. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  3944. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  3945. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3946. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  3947. }
  3948. else {
  3949. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  3950. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  3951. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  3952. }
  3953. dataOffset += dataLength;
  3954. width *= 0.5;
  3955. height *= 0.5;
  3956. width = Math.max(1.0, width);
  3957. height = Math.max(1.0, height);
  3958. }
  3959. }
  3960. };
  3961. return DDSTools;
  3962. })();
  3963. Internals.DDSTools = DDSTools;
  3964. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3965. })(BABYLON || (BABYLON = {}));
  3966. //# sourceMappingURL=babylon.tools.dds.js.map
  3967. var BABYLON;
  3968. (function (BABYLON) {
  3969. var SmartArray = (function () {
  3970. function SmartArray(capacity) {
  3971. this.length = 0;
  3972. this._duplicateId = 0;
  3973. this.data = new Array(capacity);
  3974. this._id = SmartArray._GlobalId++;
  3975. }
  3976. SmartArray.prototype.push = function (value) {
  3977. this.data[this.length++] = value;
  3978. if (this.length > this.data.length) {
  3979. this.data.length *= 2;
  3980. }
  3981. if (!value.__smartArrayFlags) {
  3982. value.__smartArrayFlags = {};
  3983. }
  3984. value.__smartArrayFlags[this._id] = this._duplicateId;
  3985. };
  3986. SmartArray.prototype.pushNoDuplicate = function (value) {
  3987. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3988. return;
  3989. }
  3990. this.push(value);
  3991. };
  3992. SmartArray.prototype.sort = function (compareFn) {
  3993. this.data.sort(compareFn);
  3994. };
  3995. SmartArray.prototype.reset = function () {
  3996. this.length = 0;
  3997. this._duplicateId++;
  3998. };
  3999. SmartArray.prototype.concat = function (array) {
  4000. if (array.length === 0) {
  4001. return;
  4002. }
  4003. if (this.length + array.length > this.data.length) {
  4004. this.data.length = (this.length + array.length) * 2;
  4005. }
  4006. for (var index = 0; index < array.length; index++) {
  4007. this.data[this.length++] = (array.data || array)[index];
  4008. }
  4009. };
  4010. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4011. if (array.length === 0) {
  4012. return;
  4013. }
  4014. if (this.length + array.length > this.data.length) {
  4015. this.data.length = (this.length + array.length) * 2;
  4016. }
  4017. for (var index = 0; index < array.length; index++) {
  4018. var item = (array.data || array)[index];
  4019. this.pushNoDuplicate(item);
  4020. }
  4021. };
  4022. SmartArray.prototype.indexOf = function (value) {
  4023. var position = this.data.indexOf(value);
  4024. if (position >= this.length) {
  4025. return -1;
  4026. }
  4027. return position;
  4028. };
  4029. // Statics
  4030. SmartArray._GlobalId = 0;
  4031. return SmartArray;
  4032. })();
  4033. BABYLON.SmartArray = SmartArray;
  4034. })(BABYLON || (BABYLON = {}));
  4035. //# sourceMappingURL=babylon.smartArray.js.map
  4036. var BABYLON;
  4037. (function (BABYLON) {
  4038. var SmartCollection = (function () {
  4039. function SmartCollection(capacity) {
  4040. if (capacity === void 0) { capacity = 10; }
  4041. this.count = 0;
  4042. this._initialCapacity = capacity;
  4043. this.items = {};
  4044. this._keys = new Array(this._initialCapacity);
  4045. }
  4046. SmartCollection.prototype.add = function (key, item) {
  4047. if (this.items[key] != undefined) {
  4048. return -1;
  4049. }
  4050. this.items[key] = item;
  4051. //literal keys are always strings, but we keep source type of key in _keys array
  4052. this._keys[this.count++] = key;
  4053. if (this.count > this._keys.length) {
  4054. this._keys.length *= 2;
  4055. }
  4056. return this.count;
  4057. };
  4058. SmartCollection.prototype.remove = function (key) {
  4059. if (this.items[key] == undefined) {
  4060. return -1;
  4061. }
  4062. return this.removeItemOfIndex(this.indexOf(key));
  4063. };
  4064. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4065. if (index < this.count && index > -1) {
  4066. delete this.items[this._keys[index]];
  4067. //here, shifting by hand is better optimised than .splice
  4068. while (index < this.count) {
  4069. this._keys[index] = this._keys[index + 1];
  4070. index++;
  4071. }
  4072. }
  4073. else {
  4074. return -1;
  4075. }
  4076. return --this.count;
  4077. };
  4078. SmartCollection.prototype.indexOf = function (key) {
  4079. for (var i = 0; i !== this.count; i++) {
  4080. if (this._keys[i] === key) {
  4081. return i;
  4082. }
  4083. }
  4084. return -1;
  4085. };
  4086. SmartCollection.prototype.item = function (key) {
  4087. return this.items[key];
  4088. };
  4089. SmartCollection.prototype.getAllKeys = function () {
  4090. if (this.count > 0) {
  4091. var keys = new Array(this.count);
  4092. for (var i = 0; i < this.count; i++) {
  4093. keys[i] = this._keys[i];
  4094. }
  4095. return keys;
  4096. }
  4097. else {
  4098. return undefined;
  4099. }
  4100. };
  4101. SmartCollection.prototype.getKeyByIndex = function (index) {
  4102. if (index < this.count && index > -1) {
  4103. return this._keys[index];
  4104. }
  4105. else {
  4106. return undefined;
  4107. }
  4108. };
  4109. SmartCollection.prototype.getItemByIndex = function (index) {
  4110. if (index < this.count && index > -1) {
  4111. return this.items[this._keys[index]];
  4112. }
  4113. else {
  4114. return undefined;
  4115. }
  4116. };
  4117. SmartCollection.prototype.empty = function () {
  4118. if (this.count > 0) {
  4119. this.count = 0;
  4120. this.items = {};
  4121. this._keys = new Array(this._initialCapacity);
  4122. }
  4123. };
  4124. SmartCollection.prototype.forEach = function (block) {
  4125. var key;
  4126. for (key in this.items) {
  4127. if (this.items.hasOwnProperty(key)) {
  4128. block(this.items[key]);
  4129. }
  4130. }
  4131. };
  4132. return SmartCollection;
  4133. })();
  4134. BABYLON.SmartCollection = SmartCollection;
  4135. })(BABYLON || (BABYLON = {}));
  4136. //# sourceMappingURL=babylon.smartCollection.js.map
  4137. var BABYLON;
  4138. (function (BABYLON) {
  4139. // Screenshots
  4140. var screenshotCanvas;
  4141. var cloneValue = function (source, destinationObject) {
  4142. if (!source)
  4143. return null;
  4144. if (source instanceof BABYLON.Mesh) {
  4145. return null;
  4146. }
  4147. if (source instanceof BABYLON.SubMesh) {
  4148. return source.clone(destinationObject);
  4149. }
  4150. else if (source.clone) {
  4151. return source.clone();
  4152. }
  4153. return null;
  4154. };
  4155. var Tools = (function () {
  4156. function Tools() {
  4157. }
  4158. Tools.SetImmediate = function (action) {
  4159. if (window.setImmediate) {
  4160. window.setImmediate(action);
  4161. }
  4162. else {
  4163. setTimeout(action, 1);
  4164. }
  4165. };
  4166. Tools.IsExponantOfTwo = function (value) {
  4167. var count = 1;
  4168. do {
  4169. count *= 2;
  4170. } while (count < value);
  4171. return count === value;
  4172. };
  4173. Tools.GetExponantOfTwo = function (value, max) {
  4174. var count = 1;
  4175. do {
  4176. count *= 2;
  4177. } while (count < value);
  4178. if (count > max)
  4179. count = max;
  4180. return count;
  4181. };
  4182. Tools.GetFilename = function (path) {
  4183. var index = path.lastIndexOf("/");
  4184. if (index < 0)
  4185. return path;
  4186. return path.substring(index + 1);
  4187. };
  4188. Tools.GetDOMTextContent = function (element) {
  4189. var result = "";
  4190. var child = element.firstChild;
  4191. while (child) {
  4192. if (child.nodeType === 3) {
  4193. result += child.textContent;
  4194. }
  4195. child = child.nextSibling;
  4196. }
  4197. return result;
  4198. };
  4199. Tools.ToDegrees = function (angle) {
  4200. return angle * 180 / Math.PI;
  4201. };
  4202. Tools.ToRadians = function (angle) {
  4203. return angle * Math.PI / 180;
  4204. };
  4205. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4206. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4207. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4208. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4209. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4210. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4211. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4212. }
  4213. return {
  4214. minimum: minimum,
  4215. maximum: maximum
  4216. };
  4217. };
  4218. Tools.ExtractMinAndMax = function (positions, start, count) {
  4219. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4220. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4221. for (var index = start; index < start + count; index++) {
  4222. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4223. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4224. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4225. }
  4226. return {
  4227. minimum: minimum,
  4228. maximum: maximum
  4229. };
  4230. };
  4231. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4232. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4233. return undefined;
  4234. return Array.isArray(obj) ? obj : [obj];
  4235. };
  4236. // Misc.
  4237. Tools.GetPointerPrefix = function () {
  4238. var eventPrefix = "pointer";
  4239. // Check if hand.js is referenced or if the browser natively supports pointer events
  4240. if (!navigator.pointerEnabled) {
  4241. eventPrefix = "mouse";
  4242. }
  4243. return eventPrefix;
  4244. };
  4245. Tools.QueueNewFrame = function (func) {
  4246. if (window.requestAnimationFrame)
  4247. window.requestAnimationFrame(func);
  4248. else if (window.msRequestAnimationFrame)
  4249. window.msRequestAnimationFrame(func);
  4250. else if (window.webkitRequestAnimationFrame)
  4251. window.webkitRequestAnimationFrame(func);
  4252. else if (window.mozRequestAnimationFrame)
  4253. window.mozRequestAnimationFrame(func);
  4254. else if (window.oRequestAnimationFrame)
  4255. window.oRequestAnimationFrame(func);
  4256. else {
  4257. window.setTimeout(func, 16);
  4258. }
  4259. };
  4260. Tools.RequestFullscreen = function (element) {
  4261. if (element.requestFullscreen)
  4262. element.requestFullscreen();
  4263. else if (element.msRequestFullscreen)
  4264. element.msRequestFullscreen();
  4265. else if (element.webkitRequestFullscreen)
  4266. element.webkitRequestFullscreen();
  4267. else if (element.mozRequestFullScreen)
  4268. element.mozRequestFullScreen();
  4269. };
  4270. Tools.ExitFullscreen = function () {
  4271. if (document.exitFullscreen) {
  4272. document.exitFullscreen();
  4273. }
  4274. else if (document.mozCancelFullScreen) {
  4275. document.mozCancelFullScreen();
  4276. }
  4277. else if (document.webkitCancelFullScreen) {
  4278. document.webkitCancelFullScreen();
  4279. }
  4280. else if (document.msCancelFullScreen) {
  4281. document.msCancelFullScreen();
  4282. }
  4283. };
  4284. // External files
  4285. Tools.CleanUrl = function (url) {
  4286. url = url.replace(/#/mg, "%23");
  4287. return url;
  4288. };
  4289. Tools.LoadImage = function (url, onload, onerror, database) {
  4290. url = Tools.CleanUrl(url);
  4291. var img = new Image();
  4292. if (url.substr(0, 5) !== "data:")
  4293. img.crossOrigin = 'anonymous';
  4294. img.onload = function () {
  4295. onload(img);
  4296. };
  4297. img.onerror = function (err) {
  4298. onerror(img, err);
  4299. };
  4300. var noIndexedDB = function () {
  4301. img.src = url;
  4302. };
  4303. var loadFromIndexedDB = function () {
  4304. database.loadImageFromDB(url, img);
  4305. };
  4306. //ANY database to do!
  4307. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4308. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4309. }
  4310. else {
  4311. if (url.indexOf("file:") === -1) {
  4312. noIndexedDB();
  4313. }
  4314. else {
  4315. try {
  4316. var textureName = url.substring(5);
  4317. var blobURL;
  4318. try {
  4319. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4320. }
  4321. catch (ex) {
  4322. // Chrome doesn't support oneTimeOnly parameter
  4323. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4324. }
  4325. img.src = blobURL;
  4326. }
  4327. catch (e) {
  4328. Tools.Log("Error while trying to load texture: " + textureName);
  4329. img.src = null;
  4330. }
  4331. }
  4332. }
  4333. return img;
  4334. };
  4335. //ANY
  4336. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4337. url = Tools.CleanUrl(url);
  4338. var noIndexedDB = function () {
  4339. var request = new XMLHttpRequest();
  4340. var loadUrl = Tools.BaseUrl + url;
  4341. request.open('GET', loadUrl, true);
  4342. if (useArrayBuffer) {
  4343. request.responseType = "arraybuffer";
  4344. }
  4345. request.onprogress = progressCallBack;
  4346. request.onreadystatechange = function () {
  4347. if (request.readyState === 4) {
  4348. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4349. callback(!useArrayBuffer ? request.responseText : request.response);
  4350. }
  4351. else {
  4352. if (onError) {
  4353. onError();
  4354. }
  4355. else {
  4356. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4357. }
  4358. }
  4359. }
  4360. };
  4361. request.send(null);
  4362. };
  4363. var loadFromIndexedDB = function () {
  4364. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4365. };
  4366. if (url.indexOf("file:") !== -1) {
  4367. var fileName = url.substring(5);
  4368. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4369. }
  4370. else {
  4371. // Caching all files
  4372. if (database && database.enableSceneOffline) {
  4373. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4374. }
  4375. else {
  4376. noIndexedDB();
  4377. }
  4378. }
  4379. };
  4380. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4381. var reader = new FileReader();
  4382. reader.onload = function (e) {
  4383. //target doesn't have result from ts 1.3
  4384. callback(e.target['result']);
  4385. };
  4386. reader.onprogress = progressCallback;
  4387. reader.readAsDataURL(fileToLoad);
  4388. };
  4389. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4390. var reader = new FileReader();
  4391. reader.onerror = function (e) {
  4392. Tools.Log("Error while reading file: " + fileToLoad.name);
  4393. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  4394. };
  4395. reader.onload = function (e) {
  4396. //target doesn't have result from ts 1.3
  4397. callback(e.target['result']);
  4398. };
  4399. reader.onprogress = progressCallBack;
  4400. if (!useArrayBuffer) {
  4401. // Asynchronous read
  4402. reader.readAsText(fileToLoad);
  4403. }
  4404. else {
  4405. reader.readAsArrayBuffer(fileToLoad);
  4406. }
  4407. };
  4408. // Misc.
  4409. Tools.Clamp = function (value, min, max) {
  4410. if (min === void 0) { min = 0; }
  4411. if (max === void 0) { max = 1; }
  4412. return Math.min(max, Math.max(min, value));
  4413. };
  4414. // Returns -1 when value is a negative number and
  4415. // +1 when value is a positive number.
  4416. Tools.Sign = function (value) {
  4417. value = +value; // convert to a number
  4418. if (value === 0 || isNaN(value))
  4419. return value;
  4420. return value > 0 ? 1 : -1;
  4421. };
  4422. Tools.Format = function (value, decimals) {
  4423. if (decimals === void 0) { decimals = 2; }
  4424. return value.toFixed(decimals);
  4425. };
  4426. Tools.CheckExtends = function (v, min, max) {
  4427. if (v.x < min.x)
  4428. min.x = v.x;
  4429. if (v.y < min.y)
  4430. min.y = v.y;
  4431. if (v.z < min.z)
  4432. min.z = v.z;
  4433. if (v.x > max.x)
  4434. max.x = v.x;
  4435. if (v.y > max.y)
  4436. max.y = v.y;
  4437. if (v.z > max.z)
  4438. max.z = v.z;
  4439. };
  4440. Tools.WithinEpsilon = function (a, b, epsilon) {
  4441. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4442. var num = a - b;
  4443. return -epsilon <= num && num <= epsilon;
  4444. };
  4445. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4446. for (var prop in source) {
  4447. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4448. continue;
  4449. }
  4450. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4451. continue;
  4452. }
  4453. var sourceValue = source[prop];
  4454. var typeOfSourceValue = typeof sourceValue;
  4455. if (typeOfSourceValue === "function") {
  4456. continue;
  4457. }
  4458. if (typeOfSourceValue === "object") {
  4459. if (sourceValue instanceof Array) {
  4460. destination[prop] = [];
  4461. if (sourceValue.length > 0) {
  4462. if (typeof sourceValue[0] == "object") {
  4463. for (var index = 0; index < sourceValue.length; index++) {
  4464. var clonedValue = cloneValue(sourceValue[index], destination);
  4465. if (destination[prop].indexOf(clonedValue) === -1) {
  4466. destination[prop].push(clonedValue);
  4467. }
  4468. }
  4469. }
  4470. else {
  4471. destination[prop] = sourceValue.slice(0);
  4472. }
  4473. }
  4474. }
  4475. else {
  4476. destination[prop] = cloneValue(sourceValue, destination);
  4477. }
  4478. }
  4479. else {
  4480. destination[prop] = sourceValue;
  4481. }
  4482. }
  4483. };
  4484. Tools.IsEmpty = function (obj) {
  4485. for (var i in obj) {
  4486. return false;
  4487. }
  4488. return true;
  4489. };
  4490. Tools.RegisterTopRootEvents = function (events) {
  4491. for (var index = 0; index < events.length; index++) {
  4492. var event = events[index];
  4493. window.addEventListener(event.name, event.handler, false);
  4494. try {
  4495. if (window.parent) {
  4496. window.parent.addEventListener(event.name, event.handler, false);
  4497. }
  4498. }
  4499. catch (e) {
  4500. }
  4501. }
  4502. };
  4503. Tools.UnregisterTopRootEvents = function (events) {
  4504. for (var index = 0; index < events.length; index++) {
  4505. var event = events[index];
  4506. window.removeEventListener(event.name, event.handler);
  4507. try {
  4508. if (window.parent) {
  4509. window.parent.removeEventListener(event.name, event.handler);
  4510. }
  4511. }
  4512. catch (e) {
  4513. }
  4514. }
  4515. };
  4516. Tools.DumpFramebuffer = function (width, height, engine) {
  4517. // Read the contents of the framebuffer
  4518. var numberOfChannelsByLine = width * 4;
  4519. var halfHeight = height / 2;
  4520. //Reading datas from WebGL
  4521. var data = engine.readPixels(0, 0, width, height);
  4522. //To flip image on Y axis.
  4523. for (var i = 0; i < halfHeight; i++) {
  4524. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4525. var currentCell = j + i * numberOfChannelsByLine;
  4526. var targetLine = height - i - 1;
  4527. var targetCell = j + targetLine * numberOfChannelsByLine;
  4528. var temp = data[currentCell];
  4529. data[currentCell] = data[targetCell];
  4530. data[targetCell] = temp;
  4531. }
  4532. }
  4533. // Create a 2D canvas to store the result
  4534. if (!screenshotCanvas) {
  4535. screenshotCanvas = document.createElement('canvas');
  4536. }
  4537. screenshotCanvas.width = width;
  4538. screenshotCanvas.height = height;
  4539. var context = screenshotCanvas.getContext('2d');
  4540. // Copy the pixels to a 2D canvas
  4541. var imageData = context.createImageData(width, height);
  4542. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4543. var castData = imageData.data;
  4544. castData.set(data);
  4545. context.putImageData(imageData, 0, 0);
  4546. var base64Image = screenshotCanvas.toDataURL();
  4547. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4548. if (("download" in document.createElement("a"))) {
  4549. var a = window.document.createElement("a");
  4550. a.href = base64Image;
  4551. var date = new Date();
  4552. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  4553. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  4554. window.document.body.appendChild(a);
  4555. a.addEventListener("click", function () {
  4556. a.parentElement.removeChild(a);
  4557. });
  4558. a.click();
  4559. }
  4560. else {
  4561. var newWindow = window.open("");
  4562. var img = newWindow.document.createElement("img");
  4563. img.src = base64Image;
  4564. newWindow.document.body.appendChild(img);
  4565. }
  4566. };
  4567. Tools.CreateScreenshot = function (engine, camera, size) {
  4568. var width;
  4569. var height;
  4570. var scene = camera.getScene();
  4571. var previousCamera = null;
  4572. if (scene.activeCamera !== camera) {
  4573. previousCamera = scene.activeCamera;
  4574. scene.activeCamera = camera;
  4575. }
  4576. //If a precision value is specified
  4577. if (size.precision) {
  4578. width = Math.round(engine.getRenderWidth() * size.precision);
  4579. height = Math.round(width / engine.getAspectRatio(camera));
  4580. size = { width: width, height: height };
  4581. }
  4582. else if (size.width && size.height) {
  4583. width = size.width;
  4584. height = size.height;
  4585. }
  4586. else if (size.width && !size.height) {
  4587. width = size.width;
  4588. height = Math.round(width / engine.getAspectRatio(camera));
  4589. size = { width: width, height: height };
  4590. }
  4591. else if (size.height && !size.width) {
  4592. height = size.height;
  4593. width = Math.round(height * engine.getAspectRatio(camera));
  4594. size = { width: width, height: height };
  4595. }
  4596. else if (!isNaN(size)) {
  4597. height = size;
  4598. width = size;
  4599. }
  4600. else {
  4601. Tools.Error("Invalid 'size' parameter !");
  4602. return;
  4603. }
  4604. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4605. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4606. texture.renderList = scene.meshes;
  4607. texture.onAfterRender = function () {
  4608. Tools.DumpFramebuffer(width, height, engine);
  4609. };
  4610. scene.incrementRenderId();
  4611. texture.render(true);
  4612. texture.dispose();
  4613. if (previousCamera) {
  4614. scene.activeCamera = previousCamera;
  4615. }
  4616. };
  4617. // XHR response validator for local file scenario
  4618. Tools.ValidateXHRData = function (xhr, dataType) {
  4619. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4620. if (dataType === void 0) { dataType = 7; }
  4621. try {
  4622. if (dataType & 1) {
  4623. if (xhr.responseText && xhr.responseText.length > 0) {
  4624. return true;
  4625. }
  4626. else if (dataType === 1) {
  4627. return false;
  4628. }
  4629. }
  4630. if (dataType & 2) {
  4631. // Check header width and height since there is no "TGA" magic number
  4632. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4633. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4634. return true;
  4635. }
  4636. else if (dataType === 2) {
  4637. return false;
  4638. }
  4639. }
  4640. if (dataType & 4) {
  4641. // Check for the "DDS" magic number
  4642. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4643. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4644. return true;
  4645. }
  4646. else {
  4647. return false;
  4648. }
  4649. }
  4650. }
  4651. catch (e) {
  4652. }
  4653. return false;
  4654. };
  4655. Object.defineProperty(Tools, "NoneLogLevel", {
  4656. get: function () {
  4657. return Tools._NoneLogLevel;
  4658. },
  4659. enumerable: true,
  4660. configurable: true
  4661. });
  4662. Object.defineProperty(Tools, "MessageLogLevel", {
  4663. get: function () {
  4664. return Tools._MessageLogLevel;
  4665. },
  4666. enumerable: true,
  4667. configurable: true
  4668. });
  4669. Object.defineProperty(Tools, "WarningLogLevel", {
  4670. get: function () {
  4671. return Tools._WarningLogLevel;
  4672. },
  4673. enumerable: true,
  4674. configurable: true
  4675. });
  4676. Object.defineProperty(Tools, "ErrorLogLevel", {
  4677. get: function () {
  4678. return Tools._ErrorLogLevel;
  4679. },
  4680. enumerable: true,
  4681. configurable: true
  4682. });
  4683. Object.defineProperty(Tools, "AllLogLevel", {
  4684. get: function () {
  4685. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4686. },
  4687. enumerable: true,
  4688. configurable: true
  4689. });
  4690. Tools._AddLogEntry = function (entry) {
  4691. Tools._LogCache = entry + Tools._LogCache;
  4692. if (Tools.OnNewCacheEntry) {
  4693. Tools.OnNewCacheEntry(entry);
  4694. }
  4695. };
  4696. Tools._FormatMessage = function (message) {
  4697. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4698. var date = new Date();
  4699. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4700. };
  4701. Tools._LogDisabled = function (message) {
  4702. // nothing to do
  4703. };
  4704. Tools._LogEnabled = function (message) {
  4705. var formattedMessage = Tools._FormatMessage(message);
  4706. console.log("BJS - " + formattedMessage);
  4707. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4708. Tools._AddLogEntry(entry);
  4709. };
  4710. Tools._WarnDisabled = function (message) {
  4711. // nothing to do
  4712. };
  4713. Tools._WarnEnabled = function (message) {
  4714. var formattedMessage = Tools._FormatMessage(message);
  4715. console.warn("BJS - " + formattedMessage);
  4716. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4717. Tools._AddLogEntry(entry);
  4718. };
  4719. Tools._ErrorDisabled = function (message) {
  4720. // nothing to do
  4721. };
  4722. Tools._ErrorEnabled = function (message) {
  4723. var formattedMessage = Tools._FormatMessage(message);
  4724. console.error("BJS - " + formattedMessage);
  4725. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4726. Tools._AddLogEntry(entry);
  4727. };
  4728. Object.defineProperty(Tools, "LogCache", {
  4729. get: function () {
  4730. return Tools._LogCache;
  4731. },
  4732. enumerable: true,
  4733. configurable: true
  4734. });
  4735. Object.defineProperty(Tools, "LogLevels", {
  4736. set: function (level) {
  4737. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4738. Tools.Log = Tools._LogEnabled;
  4739. }
  4740. else {
  4741. Tools.Log = Tools._LogDisabled;
  4742. }
  4743. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4744. Tools.Warn = Tools._WarnEnabled;
  4745. }
  4746. else {
  4747. Tools.Warn = Tools._WarnDisabled;
  4748. }
  4749. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4750. Tools.Error = Tools._ErrorEnabled;
  4751. }
  4752. else {
  4753. Tools.Error = Tools._ErrorDisabled;
  4754. }
  4755. },
  4756. enumerable: true,
  4757. configurable: true
  4758. });
  4759. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4760. get: function () {
  4761. return Tools._PerformanceNoneLogLevel;
  4762. },
  4763. enumerable: true,
  4764. configurable: true
  4765. });
  4766. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4767. get: function () {
  4768. return Tools._PerformanceUserMarkLogLevel;
  4769. },
  4770. enumerable: true,
  4771. configurable: true
  4772. });
  4773. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4774. get: function () {
  4775. return Tools._PerformanceConsoleLogLevel;
  4776. },
  4777. enumerable: true,
  4778. configurable: true
  4779. });
  4780. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4781. set: function (level) {
  4782. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4783. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4784. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4785. return;
  4786. }
  4787. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4788. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4789. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4790. return;
  4791. }
  4792. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4793. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4794. },
  4795. enumerable: true,
  4796. configurable: true
  4797. });
  4798. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4799. };
  4800. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4801. };
  4802. Tools._StartUserMark = function (counterName, condition) {
  4803. if (condition === void 0) { condition = true; }
  4804. if (!condition || !Tools._performance.mark) {
  4805. return;
  4806. }
  4807. Tools._performance.mark(counterName + "-Begin");
  4808. };
  4809. Tools._EndUserMark = function (counterName, condition) {
  4810. if (condition === void 0) { condition = true; }
  4811. if (!condition || !Tools._performance.mark) {
  4812. return;
  4813. }
  4814. Tools._performance.mark(counterName + "-End");
  4815. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4816. };
  4817. Tools._StartPerformanceConsole = function (counterName, condition) {
  4818. if (condition === void 0) { condition = true; }
  4819. if (!condition) {
  4820. return;
  4821. }
  4822. Tools._StartUserMark(counterName, condition);
  4823. if (console.time) {
  4824. console.time(counterName);
  4825. }
  4826. };
  4827. Tools._EndPerformanceConsole = function (counterName, condition) {
  4828. if (condition === void 0) { condition = true; }
  4829. if (!condition) {
  4830. return;
  4831. }
  4832. Tools._EndUserMark(counterName, condition);
  4833. if (console.time) {
  4834. console.timeEnd(counterName);
  4835. }
  4836. };
  4837. Object.defineProperty(Tools, "Now", {
  4838. get: function () {
  4839. if (window.performance && window.performance.now) {
  4840. return window.performance.now();
  4841. }
  4842. return new Date().getTime();
  4843. },
  4844. enumerable: true,
  4845. configurable: true
  4846. });
  4847. // Deprecated
  4848. Tools.GetFps = function () {
  4849. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  4850. return 0;
  4851. };
  4852. Tools.BaseUrl = "";
  4853. // Logs
  4854. Tools._NoneLogLevel = 0;
  4855. Tools._MessageLogLevel = 1;
  4856. Tools._WarningLogLevel = 2;
  4857. Tools._ErrorLogLevel = 4;
  4858. Tools._LogCache = "";
  4859. Tools.Log = Tools._LogEnabled;
  4860. Tools.Warn = Tools._WarnEnabled;
  4861. Tools.Error = Tools._ErrorEnabled;
  4862. // Performances
  4863. Tools._PerformanceNoneLogLevel = 0;
  4864. Tools._PerformanceUserMarkLogLevel = 1;
  4865. Tools._PerformanceConsoleLogLevel = 2;
  4866. Tools._performance = window.performance;
  4867. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4868. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4869. return Tools;
  4870. })();
  4871. BABYLON.Tools = Tools;
  4872. /**
  4873. * An implementation of a loop for asynchronous functions.
  4874. */
  4875. var AsyncLoop = (function () {
  4876. /**
  4877. * Constroctor.
  4878. * @param iterations the number of iterations.
  4879. * @param _fn the function to run each iteration
  4880. * @param _successCallback the callback that will be called upon succesful execution
  4881. * @param offset starting offset.
  4882. */
  4883. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4884. if (offset === void 0) { offset = 0; }
  4885. this.iterations = iterations;
  4886. this._fn = _fn;
  4887. this._successCallback = _successCallback;
  4888. this.index = offset - 1;
  4889. this._done = false;
  4890. }
  4891. /**
  4892. * Execute the next iteration. Must be called after the last iteration was finished.
  4893. */
  4894. AsyncLoop.prototype.executeNext = function () {
  4895. if (!this._done) {
  4896. if (this.index + 1 < this.iterations) {
  4897. ++this.index;
  4898. this._fn(this);
  4899. }
  4900. else {
  4901. this.breakLoop();
  4902. }
  4903. }
  4904. };
  4905. /**
  4906. * Break the loop and run the success callback.
  4907. */
  4908. AsyncLoop.prototype.breakLoop = function () {
  4909. this._done = true;
  4910. this._successCallback();
  4911. };
  4912. /**
  4913. * Helper function
  4914. */
  4915. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4916. if (offset === void 0) { offset = 0; }
  4917. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4918. loop.executeNext();
  4919. return loop;
  4920. };
  4921. /**
  4922. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4923. * @param iterations total number of iterations
  4924. * @param syncedIterations number of synchronous iterations in each async iteration.
  4925. * @param fn the function to call each iteration.
  4926. * @param callback a success call back that will be called when iterating stops.
  4927. * @param breakFunction a break condition (optional)
  4928. * @param timeout timeout settings for the setTimeout function. default - 0.
  4929. * @constructor
  4930. */
  4931. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4932. if (timeout === void 0) { timeout = 0; }
  4933. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4934. if (breakFunction && breakFunction())
  4935. loop.breakLoop();
  4936. else {
  4937. setTimeout(function () {
  4938. for (var i = 0; i < syncedIterations; ++i) {
  4939. var iteration = (loop.index * syncedIterations) + i;
  4940. if (iteration >= iterations)
  4941. break;
  4942. fn(iteration);
  4943. if (breakFunction && breakFunction()) {
  4944. loop.breakLoop();
  4945. break;
  4946. }
  4947. }
  4948. loop.executeNext();
  4949. }, timeout);
  4950. }
  4951. }, callback);
  4952. };
  4953. return AsyncLoop;
  4954. })();
  4955. BABYLON.AsyncLoop = AsyncLoop;
  4956. })(BABYLON || (BABYLON = {}));
  4957. //# sourceMappingURL=babylon.tools.js.map
  4958. var BABYLON;
  4959. (function (BABYLON) {
  4960. var _DepthCullingState = (function () {
  4961. function _DepthCullingState() {
  4962. this._isDepthTestDirty = false;
  4963. this._isDepthMaskDirty = false;
  4964. this._isDepthFuncDirty = false;
  4965. this._isCullFaceDirty = false;
  4966. this._isCullDirty = false;
  4967. this._isZOffsetDirty = false;
  4968. }
  4969. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4970. get: function () {
  4971. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4972. },
  4973. enumerable: true,
  4974. configurable: true
  4975. });
  4976. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4977. get: function () {
  4978. return this._zOffset;
  4979. },
  4980. set: function (value) {
  4981. if (this._zOffset === value) {
  4982. return;
  4983. }
  4984. this._zOffset = value;
  4985. this._isZOffsetDirty = true;
  4986. },
  4987. enumerable: true,
  4988. configurable: true
  4989. });
  4990. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4991. get: function () {
  4992. return this._cullFace;
  4993. },
  4994. set: function (value) {
  4995. if (this._cullFace === value) {
  4996. return;
  4997. }
  4998. this._cullFace = value;
  4999. this._isCullFaceDirty = true;
  5000. },
  5001. enumerable: true,
  5002. configurable: true
  5003. });
  5004. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5005. get: function () {
  5006. return this._cull;
  5007. },
  5008. set: function (value) {
  5009. if (this._cull === value) {
  5010. return;
  5011. }
  5012. this._cull = value;
  5013. this._isCullDirty = true;
  5014. },
  5015. enumerable: true,
  5016. configurable: true
  5017. });
  5018. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5019. get: function () {
  5020. return this._depthFunc;
  5021. },
  5022. set: function (value) {
  5023. if (this._depthFunc === value) {
  5024. return;
  5025. }
  5026. this._depthFunc = value;
  5027. this._isDepthFuncDirty = true;
  5028. },
  5029. enumerable: true,
  5030. configurable: true
  5031. });
  5032. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5033. get: function () {
  5034. return this._depthMask;
  5035. },
  5036. set: function (value) {
  5037. if (this._depthMask === value) {
  5038. return;
  5039. }
  5040. this._depthMask = value;
  5041. this._isDepthMaskDirty = true;
  5042. },
  5043. enumerable: true,
  5044. configurable: true
  5045. });
  5046. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5047. get: function () {
  5048. return this._depthTest;
  5049. },
  5050. set: function (value) {
  5051. if (this._depthTest === value) {
  5052. return;
  5053. }
  5054. this._depthTest = value;
  5055. this._isDepthTestDirty = true;
  5056. },
  5057. enumerable: true,
  5058. configurable: true
  5059. });
  5060. _DepthCullingState.prototype.reset = function () {
  5061. this._depthMask = true;
  5062. this._depthTest = true;
  5063. this._depthFunc = null;
  5064. this._cull = null;
  5065. this._cullFace = null;
  5066. this._zOffset = 0;
  5067. this._isDepthTestDirty = true;
  5068. this._isDepthMaskDirty = true;
  5069. this._isDepthFuncDirty = false;
  5070. this._isCullFaceDirty = false;
  5071. this._isCullDirty = false;
  5072. this._isZOffsetDirty = false;
  5073. };
  5074. _DepthCullingState.prototype.apply = function (gl) {
  5075. if (!this.isDirty) {
  5076. return;
  5077. }
  5078. // Cull
  5079. if (this._isCullDirty) {
  5080. if (this.cull) {
  5081. gl.enable(gl.CULL_FACE);
  5082. }
  5083. else {
  5084. gl.disable(gl.CULL_FACE);
  5085. }
  5086. this._isCullDirty = false;
  5087. }
  5088. // Cull face
  5089. if (this._isCullFaceDirty) {
  5090. gl.cullFace(this.cullFace);
  5091. this._isCullFaceDirty = false;
  5092. }
  5093. // Depth mask
  5094. if (this._isDepthMaskDirty) {
  5095. gl.depthMask(this.depthMask);
  5096. this._isDepthMaskDirty = false;
  5097. }
  5098. // Depth test
  5099. if (this._isDepthTestDirty) {
  5100. if (this.depthTest) {
  5101. gl.enable(gl.DEPTH_TEST);
  5102. }
  5103. else {
  5104. gl.disable(gl.DEPTH_TEST);
  5105. }
  5106. this._isDepthTestDirty = false;
  5107. }
  5108. // Depth func
  5109. if (this._isDepthFuncDirty) {
  5110. gl.depthFunc(this.depthFunc);
  5111. this._isDepthFuncDirty = false;
  5112. }
  5113. // zOffset
  5114. if (this._isZOffsetDirty) {
  5115. if (this.zOffset) {
  5116. gl.enable(gl.POLYGON_OFFSET_FILL);
  5117. gl.polygonOffset(this.zOffset, 0);
  5118. }
  5119. else {
  5120. gl.disable(gl.POLYGON_OFFSET_FILL);
  5121. }
  5122. this._isZOffsetDirty = false;
  5123. }
  5124. };
  5125. return _DepthCullingState;
  5126. })();
  5127. BABYLON._DepthCullingState = _DepthCullingState;
  5128. var _AlphaState = (function () {
  5129. function _AlphaState() {
  5130. this._isAlphaBlendDirty = false;
  5131. this._isBlendFunctionParametersDirty = false;
  5132. this._alphaBlend = false;
  5133. this._blendFunctionParameters = new Array(4);
  5134. }
  5135. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5136. get: function () {
  5137. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5138. },
  5139. enumerable: true,
  5140. configurable: true
  5141. });
  5142. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5143. get: function () {
  5144. return this._alphaBlend;
  5145. },
  5146. set: function (value) {
  5147. if (this._alphaBlend === value) {
  5148. return;
  5149. }
  5150. this._alphaBlend = value;
  5151. this._isAlphaBlendDirty = true;
  5152. },
  5153. enumerable: true,
  5154. configurable: true
  5155. });
  5156. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5157. if (this._blendFunctionParameters[0] === value0 &&
  5158. this._blendFunctionParameters[1] === value1 &&
  5159. this._blendFunctionParameters[2] === value2 &&
  5160. this._blendFunctionParameters[3] === value3) {
  5161. return;
  5162. }
  5163. this._blendFunctionParameters[0] = value0;
  5164. this._blendFunctionParameters[1] = value1;
  5165. this._blendFunctionParameters[2] = value2;
  5166. this._blendFunctionParameters[3] = value3;
  5167. this._isBlendFunctionParametersDirty = true;
  5168. };
  5169. _AlphaState.prototype.reset = function () {
  5170. this._alphaBlend = false;
  5171. this._blendFunctionParameters[0] = null;
  5172. this._blendFunctionParameters[1] = null;
  5173. this._blendFunctionParameters[2] = null;
  5174. this._blendFunctionParameters[3] = null;
  5175. this._isAlphaBlendDirty = true;
  5176. this._isBlendFunctionParametersDirty = false;
  5177. };
  5178. _AlphaState.prototype.apply = function (gl) {
  5179. if (!this.isDirty) {
  5180. return;
  5181. }
  5182. // Alpha blend
  5183. if (this._isAlphaBlendDirty) {
  5184. if (this._alphaBlend) {
  5185. gl.enable(gl.BLEND);
  5186. }
  5187. else {
  5188. gl.disable(gl.BLEND);
  5189. }
  5190. this._isAlphaBlendDirty = false;
  5191. }
  5192. // Alpha function
  5193. if (this._isBlendFunctionParametersDirty) {
  5194. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5195. this._isBlendFunctionParametersDirty = false;
  5196. }
  5197. };
  5198. return _AlphaState;
  5199. })();
  5200. BABYLON._AlphaState = _AlphaState;
  5201. var compileShader = function (gl, source, type, defines) {
  5202. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5203. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5204. gl.compileShader(shader);
  5205. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5206. throw new Error(gl.getShaderInfoLog(shader));
  5207. }
  5208. return shader;
  5209. };
  5210. var getWebGLTextureType = function (gl, type) {
  5211. var textureType = gl.UNSIGNED_BYTE;
  5212. if (type === Engine.TEXTURETYPE_FLOAT)
  5213. textureType = gl.FLOAT;
  5214. return textureType;
  5215. };
  5216. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5217. var magFilter = gl.NEAREST;
  5218. var minFilter = gl.NEAREST;
  5219. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5220. magFilter = gl.LINEAR;
  5221. if (generateMipMaps) {
  5222. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5223. }
  5224. else {
  5225. minFilter = gl.LINEAR;
  5226. }
  5227. }
  5228. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5229. magFilter = gl.LINEAR;
  5230. if (generateMipMaps) {
  5231. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5232. }
  5233. else {
  5234. minFilter = gl.LINEAR;
  5235. }
  5236. }
  5237. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5238. magFilter = gl.NEAREST;
  5239. if (generateMipMaps) {
  5240. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5241. }
  5242. else {
  5243. minFilter = gl.NEAREST;
  5244. }
  5245. }
  5246. return {
  5247. min: minFilter,
  5248. mag: magFilter
  5249. };
  5250. };
  5251. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5252. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5253. var engine = scene.getEngine();
  5254. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  5255. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  5256. gl.bindTexture(gl.TEXTURE_2D, texture);
  5257. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5258. texture._baseWidth = width;
  5259. texture._baseHeight = height;
  5260. texture._width = potWidth;
  5261. texture._height = potHeight;
  5262. texture.isReady = true;
  5263. processFunction(potWidth, potHeight);
  5264. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5265. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5266. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5267. if (!noMipmap && !isCompressed) {
  5268. gl.generateMipmap(gl.TEXTURE_2D);
  5269. }
  5270. gl.bindTexture(gl.TEXTURE_2D, null);
  5271. engine._activeTexturesCache = [];
  5272. scene._removePendingData(texture);
  5273. };
  5274. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5275. var onload = function () {
  5276. loadedImages[index] = img;
  5277. loadedImages._internalCount++;
  5278. scene._removePendingData(img);
  5279. if (loadedImages._internalCount === 6) {
  5280. onfinish(loadedImages);
  5281. }
  5282. };
  5283. var onerror = function () {
  5284. scene._removePendingData(img);
  5285. };
  5286. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5287. scene._addPendingData(img);
  5288. };
  5289. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5290. var loadedImages = [];
  5291. loadedImages._internalCount = 0;
  5292. for (var index = 0; index < 6; index++) {
  5293. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5294. }
  5295. };
  5296. var EngineCapabilities = (function () {
  5297. function EngineCapabilities() {
  5298. }
  5299. return EngineCapabilities;
  5300. })();
  5301. BABYLON.EngineCapabilities = EngineCapabilities;
  5302. /**
  5303. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5304. */
  5305. var Engine = (function () {
  5306. /**
  5307. * @constructor
  5308. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5309. * @param {boolean} [antialias] - enable antialias
  5310. * @param options - further options to be sent to the getContext function
  5311. */
  5312. function Engine(canvas, antialias, options) {
  5313. var _this = this;
  5314. // Public members
  5315. this.isFullscreen = false;
  5316. this.isPointerLock = false;
  5317. this.cullBackFaces = true;
  5318. this.renderEvenInBackground = true;
  5319. this.scenes = new Array();
  5320. this._windowIsBackground = false;
  5321. this._loadingDivBackgroundColor = "black";
  5322. this._drawCalls = 0;
  5323. this._renderingQueueLaunched = false;
  5324. this._activeRenderLoops = [];
  5325. // FPS
  5326. this.fpsRange = 60;
  5327. this.previousFramesDuration = [];
  5328. this.fps = 60;
  5329. this.deltaTime = 0;
  5330. // States
  5331. this._depthCullingState = new _DepthCullingState();
  5332. this._alphaState = new _AlphaState();
  5333. this._alphaMode = Engine.ALPHA_DISABLE;
  5334. // Cache
  5335. this._loadedTexturesCache = new Array();
  5336. this._activeTexturesCache = new Array();
  5337. this._compiledEffects = {};
  5338. this._uintIndicesCurrentlySet = false;
  5339. this._renderingCanvas = canvas;
  5340. options = options || {};
  5341. options.antialias = antialias;
  5342. // GL
  5343. try {
  5344. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  5345. }
  5346. catch (e) {
  5347. throw new Error("WebGL not supported");
  5348. }
  5349. if (!this._gl) {
  5350. throw new Error("WebGL not supported");
  5351. }
  5352. this._onBlur = function () {
  5353. _this._windowIsBackground = true;
  5354. };
  5355. this._onFocus = function () {
  5356. _this._windowIsBackground = false;
  5357. };
  5358. window.addEventListener("blur", this._onBlur);
  5359. window.addEventListener("focus", this._onFocus);
  5360. // Viewport
  5361. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  5362. this.resize();
  5363. // Caps
  5364. this._caps = new EngineCapabilities();
  5365. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5366. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5367. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5368. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5369. // Infos
  5370. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5371. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5372. if (rendererInfo != null) {
  5373. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5374. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5375. }
  5376. if (!this._glVendor) {
  5377. this._glVendor = "Unknown vendor";
  5378. }
  5379. if (!this._glRenderer) {
  5380. this._glRenderer = "Unknown renderer";
  5381. }
  5382. // Extensions
  5383. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5384. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5385. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5386. 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');
  5387. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5388. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5389. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5390. this._caps.highPrecisionShaderSupported = true;
  5391. if (this._gl.getShaderPrecisionFormat) {
  5392. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5393. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  5394. }
  5395. // Depth buffer
  5396. this.setDepthBuffer(true);
  5397. this.setDepthFunctionToLessOrEqual();
  5398. this.setDepthWrite(true);
  5399. // Fullscreen
  5400. this._onFullscreenChange = function () {
  5401. if (document.fullscreen !== undefined) {
  5402. _this.isFullscreen = document.fullscreen;
  5403. }
  5404. else if (document.mozFullScreen !== undefined) {
  5405. _this.isFullscreen = document.mozFullScreen;
  5406. }
  5407. else if (document.webkitIsFullScreen !== undefined) {
  5408. _this.isFullscreen = document.webkitIsFullScreen;
  5409. }
  5410. else if (document.msIsFullScreen !== undefined) {
  5411. _this.isFullscreen = document.msIsFullScreen;
  5412. }
  5413. // Pointer lock
  5414. if (_this.isFullscreen && _this._pointerLockRequested) {
  5415. canvas.requestPointerLock = canvas.requestPointerLock ||
  5416. canvas.msRequestPointerLock ||
  5417. canvas.mozRequestPointerLock ||
  5418. canvas.webkitRequestPointerLock;
  5419. if (canvas.requestPointerLock) {
  5420. canvas.requestPointerLock();
  5421. }
  5422. }
  5423. };
  5424. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5425. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5426. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5427. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5428. // Pointer lock
  5429. this._onPointerLockChange = function () {
  5430. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5431. document.webkitPointerLockElement === canvas ||
  5432. document.msPointerLockElement === canvas ||
  5433. document.pointerLockElement === canvas);
  5434. };
  5435. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5436. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5437. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5438. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5439. if (!Engine.audioEngine) {
  5440. Engine.audioEngine = new BABYLON.AudioEngine();
  5441. }
  5442. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5443. }
  5444. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5445. get: function () {
  5446. return Engine._ALPHA_DISABLE;
  5447. },
  5448. enumerable: true,
  5449. configurable: true
  5450. });
  5451. Object.defineProperty(Engine, "ALPHA_ADD", {
  5452. get: function () {
  5453. return Engine._ALPHA_ADD;
  5454. },
  5455. enumerable: true,
  5456. configurable: true
  5457. });
  5458. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5459. get: function () {
  5460. return Engine._ALPHA_COMBINE;
  5461. },
  5462. enumerable: true,
  5463. configurable: true
  5464. });
  5465. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5466. get: function () {
  5467. return Engine._DELAYLOADSTATE_NONE;
  5468. },
  5469. enumerable: true,
  5470. configurable: true
  5471. });
  5472. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5473. get: function () {
  5474. return Engine._DELAYLOADSTATE_LOADED;
  5475. },
  5476. enumerable: true,
  5477. configurable: true
  5478. });
  5479. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5480. get: function () {
  5481. return Engine._DELAYLOADSTATE_LOADING;
  5482. },
  5483. enumerable: true,
  5484. configurable: true
  5485. });
  5486. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5487. get: function () {
  5488. return Engine._DELAYLOADSTATE_NOTLOADED;
  5489. },
  5490. enumerable: true,
  5491. configurable: true
  5492. });
  5493. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5494. get: function () {
  5495. return Engine._TEXTUREFORMAT_ALPHA;
  5496. },
  5497. enumerable: true,
  5498. configurable: true
  5499. });
  5500. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5501. get: function () {
  5502. return Engine._TEXTUREFORMAT_LUMINANCE;
  5503. },
  5504. enumerable: true,
  5505. configurable: true
  5506. });
  5507. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5508. get: function () {
  5509. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5510. },
  5511. enumerable: true,
  5512. configurable: true
  5513. });
  5514. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5515. get: function () {
  5516. return Engine._TEXTUREFORMAT_RGB;
  5517. },
  5518. enumerable: true,
  5519. configurable: true
  5520. });
  5521. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5522. get: function () {
  5523. return Engine._TEXTUREFORMAT_RGBA;
  5524. },
  5525. enumerable: true,
  5526. configurable: true
  5527. });
  5528. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5529. get: function () {
  5530. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5531. },
  5532. enumerable: true,
  5533. configurable: true
  5534. });
  5535. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5536. get: function () {
  5537. return Engine._TEXTURETYPE_FLOAT;
  5538. },
  5539. enumerable: true,
  5540. configurable: true
  5541. });
  5542. Object.defineProperty(Engine, "Version", {
  5543. get: function () {
  5544. return "2.1.0";
  5545. },
  5546. enumerable: true,
  5547. configurable: true
  5548. });
  5549. Engine.prototype._prepareWorkingCanvas = function () {
  5550. if (this._workingCanvas) {
  5551. return;
  5552. }
  5553. this._workingCanvas = document.createElement("canvas");
  5554. this._workingContext = this._workingCanvas.getContext("2d");
  5555. };
  5556. Engine.prototype.getGlInfo = function () {
  5557. return {
  5558. vendor: this._glVendor,
  5559. renderer: this._glRenderer,
  5560. version: this._glVersion
  5561. };
  5562. };
  5563. Engine.prototype.getAspectRatio = function (camera) {
  5564. var viewport = camera.viewport;
  5565. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5566. };
  5567. Engine.prototype.getRenderWidth = function () {
  5568. if (this._currentRenderTarget) {
  5569. return this._currentRenderTarget._width;
  5570. }
  5571. return this._renderingCanvas.width;
  5572. };
  5573. Engine.prototype.getRenderHeight = function () {
  5574. if (this._currentRenderTarget) {
  5575. return this._currentRenderTarget._height;
  5576. }
  5577. return this._renderingCanvas.height;
  5578. };
  5579. Engine.prototype.getRenderingCanvas = function () {
  5580. return this._renderingCanvas;
  5581. };
  5582. Engine.prototype.getRenderingCanvasClientRect = function () {
  5583. return this._renderingCanvas.getBoundingClientRect();
  5584. };
  5585. Engine.prototype.setHardwareScalingLevel = function (level) {
  5586. this._hardwareScalingLevel = level;
  5587. this.resize();
  5588. };
  5589. Engine.prototype.getHardwareScalingLevel = function () {
  5590. return this._hardwareScalingLevel;
  5591. };
  5592. Engine.prototype.getLoadedTexturesCache = function () {
  5593. return this._loadedTexturesCache;
  5594. };
  5595. Engine.prototype.getCaps = function () {
  5596. return this._caps;
  5597. };
  5598. Object.defineProperty(Engine.prototype, "drawCalls", {
  5599. get: function () {
  5600. return this._drawCalls;
  5601. },
  5602. enumerable: true,
  5603. configurable: true
  5604. });
  5605. // Methods
  5606. Engine.prototype.resetDrawCalls = function () {
  5607. this._drawCalls = 0;
  5608. };
  5609. Engine.prototype.setDepthFunctionToGreater = function () {
  5610. this._depthCullingState.depthFunc = this._gl.GREATER;
  5611. };
  5612. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5613. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5614. };
  5615. Engine.prototype.setDepthFunctionToLess = function () {
  5616. this._depthCullingState.depthFunc = this._gl.LESS;
  5617. };
  5618. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5619. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5620. };
  5621. /**
  5622. * stop executing a render loop function and remove it from the execution array
  5623. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5624. */
  5625. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5626. if (!renderFunction) {
  5627. this._activeRenderLoops = [];
  5628. return;
  5629. }
  5630. var index = this._activeRenderLoops.indexOf(renderFunction);
  5631. if (index >= 0) {
  5632. this._activeRenderLoops.splice(index, 1);
  5633. }
  5634. };
  5635. Engine.prototype._renderLoop = function () {
  5636. var _this = this;
  5637. var shouldRender = true;
  5638. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5639. shouldRender = false;
  5640. }
  5641. if (shouldRender) {
  5642. // Start new frame
  5643. this.beginFrame();
  5644. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5645. var renderFunction = this._activeRenderLoops[index];
  5646. renderFunction();
  5647. }
  5648. // Present
  5649. this.endFrame();
  5650. }
  5651. if (this._activeRenderLoops.length > 0) {
  5652. // Register new frame
  5653. BABYLON.Tools.QueueNewFrame(function () {
  5654. _this._renderLoop();
  5655. });
  5656. }
  5657. else {
  5658. this._renderingQueueLaunched = false;
  5659. }
  5660. };
  5661. /**
  5662. * Register and execute a render loop. The engine can have more than one render function.
  5663. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5664. * @example
  5665. * engine.runRenderLoop(function () {
  5666. * scene.render()
  5667. * })
  5668. */
  5669. Engine.prototype.runRenderLoop = function (renderFunction) {
  5670. var _this = this;
  5671. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5672. return;
  5673. }
  5674. this._activeRenderLoops.push(renderFunction);
  5675. if (!this._renderingQueueLaunched) {
  5676. this._renderingQueueLaunched = true;
  5677. BABYLON.Tools.QueueNewFrame(function () {
  5678. _this._renderLoop();
  5679. });
  5680. }
  5681. };
  5682. /**
  5683. * Toggle full screen mode.
  5684. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5685. */
  5686. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5687. if (this.isFullscreen) {
  5688. BABYLON.Tools.ExitFullscreen();
  5689. }
  5690. else {
  5691. this._pointerLockRequested = requestPointerLock;
  5692. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5693. }
  5694. };
  5695. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5696. this.applyStates();
  5697. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5698. if (this._depthCullingState.depthMask) {
  5699. this._gl.clearDepth(1.0);
  5700. }
  5701. var mode = 0;
  5702. if (backBuffer)
  5703. mode |= this._gl.COLOR_BUFFER_BIT;
  5704. if (depthStencil && this._depthCullingState.depthMask)
  5705. mode |= this._gl.DEPTH_BUFFER_BIT;
  5706. this._gl.clear(mode);
  5707. };
  5708. /**
  5709. * Set the WebGL's viewport
  5710. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5711. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5712. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5713. */
  5714. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5715. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5716. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5717. var x = viewport.x || 0;
  5718. var y = viewport.y || 0;
  5719. this._cachedViewport = viewport;
  5720. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5721. };
  5722. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5723. this._cachedViewport = null;
  5724. this._gl.viewport(x, y, width, height);
  5725. };
  5726. Engine.prototype.beginFrame = function () {
  5727. this._measureFps();
  5728. };
  5729. Engine.prototype.endFrame = function () {
  5730. //this.flushFramebuffer();
  5731. };
  5732. /**
  5733. * resize the view according to the canvas' size.
  5734. * @example
  5735. * window.addEventListener("resize", function () {
  5736. * engine.resize();
  5737. * });
  5738. */
  5739. Engine.prototype.resize = function () {
  5740. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5741. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5742. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5743. };
  5744. /**
  5745. * force a specific size of the canvas
  5746. * @param {number} width - the new canvas' width
  5747. * @param {number} height - the new canvas' height
  5748. */
  5749. Engine.prototype.setSize = function (width, height) {
  5750. this._renderingCanvas.width = width;
  5751. this._renderingCanvas.height = height;
  5752. for (var index = 0; index < this.scenes.length; index++) {
  5753. var scene = this.scenes[index];
  5754. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5755. var cam = scene.cameras[camIndex];
  5756. cam._currentRenderId = 0;
  5757. }
  5758. }
  5759. };
  5760. Engine.prototype.bindFramebuffer = function (texture) {
  5761. this._currentRenderTarget = texture;
  5762. var gl = this._gl;
  5763. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5764. this._gl.viewport(0, 0, texture._width, texture._height);
  5765. this.wipeCaches();
  5766. };
  5767. Engine.prototype.unBindFramebuffer = function (texture) {
  5768. this._currentRenderTarget = null;
  5769. if (texture.generateMipMaps) {
  5770. var gl = this._gl;
  5771. gl.bindTexture(gl.TEXTURE_2D, texture);
  5772. gl.generateMipmap(gl.TEXTURE_2D);
  5773. gl.bindTexture(gl.TEXTURE_2D, null);
  5774. }
  5775. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5776. };
  5777. Engine.prototype.flushFramebuffer = function () {
  5778. this._gl.flush();
  5779. };
  5780. Engine.prototype.restoreDefaultFramebuffer = function () {
  5781. this._currentRenderTarget = null;
  5782. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5783. this.setViewport(this._cachedViewport);
  5784. this.wipeCaches();
  5785. };
  5786. // VBOs
  5787. Engine.prototype._resetVertexBufferBinding = function () {
  5788. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5789. this._cachedVertexBuffers = null;
  5790. };
  5791. Engine.prototype.createVertexBuffer = function (vertices) {
  5792. var vbo = this._gl.createBuffer();
  5793. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5794. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5795. this._resetVertexBufferBinding();
  5796. vbo.references = 1;
  5797. return vbo;
  5798. };
  5799. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5800. var vbo = this._gl.createBuffer();
  5801. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5802. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5803. this._resetVertexBufferBinding();
  5804. vbo.references = 1;
  5805. return vbo;
  5806. };
  5807. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5808. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5809. if (offset === undefined) {
  5810. offset = 0;
  5811. }
  5812. if (vertices instanceof Float32Array) {
  5813. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5814. }
  5815. else {
  5816. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5817. }
  5818. this._resetVertexBufferBinding();
  5819. };
  5820. Engine.prototype._resetIndexBufferBinding = function () {
  5821. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5822. this._cachedIndexBuffer = null;
  5823. };
  5824. Engine.prototype.createIndexBuffer = function (indices) {
  5825. var vbo = this._gl.createBuffer();
  5826. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5827. // Check for 32 bits indices
  5828. var arrayBuffer;
  5829. var need32Bits = false;
  5830. if (this._caps.uintIndices) {
  5831. for (var index = 0; index < indices.length; index++) {
  5832. if (indices[index] > 65535) {
  5833. need32Bits = true;
  5834. break;
  5835. }
  5836. }
  5837. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5838. }
  5839. else {
  5840. arrayBuffer = new Uint16Array(indices);
  5841. }
  5842. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5843. this._resetIndexBufferBinding();
  5844. vbo.references = 1;
  5845. vbo.is32Bits = need32Bits;
  5846. return vbo;
  5847. };
  5848. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5849. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5850. this._cachedVertexBuffers = vertexBuffer;
  5851. this._cachedEffectForVertexBuffers = effect;
  5852. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5853. var offset = 0;
  5854. for (var index = 0; index < vertexDeclaration.length; index++) {
  5855. var order = effect.getAttributeLocation(index);
  5856. if (order >= 0) {
  5857. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5858. }
  5859. offset += vertexDeclaration[index] * 4;
  5860. }
  5861. }
  5862. if (this._cachedIndexBuffer !== indexBuffer) {
  5863. this._cachedIndexBuffer = indexBuffer;
  5864. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5865. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5866. }
  5867. };
  5868. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5869. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5870. this._cachedVertexBuffers = vertexBuffers;
  5871. this._cachedEffectForVertexBuffers = effect;
  5872. var attributes = effect.getAttributesNames();
  5873. for (var index = 0; index < attributes.length; index++) {
  5874. var order = effect.getAttributeLocation(index);
  5875. if (order >= 0) {
  5876. var vertexBuffer = vertexBuffers[attributes[index]];
  5877. if (!vertexBuffer) {
  5878. continue;
  5879. }
  5880. var stride = vertexBuffer.getStrideSize();
  5881. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5882. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5883. }
  5884. }
  5885. }
  5886. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5887. this._cachedIndexBuffer = indexBuffer;
  5888. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5889. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5890. }
  5891. };
  5892. Engine.prototype._releaseBuffer = function (buffer) {
  5893. buffer.references--;
  5894. if (buffer.references === 0) {
  5895. this._gl.deleteBuffer(buffer);
  5896. return true;
  5897. }
  5898. return false;
  5899. };
  5900. Engine.prototype.createInstancesBuffer = function (capacity) {
  5901. var buffer = this._gl.createBuffer();
  5902. buffer.capacity = capacity;
  5903. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5904. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5905. return buffer;
  5906. };
  5907. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5908. this._gl.deleteBuffer(buffer);
  5909. };
  5910. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5911. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5912. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5913. for (var index = 0; index < 4; index++) {
  5914. var offsetLocation = offsetLocations[index];
  5915. this._gl.enableVertexAttribArray(offsetLocation);
  5916. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5917. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5918. }
  5919. };
  5920. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5921. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5922. for (var index = 0; index < 4; index++) {
  5923. var offsetLocation = offsetLocations[index];
  5924. this._gl.disableVertexAttribArray(offsetLocation);
  5925. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5926. }
  5927. };
  5928. Engine.prototype.applyStates = function () {
  5929. this._depthCullingState.apply(this._gl);
  5930. this._alphaState.apply(this._gl);
  5931. };
  5932. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5933. // Apply states
  5934. this.applyStates();
  5935. this._drawCalls++;
  5936. // Render
  5937. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5938. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5939. if (instancesCount) {
  5940. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5941. return;
  5942. }
  5943. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5944. };
  5945. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5946. // Apply states
  5947. this.applyStates();
  5948. this._drawCalls++;
  5949. if (instancesCount) {
  5950. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5951. return;
  5952. }
  5953. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5954. };
  5955. // Shaders
  5956. Engine.prototype._releaseEffect = function (effect) {
  5957. if (this._compiledEffects[effect._key]) {
  5958. delete this._compiledEffects[effect._key];
  5959. if (effect.getProgram()) {
  5960. this._gl.deleteProgram(effect.getProgram());
  5961. }
  5962. }
  5963. };
  5964. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5965. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5966. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5967. var name = vertex + "+" + fragment + "@" + defines;
  5968. if (this._compiledEffects[name]) {
  5969. return this._compiledEffects[name];
  5970. }
  5971. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5972. effect._key = name;
  5973. this._compiledEffects[name] = effect;
  5974. return effect;
  5975. };
  5976. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5977. if (uniformsNames === void 0) { uniformsNames = []; }
  5978. if (samplers === void 0) { samplers = []; }
  5979. if (defines === void 0) { defines = ""; }
  5980. return this.createEffect({
  5981. vertex: "particles",
  5982. fragmentElement: fragmentName
  5983. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5984. };
  5985. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5986. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5987. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5988. var shaderProgram = this._gl.createProgram();
  5989. this._gl.attachShader(shaderProgram, vertexShader);
  5990. this._gl.attachShader(shaderProgram, fragmentShader);
  5991. this._gl.linkProgram(shaderProgram);
  5992. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5993. if (!linked) {
  5994. var error = this._gl.getProgramInfoLog(shaderProgram);
  5995. if (error) {
  5996. throw new Error(error);
  5997. }
  5998. }
  5999. this._gl.deleteShader(vertexShader);
  6000. this._gl.deleteShader(fragmentShader);
  6001. return shaderProgram;
  6002. };
  6003. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6004. var results = [];
  6005. for (var index = 0; index < uniformsNames.length; index++) {
  6006. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6007. }
  6008. return results;
  6009. };
  6010. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6011. var results = [];
  6012. for (var index = 0; index < attributesNames.length; index++) {
  6013. try {
  6014. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6015. }
  6016. catch (e) {
  6017. results.push(-1);
  6018. }
  6019. }
  6020. return results;
  6021. };
  6022. Engine.prototype.enableEffect = function (effect) {
  6023. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6024. if (effect && effect.onBind) {
  6025. effect.onBind(effect);
  6026. }
  6027. return;
  6028. }
  6029. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6030. // Use program
  6031. this._gl.useProgram(effect.getProgram());
  6032. for (var i in this._vertexAttribArrays) {
  6033. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6034. continue;
  6035. }
  6036. this._vertexAttribArrays[i] = false;
  6037. this._gl.disableVertexAttribArray(i);
  6038. }
  6039. var attributesCount = effect.getAttributesCount();
  6040. for (var index = 0; index < attributesCount; index++) {
  6041. // Attributes
  6042. var order = effect.getAttributeLocation(index);
  6043. if (order >= 0) {
  6044. this._vertexAttribArrays[order] = true;
  6045. this._gl.enableVertexAttribArray(order);
  6046. }
  6047. }
  6048. this._currentEffect = effect;
  6049. if (effect.onBind) {
  6050. effect.onBind(effect);
  6051. }
  6052. };
  6053. Engine.prototype.setArray = function (uniform, array) {
  6054. if (!uniform)
  6055. return;
  6056. this._gl.uniform1fv(uniform, array);
  6057. };
  6058. Engine.prototype.setArray2 = function (uniform, array) {
  6059. if (!uniform || array.length % 2 !== 0)
  6060. return;
  6061. this._gl.uniform2fv(uniform, array);
  6062. };
  6063. Engine.prototype.setArray3 = function (uniform, array) {
  6064. if (!uniform || array.length % 3 !== 0)
  6065. return;
  6066. this._gl.uniform3fv(uniform, array);
  6067. };
  6068. Engine.prototype.setArray4 = function (uniform, array) {
  6069. if (!uniform || array.length % 4 !== 0)
  6070. return;
  6071. this._gl.uniform4fv(uniform, array);
  6072. };
  6073. Engine.prototype.setMatrices = function (uniform, matrices) {
  6074. if (!uniform)
  6075. return;
  6076. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6077. };
  6078. Engine.prototype.setMatrix = function (uniform, matrix) {
  6079. if (!uniform)
  6080. return;
  6081. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6082. };
  6083. Engine.prototype.setFloat = function (uniform, value) {
  6084. if (!uniform)
  6085. return;
  6086. this._gl.uniform1f(uniform, value);
  6087. };
  6088. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6089. if (!uniform)
  6090. return;
  6091. this._gl.uniform2f(uniform, x, y);
  6092. };
  6093. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6094. if (!uniform)
  6095. return;
  6096. this._gl.uniform3f(uniform, x, y, z);
  6097. };
  6098. Engine.prototype.setBool = function (uniform, bool) {
  6099. if (!uniform)
  6100. return;
  6101. this._gl.uniform1i(uniform, bool);
  6102. };
  6103. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6104. if (!uniform)
  6105. return;
  6106. this._gl.uniform4f(uniform, x, y, z, w);
  6107. };
  6108. Engine.prototype.setColor3 = function (uniform, color3) {
  6109. if (!uniform)
  6110. return;
  6111. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6112. };
  6113. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6114. if (!uniform)
  6115. return;
  6116. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6117. };
  6118. // States
  6119. Engine.prototype.setState = function (culling, zOffset, force) {
  6120. if (zOffset === void 0) { zOffset = 0; }
  6121. // Culling
  6122. if (this._depthCullingState.cull !== culling || force) {
  6123. if (culling) {
  6124. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  6125. this._depthCullingState.cull = true;
  6126. }
  6127. else {
  6128. this._depthCullingState.cull = false;
  6129. }
  6130. }
  6131. // Z offset
  6132. this._depthCullingState.zOffset = zOffset;
  6133. };
  6134. Engine.prototype.setDepthBuffer = function (enable) {
  6135. this._depthCullingState.depthTest = enable;
  6136. };
  6137. Engine.prototype.getDepthWrite = function () {
  6138. return this._depthCullingState.depthMask;
  6139. };
  6140. Engine.prototype.setDepthWrite = function (enable) {
  6141. this._depthCullingState.depthMask = enable;
  6142. };
  6143. Engine.prototype.setColorWrite = function (enable) {
  6144. this._gl.colorMask(enable, enable, enable, enable);
  6145. };
  6146. Engine.prototype.setAlphaMode = function (mode) {
  6147. switch (mode) {
  6148. case Engine.ALPHA_DISABLE:
  6149. this.setDepthWrite(true);
  6150. this._alphaState.alphaBlend = false;
  6151. break;
  6152. case Engine.ALPHA_COMBINE:
  6153. this.setDepthWrite(false);
  6154. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6155. this._alphaState.alphaBlend = true;
  6156. break;
  6157. case Engine.ALPHA_ADD:
  6158. this.setDepthWrite(false);
  6159. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6160. this._alphaState.alphaBlend = true;
  6161. break;
  6162. }
  6163. this._alphaMode = mode;
  6164. };
  6165. Engine.prototype.getAlphaMode = function () {
  6166. return this._alphaMode;
  6167. };
  6168. Engine.prototype.setAlphaTesting = function (enable) {
  6169. this._alphaTest = enable;
  6170. };
  6171. Engine.prototype.getAlphaTesting = function () {
  6172. return this._alphaTest;
  6173. };
  6174. // Textures
  6175. Engine.prototype.wipeCaches = function () {
  6176. this._activeTexturesCache = [];
  6177. this._currentEffect = null;
  6178. this._depthCullingState.reset();
  6179. this._alphaState.reset();
  6180. this._cachedVertexBuffers = null;
  6181. this._cachedIndexBuffer = null;
  6182. this._cachedEffectForVertexBuffers = null;
  6183. };
  6184. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6185. var gl = this._gl;
  6186. gl.bindTexture(gl.TEXTURE_2D, texture);
  6187. var magFilter = gl.NEAREST;
  6188. var minFilter = gl.NEAREST;
  6189. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6190. magFilter = gl.LINEAR;
  6191. minFilter = gl.LINEAR;
  6192. }
  6193. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6194. magFilter = gl.LINEAR;
  6195. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6196. }
  6197. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6198. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6199. gl.bindTexture(gl.TEXTURE_2D, null);
  6200. texture.samplingMode = samplingMode;
  6201. };
  6202. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6203. var _this = this;
  6204. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6205. if (onLoad === void 0) { onLoad = null; }
  6206. if (onError === void 0) { onError = null; }
  6207. if (buffer === void 0) { buffer = null; }
  6208. var texture = this._gl.createTexture();
  6209. var extension;
  6210. var fromData = false;
  6211. if (url.substr(0, 5) === "data:") {
  6212. fromData = true;
  6213. }
  6214. if (!fromData)
  6215. extension = url.substr(url.length - 4, 4).toLowerCase();
  6216. else {
  6217. var oldUrl = url;
  6218. fromData = oldUrl.split(':');
  6219. url = oldUrl;
  6220. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6221. }
  6222. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6223. var isTGA = (extension === ".tga");
  6224. scene._addPendingData(texture);
  6225. texture.url = url;
  6226. texture.noMipmap = noMipmap;
  6227. texture.references = 1;
  6228. texture.samplingMode = samplingMode;
  6229. this._loadedTexturesCache.push(texture);
  6230. var onerror = function () {
  6231. scene._removePendingData(texture);
  6232. if (onError) {
  6233. onError();
  6234. }
  6235. };
  6236. if (isTGA) {
  6237. var callback = function (arrayBuffer) {
  6238. var data = new Uint8Array(arrayBuffer);
  6239. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6240. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6241. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6242. if (onLoad) {
  6243. onLoad();
  6244. }
  6245. }, samplingMode);
  6246. };
  6247. if (!(fromData instanceof Array))
  6248. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6249. callback(arrayBuffer);
  6250. }, onerror, scene.database, true);
  6251. else
  6252. callback(buffer);
  6253. }
  6254. else if (isDDS) {
  6255. callback = function (data) {
  6256. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6257. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6258. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6259. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6260. if (onLoad) {
  6261. onLoad();
  6262. }
  6263. }, samplingMode);
  6264. };
  6265. if (!(fromData instanceof Array))
  6266. BABYLON.Tools.LoadFile(url, function (data) {
  6267. callback(data);
  6268. }, onerror, scene.database, true);
  6269. else
  6270. callback(buffer);
  6271. }
  6272. else {
  6273. var onload = function (img) {
  6274. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6275. var isPot = (img.width === potWidth && img.height === potHeight);
  6276. if (!isPot) {
  6277. _this._prepareWorkingCanvas();
  6278. _this._workingCanvas.width = potWidth;
  6279. _this._workingCanvas.height = potHeight;
  6280. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6281. _this._workingContext.imageSmoothingEnabled = false;
  6282. _this._workingContext.mozImageSmoothingEnabled = false;
  6283. _this._workingContext.oImageSmoothingEnabled = false;
  6284. _this._workingContext.webkitImageSmoothingEnabled = false;
  6285. _this._workingContext.msImageSmoothingEnabled = false;
  6286. }
  6287. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6288. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6289. _this._workingContext.imageSmoothingEnabled = true;
  6290. _this._workingContext.mozImageSmoothingEnabled = true;
  6291. _this._workingContext.oImageSmoothingEnabled = true;
  6292. _this._workingContext.webkitImageSmoothingEnabled = true;
  6293. _this._workingContext.msImageSmoothingEnabled = true;
  6294. }
  6295. }
  6296. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6297. if (onLoad) {
  6298. onLoad();
  6299. }
  6300. }, samplingMode);
  6301. };
  6302. if (!(fromData instanceof Array))
  6303. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6304. else
  6305. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6306. }
  6307. return texture;
  6308. };
  6309. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  6310. var texture = this._gl.createTexture();
  6311. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6312. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6313. // Format
  6314. var internalFormat = this._gl.RGBA;
  6315. switch (format) {
  6316. case Engine.TEXTUREFORMAT_ALPHA:
  6317. internalFormat = this._gl.ALPHA;
  6318. break;
  6319. case Engine.TEXTUREFORMAT_LUMINANCE:
  6320. internalFormat = this._gl.LUMINANCE;
  6321. break;
  6322. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6323. internalFormat = this._gl.LUMINANCE_ALPHA;
  6324. break;
  6325. case Engine.TEXTUREFORMAT_RGB:
  6326. internalFormat = this._gl.RGB;
  6327. break;
  6328. case Engine.TEXTUREFORMAT_RGBA:
  6329. internalFormat = this._gl.RGBA;
  6330. break;
  6331. }
  6332. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6333. if (generateMipMaps) {
  6334. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6335. }
  6336. // Filters
  6337. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6338. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6339. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6340. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6341. this._activeTexturesCache = [];
  6342. texture._baseWidth = width;
  6343. texture._baseHeight = height;
  6344. texture._width = width;
  6345. texture._height = height;
  6346. texture.isReady = true;
  6347. texture.references = 1;
  6348. texture.samplingMode = samplingMode;
  6349. this._loadedTexturesCache.push(texture);
  6350. return texture;
  6351. };
  6352. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6353. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6354. var texture = this._gl.createTexture();
  6355. texture._baseWidth = width;
  6356. texture._baseHeight = height;
  6357. if (forceExponantOfTwo) {
  6358. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  6359. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  6360. }
  6361. this._activeTexturesCache = [];
  6362. texture._width = width;
  6363. texture._height = height;
  6364. texture.isReady = false;
  6365. texture.generateMipMaps = generateMipMaps;
  6366. texture.references = 1;
  6367. texture.samplingMode = samplingMode;
  6368. this.updateTextureSamplingMode(samplingMode, texture);
  6369. this._loadedTexturesCache.push(texture);
  6370. return texture;
  6371. };
  6372. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6373. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6374. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6375. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6376. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6377. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6378. };
  6379. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6380. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6381. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6382. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6383. if (texture.generateMipMaps) {
  6384. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6385. }
  6386. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6387. this._activeTexturesCache = [];
  6388. texture.isReady = true;
  6389. };
  6390. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6391. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6392. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6393. // Testing video texture support
  6394. if (this._videoTextureSupported === undefined) {
  6395. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6396. if (this._gl.getError() !== 0) {
  6397. this._videoTextureSupported = false;
  6398. }
  6399. else {
  6400. this._videoTextureSupported = true;
  6401. }
  6402. }
  6403. // Copy video through the current working canvas if video texture is not supported
  6404. if (!this._videoTextureSupported) {
  6405. if (!texture._workingCanvas) {
  6406. texture._workingCanvas = document.createElement("canvas");
  6407. texture._workingContext = texture._workingCanvas.getContext("2d");
  6408. texture._workingCanvas.width = texture._width;
  6409. texture._workingCanvas.height = texture._height;
  6410. }
  6411. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6412. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6413. }
  6414. else {
  6415. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6416. }
  6417. if (texture.generateMipMaps) {
  6418. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6419. }
  6420. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6421. this._activeTexturesCache = [];
  6422. texture.isReady = true;
  6423. };
  6424. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6425. // old version had a "generateMipMaps" arg instead of options.
  6426. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6427. // in the same way, generateDepthBuffer is defaulted to true
  6428. var generateMipMaps = false;
  6429. var generateDepthBuffer = true;
  6430. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6431. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6432. if (options !== undefined) {
  6433. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  6434. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6435. type = options.type === undefined ? type : options.type;
  6436. if (options.samplingMode !== undefined) {
  6437. samplingMode = options.samplingMode;
  6438. }
  6439. if (type === Engine.TEXTURETYPE_FLOAT) {
  6440. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6441. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6442. }
  6443. }
  6444. var gl = this._gl;
  6445. var texture = gl.createTexture();
  6446. gl.bindTexture(gl.TEXTURE_2D, texture);
  6447. var width = size.width || size;
  6448. var height = size.height || size;
  6449. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6450. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6451. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6452. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6453. }
  6454. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6455. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6456. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6457. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6458. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6459. var depthBuffer;
  6460. // Create the depth buffer
  6461. if (generateDepthBuffer) {
  6462. depthBuffer = gl.createRenderbuffer();
  6463. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6464. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6465. }
  6466. // Create the framebuffer
  6467. var framebuffer = gl.createFramebuffer();
  6468. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6469. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6470. if (generateDepthBuffer) {
  6471. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6472. }
  6473. if (generateMipMaps) {
  6474. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6475. }
  6476. // Unbind
  6477. gl.bindTexture(gl.TEXTURE_2D, null);
  6478. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6479. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6480. texture._framebuffer = framebuffer;
  6481. if (generateDepthBuffer) {
  6482. texture._depthBuffer = depthBuffer;
  6483. }
  6484. texture._width = width;
  6485. texture._height = height;
  6486. texture.isReady = true;
  6487. texture.generateMipMaps = generateMipMaps;
  6488. texture.references = 1;
  6489. texture.samplingMode = samplingMode;
  6490. this._activeTexturesCache = [];
  6491. this._loadedTexturesCache.push(texture);
  6492. return texture;
  6493. };
  6494. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6495. var _this = this;
  6496. var gl = this._gl;
  6497. var texture = gl.createTexture();
  6498. texture.isCube = true;
  6499. texture.url = rootUrl;
  6500. texture.references = 1;
  6501. this._loadedTexturesCache.push(texture);
  6502. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6503. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6504. if (isDDS) {
  6505. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6506. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6507. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6508. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6509. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6510. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6511. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6512. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6513. }
  6514. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6515. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6516. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6517. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6518. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6519. _this._activeTexturesCache = [];
  6520. texture._width = info.width;
  6521. texture._height = info.height;
  6522. texture.isReady = true;
  6523. }, null, null, true);
  6524. }
  6525. else {
  6526. cascadeLoad(rootUrl, scene, function (imgs) {
  6527. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6528. var height = width;
  6529. _this._prepareWorkingCanvas();
  6530. _this._workingCanvas.width = width;
  6531. _this._workingCanvas.height = height;
  6532. var faces = [
  6533. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6534. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6535. ];
  6536. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6537. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6538. for (var index = 0; index < faces.length; index++) {
  6539. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6540. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6541. }
  6542. if (!noMipmap) {
  6543. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6544. }
  6545. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6546. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6547. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6548. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6549. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6550. _this._activeTexturesCache = [];
  6551. texture._width = width;
  6552. texture._height = height;
  6553. texture.isReady = true;
  6554. }, extensions);
  6555. }
  6556. return texture;
  6557. };
  6558. Engine.prototype._releaseTexture = function (texture) {
  6559. var gl = this._gl;
  6560. if (texture._framebuffer) {
  6561. gl.deleteFramebuffer(texture._framebuffer);
  6562. }
  6563. if (texture._depthBuffer) {
  6564. gl.deleteRenderbuffer(texture._depthBuffer);
  6565. }
  6566. gl.deleteTexture(texture);
  6567. // Unbind channels
  6568. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6569. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6570. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6571. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6572. this._activeTexturesCache[channel] = null;
  6573. }
  6574. var index = this._loadedTexturesCache.indexOf(texture);
  6575. if (index !== -1) {
  6576. this._loadedTexturesCache.splice(index, 1);
  6577. }
  6578. };
  6579. Engine.prototype.bindSamplers = function (effect) {
  6580. this._gl.useProgram(effect.getProgram());
  6581. var samplers = effect.getSamplers();
  6582. for (var index = 0; index < samplers.length; index++) {
  6583. var uniform = effect.getUniform(samplers[index]);
  6584. this._gl.uniform1i(uniform, index);
  6585. }
  6586. this._currentEffect = null;
  6587. };
  6588. Engine.prototype._bindTexture = function (channel, texture) {
  6589. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6590. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6591. this._activeTexturesCache[channel] = null;
  6592. };
  6593. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6594. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6595. };
  6596. Engine.prototype.setTexture = function (channel, texture) {
  6597. if (channel < 0) {
  6598. return;
  6599. }
  6600. // Not ready?
  6601. if (!texture || !texture.isReady()) {
  6602. if (this._activeTexturesCache[channel] != null) {
  6603. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6604. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6605. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6606. this._activeTexturesCache[channel] = null;
  6607. }
  6608. return;
  6609. }
  6610. // Video
  6611. if (texture instanceof BABYLON.VideoTexture) {
  6612. if (texture.update()) {
  6613. this._activeTexturesCache[channel] = null;
  6614. }
  6615. }
  6616. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6617. texture.delayLoad();
  6618. return;
  6619. }
  6620. if (this._activeTexturesCache[channel] === texture) {
  6621. return;
  6622. }
  6623. this._activeTexturesCache[channel] = texture;
  6624. var internalTexture = texture.getInternalTexture();
  6625. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6626. if (internalTexture.isCube) {
  6627. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6628. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6629. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6630. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6631. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6632. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6633. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6634. }
  6635. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6636. }
  6637. else {
  6638. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6639. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6640. internalTexture._cachedWrapU = texture.wrapU;
  6641. switch (texture.wrapU) {
  6642. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6643. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6644. break;
  6645. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6646. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6647. break;
  6648. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6649. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6650. break;
  6651. }
  6652. }
  6653. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6654. internalTexture._cachedWrapV = texture.wrapV;
  6655. switch (texture.wrapV) {
  6656. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6657. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6658. break;
  6659. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6660. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6661. break;
  6662. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6663. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6664. break;
  6665. }
  6666. }
  6667. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6668. }
  6669. };
  6670. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6671. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6672. var value = texture.anisotropicFilteringLevel;
  6673. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6674. value = 1;
  6675. }
  6676. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6677. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6678. texture._cachedAnisotropicFilteringLevel = value;
  6679. }
  6680. };
  6681. Engine.prototype.readPixels = function (x, y, width, height) {
  6682. var data = new Uint8Array(height * width * 4);
  6683. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6684. return data;
  6685. };
  6686. // Dispose
  6687. Engine.prototype.dispose = function () {
  6688. this.hideLoadingUI();
  6689. this.stopRenderLoop();
  6690. // Release scenes
  6691. while (this.scenes.length) {
  6692. this.scenes[0].dispose();
  6693. }
  6694. // Release audio engine
  6695. Engine.audioEngine.dispose();
  6696. // Release effects
  6697. for (var name in this._compiledEffects) {
  6698. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6699. }
  6700. // Unbind
  6701. for (var i in this._vertexAttribArrays) {
  6702. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6703. continue;
  6704. }
  6705. this._gl.disableVertexAttribArray(i);
  6706. }
  6707. this._gl = null;
  6708. // Events
  6709. window.removeEventListener("blur", this._onBlur);
  6710. window.removeEventListener("focus", this._onFocus);
  6711. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6712. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6713. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6714. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6715. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6716. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6717. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6718. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6719. };
  6720. // Loading screen
  6721. Engine.prototype.displayLoadingUI = function () {
  6722. var _this = this;
  6723. this._loadingDiv = document.createElement("div");
  6724. this._loadingDiv.style.opacity = "0";
  6725. this._loadingDiv.style.transition = "opacity 1.5s ease";
  6726. // Loading text
  6727. this._loadingTextDiv = document.createElement("div");
  6728. this._loadingTextDiv.style.position = "absolute";
  6729. this._loadingTextDiv.style.left = "0";
  6730. this._loadingTextDiv.style.top = "50%";
  6731. this._loadingTextDiv.style.marginTop = "80px";
  6732. this._loadingTextDiv.style.width = "100%";
  6733. this._loadingTextDiv.style.height = "20px";
  6734. this._loadingTextDiv.style.fontFamily = "Arial";
  6735. this._loadingTextDiv.style.fontSize = "14px";
  6736. this._loadingTextDiv.style.color = "white";
  6737. this._loadingTextDiv.style.textAlign = "center";
  6738. this._loadingTextDiv.innerHTML = "Loading";
  6739. this._loadingDiv.appendChild(this._loadingTextDiv);
  6740. // Loading img
  6741. var imgBack = new Image();
  6742. 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==";
  6743. imgBack.style.position = "absolute";
  6744. imgBack.style.left = "50%";
  6745. imgBack.style.top = "50%";
  6746. imgBack.style.marginLeft = "-50px";
  6747. imgBack.style.marginTop = "-50px";
  6748. imgBack.style.transition = "transform 1.0s ease";
  6749. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  6750. var deg = 360;
  6751. var onTransitionEnd = function () {
  6752. deg += 360;
  6753. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  6754. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  6755. };
  6756. imgBack.addEventListener("transitionend", onTransitionEnd);
  6757. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  6758. this._loadingDiv.appendChild(imgBack);
  6759. // front image
  6760. var imgFront = new Image();
  6761. 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=";
  6762. imgFront.style.position = "absolute";
  6763. imgFront.style.left = "50%";
  6764. imgFront.style.top = "50%";
  6765. imgFront.style.marginLeft = "-50px";
  6766. imgFront.style.marginTop = "-50px";
  6767. this._loadingDiv.appendChild(imgFront);
  6768. // Resize
  6769. this._resizeLoadingUI = function () {
  6770. var canvasRect = _this.getRenderingCanvasClientRect();
  6771. _this._loadingDiv.style.position = "absolute";
  6772. _this._loadingDiv.style.left = canvasRect.left + "px";
  6773. _this._loadingDiv.style.top = canvasRect.top + "px";
  6774. _this._loadingDiv.style.width = canvasRect.width + "px";
  6775. _this._loadingDiv.style.height = canvasRect.height + "px";
  6776. };
  6777. this._resizeLoadingUI();
  6778. window.addEventListener("resize", this._resizeLoadingUI);
  6779. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6780. document.body.appendChild(this._loadingDiv);
  6781. setTimeout(function () {
  6782. _this._loadingDiv.style.opacity = "1";
  6783. imgBack.style.transform = "rotateZ(360deg)";
  6784. imgBack.style.webkitTransform = "rotateZ(360deg)";
  6785. }, 0);
  6786. };
  6787. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6788. set: function (text) {
  6789. if (!this._loadingDiv) {
  6790. return;
  6791. }
  6792. this._loadingTextDiv.innerHTML = text;
  6793. },
  6794. enumerable: true,
  6795. configurable: true
  6796. });
  6797. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6798. get: function () {
  6799. return this._loadingDivBackgroundColor;
  6800. },
  6801. set: function (color) {
  6802. this._loadingDivBackgroundColor = color;
  6803. if (!this._loadingDiv) {
  6804. return;
  6805. }
  6806. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6807. },
  6808. enumerable: true,
  6809. configurable: true
  6810. });
  6811. Engine.prototype.hideLoadingUI = function () {
  6812. var _this = this;
  6813. if (!this._loadingDiv) {
  6814. return;
  6815. }
  6816. var onTransitionEnd = function () {
  6817. if (!_this._loadingDiv) {
  6818. return;
  6819. }
  6820. document.body.removeChild(_this._loadingDiv);
  6821. window.removeEventListener("resize", _this._resizeLoadingUI);
  6822. _this._loadingDiv = null;
  6823. };
  6824. this._loadingDiv.style.opacity = "0";
  6825. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  6826. };
  6827. // FPS
  6828. Engine.prototype.getFps = function () {
  6829. return this.fps;
  6830. };
  6831. Engine.prototype.getDeltaTime = function () {
  6832. return this.deltaTime;
  6833. };
  6834. Engine.prototype._measureFps = function () {
  6835. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6836. var length = this.previousFramesDuration.length;
  6837. if (length >= 2) {
  6838. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6839. }
  6840. if (length >= this.fpsRange) {
  6841. if (length > this.fpsRange) {
  6842. this.previousFramesDuration.splice(0, 1);
  6843. length = this.previousFramesDuration.length;
  6844. }
  6845. var sum = 0;
  6846. for (var id = 0; id < length - 1; id++) {
  6847. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6848. }
  6849. this.fps = 1000.0 / (sum / (length - 1));
  6850. }
  6851. };
  6852. // Statics
  6853. Engine.isSupported = function () {
  6854. try {
  6855. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6856. if (navigator.isCocoonJS) {
  6857. return true;
  6858. }
  6859. var tempcanvas = document.createElement("canvas");
  6860. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6861. return gl != null && !!window.WebGLRenderingContext;
  6862. }
  6863. catch (e) {
  6864. return false;
  6865. }
  6866. };
  6867. // Const statics
  6868. Engine._ALPHA_DISABLE = 0;
  6869. Engine._ALPHA_ADD = 1;
  6870. Engine._ALPHA_COMBINE = 2;
  6871. Engine._DELAYLOADSTATE_NONE = 0;
  6872. Engine._DELAYLOADSTATE_LOADED = 1;
  6873. Engine._DELAYLOADSTATE_LOADING = 2;
  6874. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6875. Engine._TEXTUREFORMAT_ALPHA = 0;
  6876. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6877. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6878. Engine._TEXTUREFORMAT_RGB = 4;
  6879. Engine._TEXTUREFORMAT_RGBA = 4;
  6880. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6881. Engine._TEXTURETYPE_FLOAT = 1;
  6882. // Updatable statics so stick with vars here
  6883. Engine.Epsilon = 0.001;
  6884. Engine.CollisionsEpsilon = 0.001;
  6885. Engine.CodeRepository = "Babylon/";
  6886. Engine.ShadersRepository = "Babylon/Shaders/";
  6887. return Engine;
  6888. })();
  6889. BABYLON.Engine = Engine;
  6890. })(BABYLON || (BABYLON = {}));
  6891. //# sourceMappingURL=babylon.engine.js.map
  6892. var BABYLON;
  6893. (function (BABYLON) {
  6894. /**
  6895. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6896. */
  6897. var Node = (function () {
  6898. /**
  6899. * @constructor
  6900. * @param {string} name - the name and id to be given to this node
  6901. * @param {BABYLON.Scene} the scene this node will be added to
  6902. */
  6903. function Node(name, scene) {
  6904. this.state = "";
  6905. this.animations = new Array();
  6906. this._childrenFlag = -1;
  6907. this._isEnabled = true;
  6908. this._isReady = true;
  6909. this._currentRenderId = -1;
  6910. this._parentRenderId = -1;
  6911. this.name = name;
  6912. this.id = name;
  6913. this._scene = scene;
  6914. this._initCache();
  6915. }
  6916. Node.prototype.getScene = function () {
  6917. return this._scene;
  6918. };
  6919. Node.prototype.getEngine = function () {
  6920. return this._scene.getEngine();
  6921. };
  6922. // override it in derived class
  6923. Node.prototype.getWorldMatrix = function () {
  6924. return BABYLON.Matrix.Identity();
  6925. };
  6926. // override it in derived class if you add new variables to the cache
  6927. // and call the parent class method
  6928. Node.prototype._initCache = function () {
  6929. this._cache = {};
  6930. this._cache.parent = undefined;
  6931. };
  6932. Node.prototype.updateCache = function (force) {
  6933. if (!force && this.isSynchronized())
  6934. return;
  6935. this._cache.parent = this.parent;
  6936. this._updateCache();
  6937. };
  6938. // override it in derived class if you add new variables to the cache
  6939. // and call the parent class method if !ignoreParentClass
  6940. Node.prototype._updateCache = function (ignoreParentClass) {
  6941. };
  6942. // override it in derived class if you add new variables to the cache
  6943. Node.prototype._isSynchronized = function () {
  6944. return true;
  6945. };
  6946. Node.prototype._markSyncedWithParent = function () {
  6947. this._parentRenderId = this.parent._currentRenderId;
  6948. };
  6949. Node.prototype.isSynchronizedWithParent = function () {
  6950. if (!this.parent) {
  6951. return true;
  6952. }
  6953. if (this._parentRenderId !== this.parent._currentRenderId) {
  6954. return false;
  6955. }
  6956. return this.parent.isSynchronized();
  6957. };
  6958. Node.prototype.isSynchronized = function (updateCache) {
  6959. var check = this.hasNewParent();
  6960. check = check || !this.isSynchronizedWithParent();
  6961. check = check || !this._isSynchronized();
  6962. if (updateCache)
  6963. this.updateCache(true);
  6964. return !check;
  6965. };
  6966. Node.prototype.hasNewParent = function (update) {
  6967. if (this._cache.parent === this.parent)
  6968. return false;
  6969. if (update)
  6970. this._cache.parent = this.parent;
  6971. return true;
  6972. };
  6973. /**
  6974. * Is this node ready to be used/rendered
  6975. * @return {boolean} is it ready
  6976. */
  6977. Node.prototype.isReady = function () {
  6978. return this._isReady;
  6979. };
  6980. /**
  6981. * Is this node enabled.
  6982. * If the node has a parent and is enabled, the parent will be inspected as well.
  6983. * @return {boolean} whether this node (and its parent) is enabled.
  6984. * @see setEnabled
  6985. */
  6986. Node.prototype.isEnabled = function () {
  6987. if (!this._isEnabled) {
  6988. return false;
  6989. }
  6990. if (this.parent) {
  6991. return this.parent.isEnabled();
  6992. }
  6993. return true;
  6994. };
  6995. /**
  6996. * Set the enabled state of this node.
  6997. * @param {boolean} value - the new enabled state
  6998. * @see isEnabled
  6999. */
  7000. Node.prototype.setEnabled = function (value) {
  7001. this._isEnabled = value;
  7002. };
  7003. /**
  7004. * Is this node a descendant of the given node.
  7005. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7006. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7007. * @see parent
  7008. */
  7009. Node.prototype.isDescendantOf = function (ancestor) {
  7010. if (this.parent) {
  7011. if (this.parent === ancestor) {
  7012. return true;
  7013. }
  7014. return this.parent.isDescendantOf(ancestor);
  7015. }
  7016. return false;
  7017. };
  7018. Node.prototype._getDescendants = function (list, results) {
  7019. for (var index = 0; index < list.length; index++) {
  7020. var item = list[index];
  7021. if (item.isDescendantOf(this)) {
  7022. results.push(item);
  7023. }
  7024. }
  7025. };
  7026. /**
  7027. * Will return all nodes that have this node as parent.
  7028. * @return {BABYLON.Node[]} all children nodes of all types.
  7029. */
  7030. Node.prototype.getDescendants = function () {
  7031. var results = [];
  7032. this._getDescendants(this._scene.meshes, results);
  7033. this._getDescendants(this._scene.lights, results);
  7034. this._getDescendants(this._scene.cameras, results);
  7035. return results;
  7036. };
  7037. Node.prototype._setReady = function (state) {
  7038. if (state == this._isReady) {
  7039. return;
  7040. }
  7041. if (!state) {
  7042. this._isReady = false;
  7043. return;
  7044. }
  7045. this._isReady = true;
  7046. if (this.onReady) {
  7047. this.onReady(this);
  7048. }
  7049. };
  7050. return Node;
  7051. })();
  7052. BABYLON.Node = Node;
  7053. })(BABYLON || (BABYLON = {}));
  7054. //# sourceMappingURL=babylon.node.js.map
  7055. var BABYLON;
  7056. (function (BABYLON) {
  7057. var FilesInput = (function () {
  7058. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7059. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7060. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7061. this._engine = p_engine;
  7062. this._canvas = p_canvas;
  7063. this._currentScene = p_scene;
  7064. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7065. this._progressCallback = p_progressCallback;
  7066. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7067. this._textureLoadingCallback = p_textureLoadingCallback;
  7068. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7069. }
  7070. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7071. var _this = this;
  7072. if (p_elementToMonitor) {
  7073. this._elementToMonitor = p_elementToMonitor;
  7074. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7075. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7076. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7077. }
  7078. };
  7079. FilesInput.prototype.renderFunction = function () {
  7080. if (this._additionnalRenderLoopLogicCallback) {
  7081. this._additionnalRenderLoopLogicCallback();
  7082. }
  7083. if (this._currentScene) {
  7084. if (this._textureLoadingCallback) {
  7085. var remaining = this._currentScene.getWaitingItemsCount();
  7086. if (remaining > 0) {
  7087. this._textureLoadingCallback(remaining);
  7088. }
  7089. }
  7090. this._currentScene.render();
  7091. }
  7092. };
  7093. FilesInput.prototype.drag = function (e) {
  7094. e.stopPropagation();
  7095. e.preventDefault();
  7096. };
  7097. FilesInput.prototype.drop = function (eventDrop) {
  7098. eventDrop.stopPropagation();
  7099. eventDrop.preventDefault();
  7100. this.loadFiles(eventDrop);
  7101. };
  7102. FilesInput.prototype.loadFiles = function (event) {
  7103. if (this._startingProcessingFilesCallback)
  7104. this._startingProcessingFilesCallback();
  7105. // Handling data transfer via drag'n'drop
  7106. if (event && event.dataTransfer && event.dataTransfer.files) {
  7107. this._filesToLoad = event.dataTransfer.files;
  7108. }
  7109. // Handling files from input files
  7110. if (event && event.target && event.target.files) {
  7111. this._filesToLoad = event.target.files;
  7112. }
  7113. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7114. for (var i = 0; i < this._filesToLoad.length; i++) {
  7115. switch (this._filesToLoad[i].type) {
  7116. case "image/jpeg":
  7117. case "image/png":
  7118. case "image/bmp":
  7119. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7120. break;
  7121. case "image/targa":
  7122. case "image/vnd.ms-dds":
  7123. case "audio/wav":
  7124. case "audio/x-wav":
  7125. case "audio/mp3":
  7126. case "audio/mpeg":
  7127. case "audio/mpeg3":
  7128. case "audio/x-mpeg-3":
  7129. case "audio/ogg":
  7130. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7131. break;
  7132. default:
  7133. if (this._filesToLoad[i].name.indexOf(".babylon") !== -1 && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7134. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7135. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  7136. this._sceneFileToLoad = this._filesToLoad[i];
  7137. }
  7138. break;
  7139. }
  7140. }
  7141. this.reload();
  7142. }
  7143. };
  7144. FilesInput.prototype.reload = function () {
  7145. var _this = this;
  7146. var that = this;
  7147. // If a ".babylon" file has been provided
  7148. if (this._sceneFileToLoad) {
  7149. if (this._currentScene) {
  7150. this._engine.stopRenderLoop();
  7151. this._currentScene.dispose();
  7152. }
  7153. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7154. that._currentScene = newScene;
  7155. // Wait for textures and shaders to be ready
  7156. that._currentScene.executeWhenReady(function () {
  7157. // Attach camera to canvas inputs
  7158. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7159. that._currentScene.createDefaultCameraOrLight();
  7160. }
  7161. that._currentScene.activeCamera.attachControl(that._canvas);
  7162. if (that._sceneLoadedCallback) {
  7163. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7164. }
  7165. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7166. });
  7167. }, function (progress) {
  7168. if (_this._progressCallback) {
  7169. _this._progressCallback(progress);
  7170. }
  7171. });
  7172. }
  7173. else {
  7174. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7175. }
  7176. };
  7177. FilesInput.FilesTextures = new Array();
  7178. FilesInput.FilesToLoad = new Array();
  7179. return FilesInput;
  7180. })();
  7181. BABYLON.FilesInput = FilesInput;
  7182. })(BABYLON || (BABYLON = {}));
  7183. //# sourceMappingURL=babylon.filesInput.js.map
  7184. var BABYLON;
  7185. (function (BABYLON) {
  7186. var IntersectionInfo = (function () {
  7187. function IntersectionInfo(bu, bv, distance) {
  7188. this.bu = bu;
  7189. this.bv = bv;
  7190. this.distance = distance;
  7191. this.faceId = 0;
  7192. this.subMeshId = 0;
  7193. }
  7194. return IntersectionInfo;
  7195. })();
  7196. BABYLON.IntersectionInfo = IntersectionInfo;
  7197. var PickingInfo = (function () {
  7198. function PickingInfo() {
  7199. this.hit = false;
  7200. this.distance = 0;
  7201. this.pickedPoint = null;
  7202. this.pickedMesh = null;
  7203. this.bu = 0;
  7204. this.bv = 0;
  7205. this.faceId = -1;
  7206. this.subMeshId = 0;
  7207. }
  7208. // Methods
  7209. PickingInfo.prototype.getNormal = function (useWorldCoordinates) {
  7210. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7211. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7212. return null;
  7213. }
  7214. var indices = this.pickedMesh.getIndices();
  7215. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7216. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7217. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7218. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7219. normal0 = normal0.scale(this.bu);
  7220. normal1 = normal1.scale(this.bv);
  7221. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7222. var result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7223. if (useWorldCoordinates) {
  7224. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7225. }
  7226. return result;
  7227. };
  7228. PickingInfo.prototype.getTextureCoordinates = function () {
  7229. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7230. return null;
  7231. }
  7232. var indices = this.pickedMesh.getIndices();
  7233. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7234. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7235. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7236. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7237. uv0 = uv0.scale(this.bu);
  7238. uv1 = uv1.scale(this.bv);
  7239. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  7240. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7241. };
  7242. return PickingInfo;
  7243. })();
  7244. BABYLON.PickingInfo = PickingInfo;
  7245. })(BABYLON || (BABYLON = {}));
  7246. //# sourceMappingURL=babylon.pickingInfo.js.map
  7247. var BABYLON;
  7248. (function (BABYLON) {
  7249. var BoundingSphere = (function () {
  7250. function BoundingSphere(minimum, maximum) {
  7251. this.minimum = minimum;
  7252. this.maximum = maximum;
  7253. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7254. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7255. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7256. this.radius = distance * 0.5;
  7257. this.centerWorld = BABYLON.Vector3.Zero();
  7258. this._update(BABYLON.Matrix.Identity());
  7259. }
  7260. // Methods
  7261. BoundingSphere.prototype._update = function (world) {
  7262. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7263. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7264. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7265. };
  7266. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7267. for (var i = 0; i < 6; i++) {
  7268. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7269. return false;
  7270. }
  7271. return true;
  7272. };
  7273. BoundingSphere.prototype.intersectsPoint = function (point) {
  7274. var x = this.centerWorld.x - point.x;
  7275. var y = this.centerWorld.y - point.y;
  7276. var z = this.centerWorld.z - point.z;
  7277. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7278. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7279. return false;
  7280. return true;
  7281. };
  7282. // Statics
  7283. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7284. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7285. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7286. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7287. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7288. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7289. return false;
  7290. return true;
  7291. };
  7292. return BoundingSphere;
  7293. })();
  7294. BABYLON.BoundingSphere = BoundingSphere;
  7295. })(BABYLON || (BABYLON = {}));
  7296. //# sourceMappingURL=babylon.boundingSphere.js.map
  7297. var BABYLON;
  7298. (function (BABYLON) {
  7299. var BoundingBox = (function () {
  7300. function BoundingBox(minimum, maximum) {
  7301. this.minimum = minimum;
  7302. this.maximum = maximum;
  7303. this.vectors = new Array();
  7304. this.vectorsWorld = new Array();
  7305. // Bounding vectors
  7306. this.vectors.push(this.minimum.clone());
  7307. this.vectors.push(this.maximum.clone());
  7308. this.vectors.push(this.minimum.clone());
  7309. this.vectors[2].x = this.maximum.x;
  7310. this.vectors.push(this.minimum.clone());
  7311. this.vectors[3].y = this.maximum.y;
  7312. this.vectors.push(this.minimum.clone());
  7313. this.vectors[4].z = this.maximum.z;
  7314. this.vectors.push(this.maximum.clone());
  7315. this.vectors[5].z = this.minimum.z;
  7316. this.vectors.push(this.maximum.clone());
  7317. this.vectors[6].x = this.minimum.x;
  7318. this.vectors.push(this.maximum.clone());
  7319. this.vectors[7].y = this.minimum.y;
  7320. // OBB
  7321. this.center = this.maximum.add(this.minimum).scale(0.5);
  7322. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7323. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7324. // World
  7325. for (var index = 0; index < this.vectors.length; index++) {
  7326. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7327. }
  7328. this.minimumWorld = BABYLON.Vector3.Zero();
  7329. this.maximumWorld = BABYLON.Vector3.Zero();
  7330. this._update(BABYLON.Matrix.Identity());
  7331. }
  7332. // Methods
  7333. BoundingBox.prototype.getWorldMatrix = function () {
  7334. return this._worldMatrix;
  7335. };
  7336. BoundingBox.prototype._update = function (world) {
  7337. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7338. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7339. for (var index = 0; index < this.vectors.length; index++) {
  7340. var v = this.vectorsWorld[index];
  7341. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7342. if (v.x < this.minimumWorld.x)
  7343. this.minimumWorld.x = v.x;
  7344. if (v.y < this.minimumWorld.y)
  7345. this.minimumWorld.y = v.y;
  7346. if (v.z < this.minimumWorld.z)
  7347. this.minimumWorld.z = v.z;
  7348. if (v.x > this.maximumWorld.x)
  7349. this.maximumWorld.x = v.x;
  7350. if (v.y > this.maximumWorld.y)
  7351. this.maximumWorld.y = v.y;
  7352. if (v.z > this.maximumWorld.z)
  7353. this.maximumWorld.z = v.z;
  7354. }
  7355. // OBB
  7356. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7357. this.center.scaleInPlace(0.5);
  7358. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7359. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7360. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7361. this._worldMatrix = world;
  7362. };
  7363. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7364. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7365. };
  7366. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7367. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7368. };
  7369. BoundingBox.prototype.intersectsPoint = function (point) {
  7370. var delta = -BABYLON.Engine.Epsilon;
  7371. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7372. return false;
  7373. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7374. return false;
  7375. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7376. return false;
  7377. return true;
  7378. };
  7379. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7380. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7381. };
  7382. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7383. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7384. return false;
  7385. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7386. return false;
  7387. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7388. return false;
  7389. return true;
  7390. };
  7391. // Statics
  7392. BoundingBox.Intersects = function (box0, box1) {
  7393. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7394. return false;
  7395. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7396. return false;
  7397. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7398. return false;
  7399. return true;
  7400. };
  7401. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7402. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7403. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7404. return (num <= (sphereRadius * sphereRadius));
  7405. };
  7406. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7407. for (var p = 0; p < 6; p++) {
  7408. for (var i = 0; i < 8; i++) {
  7409. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7410. return false;
  7411. }
  7412. }
  7413. }
  7414. return true;
  7415. };
  7416. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7417. for (var p = 0; p < 6; p++) {
  7418. var inCount = 8;
  7419. for (var i = 0; i < 8; i++) {
  7420. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7421. --inCount;
  7422. }
  7423. else {
  7424. break;
  7425. }
  7426. }
  7427. if (inCount === 0)
  7428. return false;
  7429. }
  7430. return true;
  7431. };
  7432. return BoundingBox;
  7433. })();
  7434. BABYLON.BoundingBox = BoundingBox;
  7435. })(BABYLON || (BABYLON = {}));
  7436. //# sourceMappingURL=babylon.boundingBox.js.map
  7437. var BABYLON;
  7438. (function (BABYLON) {
  7439. var computeBoxExtents = function (axis, box) {
  7440. var p = BABYLON.Vector3.Dot(box.center, axis);
  7441. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7442. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7443. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7444. var r = r0 + r1 + r2;
  7445. return {
  7446. min: p - r,
  7447. max: p + r
  7448. };
  7449. };
  7450. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7451. var axisOverlap = function (axis, box0, box1) {
  7452. var result0 = computeBoxExtents(axis, box0);
  7453. var result1 = computeBoxExtents(axis, box1);
  7454. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7455. };
  7456. var BoundingInfo = (function () {
  7457. function BoundingInfo(minimum, maximum) {
  7458. this.minimum = minimum;
  7459. this.maximum = maximum;
  7460. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7461. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7462. }
  7463. // Methods
  7464. BoundingInfo.prototype._update = function (world) {
  7465. this.boundingBox._update(world);
  7466. this.boundingSphere._update(world);
  7467. };
  7468. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7469. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7470. return false;
  7471. return this.boundingBox.isInFrustum(frustumPlanes);
  7472. };
  7473. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7474. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7475. };
  7476. BoundingInfo.prototype._checkCollision = function (collider) {
  7477. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7478. };
  7479. BoundingInfo.prototype.intersectsPoint = function (point) {
  7480. if (!this.boundingSphere.centerWorld) {
  7481. return false;
  7482. }
  7483. if (!this.boundingSphere.intersectsPoint(point)) {
  7484. return false;
  7485. }
  7486. if (!this.boundingBox.intersectsPoint(point)) {
  7487. return false;
  7488. }
  7489. return true;
  7490. };
  7491. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7492. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7493. return false;
  7494. }
  7495. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7496. return false;
  7497. }
  7498. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7499. return false;
  7500. }
  7501. if (!precise) {
  7502. return true;
  7503. }
  7504. var box0 = this.boundingBox;
  7505. var box1 = boundingInfo.boundingBox;
  7506. if (!axisOverlap(box0.directions[0], box0, box1))
  7507. return false;
  7508. if (!axisOverlap(box0.directions[1], box0, box1))
  7509. return false;
  7510. if (!axisOverlap(box0.directions[2], box0, box1))
  7511. return false;
  7512. if (!axisOverlap(box1.directions[0], box0, box1))
  7513. return false;
  7514. if (!axisOverlap(box1.directions[1], box0, box1))
  7515. return false;
  7516. if (!axisOverlap(box1.directions[2], box0, box1))
  7517. return false;
  7518. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7519. return false;
  7520. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7521. return false;
  7522. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7523. return false;
  7524. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7525. return false;
  7526. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7527. return false;
  7528. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7529. return false;
  7530. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7531. return false;
  7532. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7533. return false;
  7534. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7535. return false;
  7536. return true;
  7537. };
  7538. return BoundingInfo;
  7539. })();
  7540. BABYLON.BoundingInfo = BoundingInfo;
  7541. })(BABYLON || (BABYLON = {}));
  7542. //# sourceMappingURL=babylon.boundingInfo.js.map
  7543. var BABYLON;
  7544. (function (BABYLON) {
  7545. var AbstractMesh = (function (_super) {
  7546. __extends(AbstractMesh, _super);
  7547. function AbstractMesh(name, scene) {
  7548. var _this = this;
  7549. _super.call(this, name, scene);
  7550. // Properties
  7551. this.definedFacingForward = true; // orientation for POV movement & rotation
  7552. this.position = new BABYLON.Vector3(0, 0, 0);
  7553. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7554. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7555. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7556. this.visibility = 1.0;
  7557. this.alphaIndex = Number.MAX_VALUE;
  7558. this.infiniteDistance = false;
  7559. this.isVisible = true;
  7560. this.isPickable = true;
  7561. this.showBoundingBox = false;
  7562. this.showSubMeshesBoundingBox = false;
  7563. this.onDispose = null;
  7564. this.isBlocker = false;
  7565. this.renderingGroupId = 0;
  7566. this.receiveShadows = false;
  7567. this.renderOutline = false;
  7568. this.outlineColor = BABYLON.Color3.Red();
  7569. this.outlineWidth = 0.02;
  7570. this.renderOverlay = false;
  7571. this.overlayColor = BABYLON.Color3.Red();
  7572. this.overlayAlpha = 0.5;
  7573. this.hasVertexAlpha = false;
  7574. this.useVertexColors = true;
  7575. this.applyFog = true;
  7576. this.useOctreeForRenderingSelection = true;
  7577. this.useOctreeForPicking = true;
  7578. this.useOctreeForCollisions = true;
  7579. this.layerMask = 0x0FFFFFFF;
  7580. this.alwaysSelectAsActiveMesh = false;
  7581. // Physics
  7582. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7583. // Collisions
  7584. this._checkCollisions = false;
  7585. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7586. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7587. this._collider = new BABYLON.Collider();
  7588. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7589. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7590. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7591. // Cache
  7592. this._localScaling = BABYLON.Matrix.Zero();
  7593. this._localRotation = BABYLON.Matrix.Zero();
  7594. this._localTranslation = BABYLON.Matrix.Zero();
  7595. this._localBillboard = BABYLON.Matrix.Zero();
  7596. this._localPivotScaling = BABYLON.Matrix.Zero();
  7597. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7598. this._localWorld = BABYLON.Matrix.Zero();
  7599. this._worldMatrix = BABYLON.Matrix.Zero();
  7600. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7601. this._absolutePosition = BABYLON.Vector3.Zero();
  7602. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7603. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7604. this._isDirty = false;
  7605. this._pivotMatrix = BABYLON.Matrix.Identity();
  7606. this._isDisposed = false;
  7607. this._renderId = 0;
  7608. this._intersectionsInProgress = new Array();
  7609. this._onAfterWorldMatrixUpdate = new Array();
  7610. this._isWorldMatrixFrozen = false;
  7611. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7612. if (collidedMesh === void 0) { collidedMesh = null; }
  7613. //TODO move this to the collision coordinator!
  7614. if (_this.getScene().workerCollisions)
  7615. newPosition.multiplyInPlace(_this._collider.radius);
  7616. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7617. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7618. _this.position.addInPlace(_this._diffPositionForCollisions);
  7619. }
  7620. };
  7621. scene.addMesh(this);
  7622. }
  7623. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7624. get: function () {
  7625. return AbstractMesh._BILLBOARDMODE_NONE;
  7626. },
  7627. enumerable: true,
  7628. configurable: true
  7629. });
  7630. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7631. get: function () {
  7632. return AbstractMesh._BILLBOARDMODE_X;
  7633. },
  7634. enumerable: true,
  7635. configurable: true
  7636. });
  7637. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7638. get: function () {
  7639. return AbstractMesh._BILLBOARDMODE_Y;
  7640. },
  7641. enumerable: true,
  7642. configurable: true
  7643. });
  7644. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7645. get: function () {
  7646. return AbstractMesh._BILLBOARDMODE_Z;
  7647. },
  7648. enumerable: true,
  7649. configurable: true
  7650. });
  7651. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7652. get: function () {
  7653. return AbstractMesh._BILLBOARDMODE_ALL;
  7654. },
  7655. enumerable: true,
  7656. configurable: true
  7657. });
  7658. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7659. // Methods
  7660. get: function () {
  7661. return false;
  7662. },
  7663. enumerable: true,
  7664. configurable: true
  7665. });
  7666. AbstractMesh.prototype.getLOD = function (camera) {
  7667. return this;
  7668. };
  7669. AbstractMesh.prototype.getTotalVertices = function () {
  7670. return 0;
  7671. };
  7672. AbstractMesh.prototype.getIndices = function () {
  7673. return null;
  7674. };
  7675. AbstractMesh.prototype.getVerticesData = function (kind) {
  7676. return null;
  7677. };
  7678. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7679. return false;
  7680. };
  7681. AbstractMesh.prototype.getBoundingInfo = function () {
  7682. if (this._masterMesh) {
  7683. return this._masterMesh.getBoundingInfo();
  7684. }
  7685. if (!this._boundingInfo) {
  7686. this._updateBoundingInfo();
  7687. }
  7688. return this._boundingInfo;
  7689. };
  7690. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7691. get: function () {
  7692. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7693. },
  7694. enumerable: true,
  7695. configurable: true
  7696. });
  7697. AbstractMesh.prototype._preActivate = function () {
  7698. };
  7699. AbstractMesh.prototype._activate = function (renderId) {
  7700. this._renderId = renderId;
  7701. };
  7702. AbstractMesh.prototype.getWorldMatrix = function () {
  7703. if (this._masterMesh) {
  7704. return this._masterMesh.getWorldMatrix();
  7705. }
  7706. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7707. this.computeWorldMatrix();
  7708. }
  7709. return this._worldMatrix;
  7710. };
  7711. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7712. get: function () {
  7713. return this._worldMatrix;
  7714. },
  7715. enumerable: true,
  7716. configurable: true
  7717. });
  7718. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7719. get: function () {
  7720. return this._absolutePosition;
  7721. },
  7722. enumerable: true,
  7723. configurable: true
  7724. });
  7725. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7726. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7727. this.computeWorldMatrix(true);
  7728. this._isWorldMatrixFrozen = true;
  7729. };
  7730. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7731. this._isWorldMatrixFrozen = false;
  7732. this.computeWorldMatrix(true);
  7733. };
  7734. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7735. get: function () {
  7736. return this._isWorldMatrixFrozen;
  7737. },
  7738. enumerable: true,
  7739. configurable: true
  7740. });
  7741. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7742. axis.normalize();
  7743. if (!this.rotationQuaternion) {
  7744. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7745. this.rotation = BABYLON.Vector3.Zero();
  7746. }
  7747. if (!space || space === BABYLON.Space.LOCAL) {
  7748. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7749. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7750. }
  7751. else {
  7752. if (this.parent) {
  7753. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7754. invertParentWorldMatrix.invert();
  7755. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7756. }
  7757. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7758. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7759. }
  7760. };
  7761. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7762. var displacementVector = axis.scale(distance);
  7763. if (!space || space === BABYLON.Space.LOCAL) {
  7764. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7765. this.setPositionWithLocalVector(tempV3);
  7766. }
  7767. else {
  7768. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7769. }
  7770. };
  7771. AbstractMesh.prototype.getAbsolutePosition = function () {
  7772. this.computeWorldMatrix();
  7773. return this._absolutePosition;
  7774. };
  7775. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7776. if (!absolutePosition) {
  7777. return;
  7778. }
  7779. var absolutePositionX;
  7780. var absolutePositionY;
  7781. var absolutePositionZ;
  7782. if (absolutePosition.x === undefined) {
  7783. if (arguments.length < 3) {
  7784. return;
  7785. }
  7786. absolutePositionX = arguments[0];
  7787. absolutePositionY = arguments[1];
  7788. absolutePositionZ = arguments[2];
  7789. }
  7790. else {
  7791. absolutePositionX = absolutePosition.x;
  7792. absolutePositionY = absolutePosition.y;
  7793. absolutePositionZ = absolutePosition.z;
  7794. }
  7795. if (this.parent) {
  7796. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7797. invertParentWorldMatrix.invert();
  7798. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7799. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7800. }
  7801. else {
  7802. this.position.x = absolutePositionX;
  7803. this.position.y = absolutePositionY;
  7804. this.position.z = absolutePositionZ;
  7805. }
  7806. };
  7807. // ================================== Point of View Movement =================================
  7808. /**
  7809. * Perform relative position change from the point of view of behind the front of the mesh.
  7810. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7811. * Supports definition of mesh facing forward or backward.
  7812. * @param {number} amountRight
  7813. * @param {number} amountUp
  7814. * @param {number} amountForward
  7815. */
  7816. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7817. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7818. };
  7819. /**
  7820. * Calculate relative position change from the point of view of behind the front of the mesh.
  7821. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7822. * Supports definition of mesh facing forward or backward.
  7823. * @param {number} amountRight
  7824. * @param {number} amountUp
  7825. * @param {number} amountForward
  7826. */
  7827. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7828. var rotMatrix = new BABYLON.Matrix();
  7829. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7830. rotQuaternion.toRotationMatrix(rotMatrix);
  7831. var translationDelta = BABYLON.Vector3.Zero();
  7832. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7833. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7834. return translationDelta;
  7835. };
  7836. // ================================== Point of View Rotation =================================
  7837. /**
  7838. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7839. * Supports definition of mesh facing forward or backward.
  7840. * @param {number} flipBack
  7841. * @param {number} twirlClockwise
  7842. * @param {number} tiltRight
  7843. */
  7844. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7845. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7846. };
  7847. /**
  7848. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7849. * Supports definition of mesh facing forward or backward.
  7850. * @param {number} flipBack
  7851. * @param {number} twirlClockwise
  7852. * @param {number} tiltRight
  7853. */
  7854. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7855. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7856. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7857. };
  7858. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7859. this._pivotMatrix = matrix;
  7860. this._cache.pivotMatrixUpdated = true;
  7861. };
  7862. AbstractMesh.prototype.getPivotMatrix = function () {
  7863. return this._pivotMatrix;
  7864. };
  7865. AbstractMesh.prototype._isSynchronized = function () {
  7866. if (this._isDirty) {
  7867. return false;
  7868. }
  7869. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7870. return false;
  7871. if (this._cache.pivotMatrixUpdated) {
  7872. return false;
  7873. }
  7874. if (this.infiniteDistance) {
  7875. return false;
  7876. }
  7877. if (!this._cache.position.equals(this.position))
  7878. return false;
  7879. if (this.rotationQuaternion) {
  7880. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7881. return false;
  7882. }
  7883. else {
  7884. if (!this._cache.rotation.equals(this.rotation))
  7885. return false;
  7886. }
  7887. if (!this._cache.scaling.equals(this.scaling))
  7888. return false;
  7889. return true;
  7890. };
  7891. AbstractMesh.prototype._initCache = function () {
  7892. _super.prototype._initCache.call(this);
  7893. this._cache.localMatrixUpdated = false;
  7894. this._cache.position = BABYLON.Vector3.Zero();
  7895. this._cache.scaling = BABYLON.Vector3.Zero();
  7896. this._cache.rotation = BABYLON.Vector3.Zero();
  7897. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7898. };
  7899. AbstractMesh.prototype.markAsDirty = function (property) {
  7900. if (property === "rotation") {
  7901. this.rotationQuaternion = null;
  7902. }
  7903. this._currentRenderId = Number.MAX_VALUE;
  7904. this._isDirty = true;
  7905. };
  7906. AbstractMesh.prototype._updateBoundingInfo = function () {
  7907. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7908. this._boundingInfo._update(this.worldMatrixFromCache);
  7909. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  7910. };
  7911. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  7912. if (!this.subMeshes) {
  7913. return;
  7914. }
  7915. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7916. var subMesh = this.subMeshes[subIndex];
  7917. subMesh.updateBoundingInfo(matrix);
  7918. }
  7919. };
  7920. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7921. if (this._isWorldMatrixFrozen) {
  7922. return this._worldMatrix;
  7923. }
  7924. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  7925. return this._worldMatrix;
  7926. }
  7927. this._cache.position.copyFrom(this.position);
  7928. this._cache.scaling.copyFrom(this.scaling);
  7929. this._cache.pivotMatrixUpdated = false;
  7930. this._currentRenderId = this.getScene().getRenderId();
  7931. this._isDirty = false;
  7932. // Scaling
  7933. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7934. // Rotation
  7935. if (this.rotationQuaternion) {
  7936. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7937. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7938. }
  7939. else {
  7940. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7941. this._cache.rotation.copyFrom(this.rotation);
  7942. }
  7943. // Translation
  7944. if (this.infiniteDistance && !this.parent) {
  7945. var camera = this.getScene().activeCamera;
  7946. var cameraWorldMatrix = camera.getWorldMatrix();
  7947. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7948. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7949. }
  7950. else {
  7951. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7952. }
  7953. // Composing transformations
  7954. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7955. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7956. // Billboarding
  7957. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7958. var localPosition = this.position.clone();
  7959. var zero = this.getScene().activeCamera.globalPosition.clone();
  7960. if (this.parent && this.parent.position) {
  7961. localPosition.addInPlace(this.parent.position);
  7962. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7963. }
  7964. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) != AbstractMesh.BILLBOARDMODE_ALL) {
  7965. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  7966. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7967. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  7968. zero.y = localPosition.y + 0.001;
  7969. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  7970. zero.z = localPosition.z + 0.001;
  7971. }
  7972. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7973. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7974. this._localBillboard.invert();
  7975. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7976. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7977. }
  7978. // Local world
  7979. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7980. // Parent
  7981. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  7982. this._markSyncedWithParent();
  7983. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7984. }
  7985. else {
  7986. this._worldMatrix.copyFrom(this._localWorld);
  7987. }
  7988. // Bounding info
  7989. this._updateBoundingInfo();
  7990. // Absolute position
  7991. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7992. // Callbacks
  7993. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  7994. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  7995. }
  7996. return this._worldMatrix;
  7997. };
  7998. /**
  7999. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8000. * @param func: callback function to add
  8001. */
  8002. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8003. this._onAfterWorldMatrixUpdate.push(func);
  8004. };
  8005. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8006. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8007. if (index > -1) {
  8008. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8009. }
  8010. };
  8011. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8012. this.computeWorldMatrix();
  8013. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8014. };
  8015. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8016. this.computeWorldMatrix();
  8017. var invLocalWorldMatrix = this._localWorld.clone();
  8018. invLocalWorldMatrix.invert();
  8019. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8020. };
  8021. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8022. this.computeWorldMatrix(true);
  8023. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8024. };
  8025. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8026. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8027. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8028. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8029. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8030. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8031. /// <returns>Mesh oriented towards targetMesh</returns>
  8032. yawCor = yawCor || 0; // default to zero if undefined
  8033. pitchCor = pitchCor || 0;
  8034. rollCor = rollCor || 0;
  8035. var dv = targetPoint.subtract(this.position);
  8036. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8037. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8038. var pitch = Math.atan2(dv.y, len);
  8039. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8040. };
  8041. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8042. return this._boundingInfo.isInFrustum(frustumPlanes);
  8043. };
  8044. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8045. if (!camera) {
  8046. camera = this.getScene().activeCamera;
  8047. }
  8048. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8049. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8050. return false;
  8051. }
  8052. return true;
  8053. };
  8054. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8055. if (!this._boundingInfo || !mesh._boundingInfo) {
  8056. return false;
  8057. }
  8058. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8059. };
  8060. AbstractMesh.prototype.intersectsPoint = function (point) {
  8061. if (!this._boundingInfo) {
  8062. return false;
  8063. }
  8064. return this._boundingInfo.intersectsPoint(point);
  8065. };
  8066. // Physics
  8067. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8068. var physicsEngine = this.getScene().getPhysicsEngine();
  8069. if (!physicsEngine) {
  8070. return;
  8071. }
  8072. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8073. if (impostor.impostor) {
  8074. // Old API
  8075. options = impostor;
  8076. impostor = impostor.impostor;
  8077. }
  8078. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8079. physicsEngine._unregisterMesh(this);
  8080. return;
  8081. }
  8082. if (!options) {
  8083. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8084. }
  8085. else {
  8086. if (!options.mass && options.mass !== 0)
  8087. options.mass = 0;
  8088. if (!options.friction && options.friction !== 0)
  8089. options.friction = 0.2;
  8090. if (!options.restitution && options.restitution !== 0)
  8091. options.restitution = 0.2;
  8092. }
  8093. this._physicImpostor = impostor;
  8094. this._physicsMass = options.mass;
  8095. this._physicsFriction = options.friction;
  8096. this._physicRestitution = options.restitution;
  8097. return physicsEngine._registerMesh(this, impostor, options);
  8098. };
  8099. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8100. if (!this._physicImpostor) {
  8101. return BABYLON.PhysicsEngine.NoImpostor;
  8102. }
  8103. return this._physicImpostor;
  8104. };
  8105. AbstractMesh.prototype.getPhysicsMass = function () {
  8106. if (!this._physicsMass) {
  8107. return 0;
  8108. }
  8109. return this._physicsMass;
  8110. };
  8111. AbstractMesh.prototype.getPhysicsFriction = function () {
  8112. if (!this._physicsFriction) {
  8113. return 0;
  8114. }
  8115. return this._physicsFriction;
  8116. };
  8117. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8118. if (!this._physicRestitution) {
  8119. return 0;
  8120. }
  8121. return this._physicRestitution;
  8122. };
  8123. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8124. if (!camera) {
  8125. camera = this.getScene().activeCamera;
  8126. }
  8127. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8128. };
  8129. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8130. if (!camera) {
  8131. camera = this.getScene().activeCamera;
  8132. }
  8133. return this.absolutePosition.subtract(camera.position).length();
  8134. };
  8135. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8136. if (!this._physicImpostor) {
  8137. return;
  8138. }
  8139. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8140. };
  8141. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8142. if (!this._physicImpostor) {
  8143. return;
  8144. }
  8145. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8146. };
  8147. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8148. if (!this._physicImpostor) {
  8149. return;
  8150. }
  8151. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8152. };
  8153. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8154. // Collisions
  8155. get: function () {
  8156. return this._checkCollisions;
  8157. },
  8158. set: function (collisionEnabled) {
  8159. this._checkCollisions = collisionEnabled;
  8160. if (this.getScene().workerCollisions) {
  8161. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8162. }
  8163. },
  8164. enumerable: true,
  8165. configurable: true
  8166. });
  8167. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8168. var globalPosition = this.getAbsolutePosition();
  8169. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8170. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8171. this._collider.radius = this.ellipsoid;
  8172. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8173. };
  8174. // Submeshes octree
  8175. /**
  8176. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8177. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8178. */
  8179. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8180. if (maxCapacity === void 0) { maxCapacity = 64; }
  8181. if (maxDepth === void 0) { maxDepth = 2; }
  8182. if (!this._submeshesOctree) {
  8183. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8184. }
  8185. this.computeWorldMatrix(true);
  8186. // Update octree
  8187. var bbox = this.getBoundingInfo().boundingBox;
  8188. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8189. return this._submeshesOctree;
  8190. };
  8191. // Collisions
  8192. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8193. this._generatePointsArray();
  8194. // Transformation
  8195. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8196. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8197. subMesh._lastColliderWorldVertices = [];
  8198. subMesh._trianglePlanes = [];
  8199. var start = subMesh.verticesStart;
  8200. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8201. for (var i = start; i < end; i++) {
  8202. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8203. }
  8204. }
  8205. // Collide
  8206. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8207. if (collider.collisionFound) {
  8208. collider.collidedMesh = this;
  8209. }
  8210. };
  8211. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8212. var subMeshes;
  8213. var len;
  8214. // Octrees
  8215. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8216. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8217. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8218. len = intersections.length;
  8219. subMeshes = intersections.data;
  8220. }
  8221. else {
  8222. subMeshes = this.subMeshes;
  8223. len = subMeshes.length;
  8224. }
  8225. for (var index = 0; index < len; index++) {
  8226. var subMesh = subMeshes[index];
  8227. // Bounding test
  8228. if (len > 1 && !subMesh._checkCollision(collider))
  8229. continue;
  8230. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8231. }
  8232. };
  8233. AbstractMesh.prototype._checkCollision = function (collider) {
  8234. // Bounding box test
  8235. if (!this._boundingInfo._checkCollision(collider))
  8236. return;
  8237. // Transformation matrix
  8238. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8239. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8240. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8241. };
  8242. // Picking
  8243. AbstractMesh.prototype._generatePointsArray = function () {
  8244. return false;
  8245. };
  8246. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8247. var pickingInfo = new BABYLON.PickingInfo();
  8248. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8249. return pickingInfo;
  8250. }
  8251. if (!this._generatePointsArray()) {
  8252. return pickingInfo;
  8253. }
  8254. var intersectInfo = null;
  8255. // Octrees
  8256. var subMeshes;
  8257. var len;
  8258. if (this._submeshesOctree && this.useOctreeForPicking) {
  8259. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8260. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8261. len = intersections.length;
  8262. subMeshes = intersections.data;
  8263. }
  8264. else {
  8265. subMeshes = this.subMeshes;
  8266. len = subMeshes.length;
  8267. }
  8268. for (var index = 0; index < len; index++) {
  8269. var subMesh = subMeshes[index];
  8270. // Bounding test
  8271. if (len > 1 && !subMesh.canIntersects(ray))
  8272. continue;
  8273. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8274. if (currentIntersectInfo) {
  8275. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8276. intersectInfo = currentIntersectInfo;
  8277. intersectInfo.subMeshId = index;
  8278. if (fastCheck) {
  8279. break;
  8280. }
  8281. }
  8282. }
  8283. }
  8284. if (intersectInfo) {
  8285. // Get picked point
  8286. var world = this.getWorldMatrix();
  8287. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8288. var direction = ray.direction.clone();
  8289. direction = direction.scale(intersectInfo.distance);
  8290. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8291. var pickedPoint = worldOrigin.add(worldDirection);
  8292. // Return result
  8293. pickingInfo.hit = true;
  8294. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8295. pickingInfo.pickedPoint = pickedPoint;
  8296. pickingInfo.pickedMesh = this;
  8297. pickingInfo.bu = intersectInfo.bu;
  8298. pickingInfo.bv = intersectInfo.bv;
  8299. pickingInfo.faceId = intersectInfo.faceId;
  8300. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8301. return pickingInfo;
  8302. }
  8303. return pickingInfo;
  8304. };
  8305. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8306. return null;
  8307. };
  8308. AbstractMesh.prototype.releaseSubMeshes = function () {
  8309. if (this.subMeshes) {
  8310. while (this.subMeshes.length) {
  8311. this.subMeshes[0].dispose();
  8312. }
  8313. }
  8314. else {
  8315. this.subMeshes = new Array();
  8316. }
  8317. };
  8318. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8319. var index;
  8320. // Physics
  8321. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8322. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8323. }
  8324. // Intersections in progress
  8325. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8326. var other = this._intersectionsInProgress[index];
  8327. var pos = other._intersectionsInProgress.indexOf(this);
  8328. other._intersectionsInProgress.splice(pos, 1);
  8329. }
  8330. this._intersectionsInProgress = [];
  8331. // SubMeshes
  8332. this.releaseSubMeshes();
  8333. // Remove from scene
  8334. this.getScene().removeMesh(this);
  8335. if (!doNotRecurse) {
  8336. // Particles
  8337. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8338. if (this.getScene().particleSystems[index].emitter === this) {
  8339. this.getScene().particleSystems[index].dispose();
  8340. index--;
  8341. }
  8342. }
  8343. // Children
  8344. var objects = this.getScene().meshes.slice(0);
  8345. for (index = 0; index < objects.length; index++) {
  8346. if (objects[index].parent === this) {
  8347. objects[index].dispose();
  8348. }
  8349. }
  8350. }
  8351. else {
  8352. for (index = 0; index < this.getScene().meshes.length; index++) {
  8353. var obj = this.getScene().meshes[index];
  8354. if (obj.parent === this) {
  8355. obj.parent = null;
  8356. obj.computeWorldMatrix(true);
  8357. }
  8358. }
  8359. }
  8360. this._onAfterWorldMatrixUpdate = [];
  8361. this._isDisposed = true;
  8362. // Callback
  8363. if (this.onDispose) {
  8364. this.onDispose();
  8365. }
  8366. };
  8367. // Statics
  8368. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8369. AbstractMesh._BILLBOARDMODE_X = 1;
  8370. AbstractMesh._BILLBOARDMODE_Y = 2;
  8371. AbstractMesh._BILLBOARDMODE_Z = 4;
  8372. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8373. return AbstractMesh;
  8374. })(BABYLON.Node);
  8375. BABYLON.AbstractMesh = AbstractMesh;
  8376. })(BABYLON || (BABYLON = {}));
  8377. //# sourceMappingURL=babylon.abstractMesh.js.map
  8378. var BABYLON;
  8379. (function (BABYLON) {
  8380. var Light = (function (_super) {
  8381. __extends(Light, _super);
  8382. function Light(name, scene) {
  8383. _super.call(this, name, scene);
  8384. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8385. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8386. this.intensity = 1.0;
  8387. this.range = Number.MAX_VALUE;
  8388. this.includeOnlyWithLayerMask = 0;
  8389. this.includedOnlyMeshes = new Array();
  8390. this.excludedMeshes = new Array();
  8391. this.excludeWithLayerMask = 0;
  8392. this._excludedMeshesIds = new Array();
  8393. this._includedOnlyMeshesIds = new Array();
  8394. scene.addLight(this);
  8395. }
  8396. Light.prototype.getShadowGenerator = function () {
  8397. return this._shadowGenerator;
  8398. };
  8399. Light.prototype.getAbsolutePosition = function () {
  8400. return BABYLON.Vector3.Zero();
  8401. };
  8402. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8403. };
  8404. Light.prototype._getWorldMatrix = function () {
  8405. return BABYLON.Matrix.Identity();
  8406. };
  8407. Light.prototype.canAffectMesh = function (mesh) {
  8408. if (!mesh) {
  8409. return true;
  8410. }
  8411. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8412. return false;
  8413. }
  8414. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8415. return false;
  8416. }
  8417. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8418. return false;
  8419. }
  8420. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8421. return false;
  8422. }
  8423. return true;
  8424. };
  8425. Light.prototype.getWorldMatrix = function () {
  8426. this._currentRenderId = this.getScene().getRenderId();
  8427. var worldMatrix = this._getWorldMatrix();
  8428. if (this.parent && this.parent.getWorldMatrix) {
  8429. if (!this._parentedWorldMatrix) {
  8430. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8431. }
  8432. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8433. this._markSyncedWithParent();
  8434. return this._parentedWorldMatrix;
  8435. }
  8436. return worldMatrix;
  8437. };
  8438. Light.prototype.dispose = function () {
  8439. if (this._shadowGenerator) {
  8440. this._shadowGenerator.dispose();
  8441. this._shadowGenerator = null;
  8442. }
  8443. // Remove from scene
  8444. this.getScene().removeLight(this);
  8445. };
  8446. return Light;
  8447. })(BABYLON.Node);
  8448. BABYLON.Light = Light;
  8449. })(BABYLON || (BABYLON = {}));
  8450. //# sourceMappingURL=babylon.light.js.map
  8451. var BABYLON;
  8452. (function (BABYLON) {
  8453. var PointLight = (function (_super) {
  8454. __extends(PointLight, _super);
  8455. function PointLight(name, position, scene) {
  8456. _super.call(this, name, scene);
  8457. this.position = position;
  8458. }
  8459. PointLight.prototype.getAbsolutePosition = function () {
  8460. return this._transformedPosition ? this._transformedPosition : this.position;
  8461. };
  8462. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8463. if (this.parent && this.parent.getWorldMatrix) {
  8464. if (!this._transformedPosition) {
  8465. this._transformedPosition = BABYLON.Vector3.Zero();
  8466. }
  8467. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  8468. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  8469. return;
  8470. }
  8471. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8472. };
  8473. PointLight.prototype.getShadowGenerator = function () {
  8474. return null;
  8475. };
  8476. PointLight.prototype._getWorldMatrix = function () {
  8477. if (!this._worldMatrix) {
  8478. this._worldMatrix = BABYLON.Matrix.Identity();
  8479. }
  8480. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8481. return this._worldMatrix;
  8482. };
  8483. return PointLight;
  8484. })(BABYLON.Light);
  8485. BABYLON.PointLight = PointLight;
  8486. })(BABYLON || (BABYLON = {}));
  8487. //# sourceMappingURL=babylon.pointLight.js.map
  8488. var BABYLON;
  8489. (function (BABYLON) {
  8490. var SpotLight = (function (_super) {
  8491. __extends(SpotLight, _super);
  8492. function SpotLight(name, position, direction, angle, exponent, scene) {
  8493. _super.call(this, name, scene);
  8494. this.position = position;
  8495. this.direction = direction;
  8496. this.angle = angle;
  8497. this.exponent = exponent;
  8498. }
  8499. SpotLight.prototype.getAbsolutePosition = function () {
  8500. return this.transformedPosition ? this.transformedPosition : this.position;
  8501. };
  8502. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8503. var activeCamera = this.getScene().activeCamera;
  8504. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8505. };
  8506. SpotLight.prototype.supportsVSM = function () {
  8507. return true;
  8508. };
  8509. SpotLight.prototype.needRefreshPerFrame = function () {
  8510. return false;
  8511. };
  8512. SpotLight.prototype.setDirectionToTarget = function (target) {
  8513. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8514. return this.direction;
  8515. };
  8516. SpotLight.prototype.computeTransformedPosition = function () {
  8517. if (this.parent && this.parent.getWorldMatrix) {
  8518. if (!this.transformedPosition) {
  8519. this.transformedPosition = BABYLON.Vector3.Zero();
  8520. }
  8521. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8522. return true;
  8523. }
  8524. return false;
  8525. };
  8526. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8527. var normalizeDirection;
  8528. if (this.parent && this.parent.getWorldMatrix) {
  8529. if (!this._transformedDirection) {
  8530. this._transformedDirection = BABYLON.Vector3.Zero();
  8531. }
  8532. this.computeTransformedPosition();
  8533. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8534. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8535. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8536. }
  8537. else {
  8538. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8539. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8540. }
  8541. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8542. };
  8543. SpotLight.prototype._getWorldMatrix = function () {
  8544. if (!this._worldMatrix) {
  8545. this._worldMatrix = BABYLON.Matrix.Identity();
  8546. }
  8547. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8548. return this._worldMatrix;
  8549. };
  8550. return SpotLight;
  8551. })(BABYLON.Light);
  8552. BABYLON.SpotLight = SpotLight;
  8553. })(BABYLON || (BABYLON = {}));
  8554. //# sourceMappingURL=babylon.spotLight.js.map
  8555. var BABYLON;
  8556. (function (BABYLON) {
  8557. var HemisphericLight = (function (_super) {
  8558. __extends(HemisphericLight, _super);
  8559. function HemisphericLight(name, direction, scene) {
  8560. _super.call(this, name, scene);
  8561. this.direction = direction;
  8562. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8563. }
  8564. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8565. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8566. return this.direction;
  8567. };
  8568. HemisphericLight.prototype.getShadowGenerator = function () {
  8569. return null;
  8570. };
  8571. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8572. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8573. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8574. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8575. };
  8576. HemisphericLight.prototype._getWorldMatrix = function () {
  8577. if (!this._worldMatrix) {
  8578. this._worldMatrix = BABYLON.Matrix.Identity();
  8579. }
  8580. return this._worldMatrix;
  8581. };
  8582. return HemisphericLight;
  8583. })(BABYLON.Light);
  8584. BABYLON.HemisphericLight = HemisphericLight;
  8585. })(BABYLON || (BABYLON = {}));
  8586. //# sourceMappingURL=babylon.hemisphericLight.js.map
  8587. var BABYLON;
  8588. (function (BABYLON) {
  8589. var DirectionalLight = (function (_super) {
  8590. __extends(DirectionalLight, _super);
  8591. function DirectionalLight(name, direction, scene) {
  8592. _super.call(this, name, scene);
  8593. this.direction = direction;
  8594. this.shadowOrthoScale = 0.5;
  8595. this.position = direction.scale(-1);
  8596. }
  8597. DirectionalLight.prototype.getAbsolutePosition = function () {
  8598. return this.transformedPosition ? this.transformedPosition : this.position;
  8599. };
  8600. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8601. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8602. return this.direction;
  8603. };
  8604. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8605. var orthoLeft = Number.MAX_VALUE;
  8606. var orthoRight = Number.MIN_VALUE;
  8607. var orthoTop = Number.MIN_VALUE;
  8608. var orthoBottom = Number.MAX_VALUE;
  8609. var tempVector3 = BABYLON.Vector3.Zero();
  8610. var activeCamera = this.getScene().activeCamera;
  8611. // Check extends
  8612. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8613. var mesh = renderList[meshIndex];
  8614. if (!mesh) {
  8615. continue;
  8616. }
  8617. var boundingInfo = mesh.getBoundingInfo();
  8618. if (!boundingInfo) {
  8619. continue;
  8620. }
  8621. var boundingBox = boundingInfo.boundingBox;
  8622. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8623. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8624. if (tempVector3.x < orthoLeft)
  8625. orthoLeft = tempVector3.x;
  8626. if (tempVector3.y < orthoBottom)
  8627. orthoBottom = tempVector3.y;
  8628. if (tempVector3.x > orthoRight)
  8629. orthoRight = tempVector3.x;
  8630. if (tempVector3.y > orthoTop)
  8631. orthoTop = tempVector3.y;
  8632. }
  8633. }
  8634. var xOffset = orthoRight - orthoLeft;
  8635. var yOffset = orthoTop - orthoBottom;
  8636. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  8637. };
  8638. DirectionalLight.prototype.supportsVSM = function () {
  8639. return true;
  8640. };
  8641. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8642. return true;
  8643. };
  8644. DirectionalLight.prototype.computeTransformedPosition = function () {
  8645. if (this.parent && this.parent.getWorldMatrix) {
  8646. if (!this.transformedPosition) {
  8647. this.transformedPosition = BABYLON.Vector3.Zero();
  8648. }
  8649. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8650. return true;
  8651. }
  8652. return false;
  8653. };
  8654. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8655. if (this.parent && this.parent.getWorldMatrix) {
  8656. if (!this._transformedDirection) {
  8657. this._transformedDirection = BABYLON.Vector3.Zero();
  8658. }
  8659. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8660. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8661. return;
  8662. }
  8663. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8664. };
  8665. DirectionalLight.prototype._getWorldMatrix = function () {
  8666. if (!this._worldMatrix) {
  8667. this._worldMatrix = BABYLON.Matrix.Identity();
  8668. }
  8669. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8670. return this._worldMatrix;
  8671. };
  8672. return DirectionalLight;
  8673. })(BABYLON.Light);
  8674. BABYLON.DirectionalLight = DirectionalLight;
  8675. })(BABYLON || (BABYLON = {}));
  8676. //# sourceMappingURL=babylon.directionalLight.js.map
  8677. var BABYLON;
  8678. (function (BABYLON) {
  8679. var ShadowGenerator = (function () {
  8680. function ShadowGenerator(mapSize, light) {
  8681. var _this = this;
  8682. // Members
  8683. this._filter = ShadowGenerator.FILTER_NONE;
  8684. this.blurScale = 2;
  8685. this._blurBoxOffset = 0;
  8686. this._bias = 0.00005;
  8687. this._darkness = 0;
  8688. this._transparencyShadow = false;
  8689. this._viewMatrix = BABYLON.Matrix.Zero();
  8690. this._projectionMatrix = BABYLON.Matrix.Zero();
  8691. this._transformMatrix = BABYLON.Matrix.Zero();
  8692. this._worldViewProjection = BABYLON.Matrix.Zero();
  8693. this._light = light;
  8694. this._scene = light.getScene();
  8695. this._mapSize = mapSize;
  8696. light._shadowGenerator = this;
  8697. // Render target
  8698. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  8699. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8700. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8701. this._shadowMap.anisotropicFilteringLevel = 1;
  8702. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8703. this._shadowMap.renderParticles = false;
  8704. this._shadowMap.onAfterUnbind = function () {
  8705. if (!_this.useBlurVarianceShadowMap) {
  8706. return;
  8707. }
  8708. if (!_this._shadowMap2) {
  8709. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8710. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8711. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8712. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8713. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8714. _this._downSamplePostprocess.onApply = function (effect) {
  8715. effect.setTexture("textureSampler", _this._shadowMap);
  8716. };
  8717. _this.blurBoxOffset = 1;
  8718. }
  8719. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8720. };
  8721. // Custom render function
  8722. var renderSubMesh = function (subMesh) {
  8723. var mesh = subMesh.getRenderingMesh();
  8724. var scene = _this._scene;
  8725. var engine = scene.getEngine();
  8726. // Culling
  8727. engine.setState(subMesh.getMaterial().backFaceCulling);
  8728. // Managing instances
  8729. var batch = mesh._getInstancesRenderList(subMesh._id);
  8730. if (batch.mustReturn) {
  8731. return;
  8732. }
  8733. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8734. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8735. engine.enableEffect(_this._effect);
  8736. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8737. var material = subMesh.getMaterial();
  8738. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8739. // Alpha test
  8740. if (material && material.needAlphaTesting()) {
  8741. var alphaTexture = material.getAlphaTestTexture();
  8742. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8743. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8744. }
  8745. // Bones
  8746. if (mesh.useBones) {
  8747. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8748. }
  8749. // Draw
  8750. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8751. }
  8752. else {
  8753. // Need to reset refresh rate of the shadowMap
  8754. _this._shadowMap.resetRefreshCounter();
  8755. }
  8756. };
  8757. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8758. var index;
  8759. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8760. renderSubMesh(opaqueSubMeshes.data[index]);
  8761. }
  8762. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8763. renderSubMesh(alphaTestSubMeshes.data[index]);
  8764. }
  8765. if (_this._transparencyShadow) {
  8766. for (index = 0; index < transparentSubMeshes.length; index++) {
  8767. renderSubMesh(transparentSubMeshes.data[index]);
  8768. }
  8769. }
  8770. };
  8771. this._shadowMap.onClear = function (engine) {
  8772. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8773. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8774. }
  8775. else {
  8776. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8777. }
  8778. };
  8779. }
  8780. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8781. // Static
  8782. get: function () {
  8783. return ShadowGenerator._FILTER_NONE;
  8784. },
  8785. enumerable: true,
  8786. configurable: true
  8787. });
  8788. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  8789. get: function () {
  8790. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  8791. },
  8792. enumerable: true,
  8793. configurable: true
  8794. });
  8795. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  8796. get: function () {
  8797. return ShadowGenerator._FILTER_POISSONSAMPLING;
  8798. },
  8799. enumerable: true,
  8800. configurable: true
  8801. });
  8802. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  8803. get: function () {
  8804. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  8805. },
  8806. enumerable: true,
  8807. configurable: true
  8808. });
  8809. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  8810. get: function () {
  8811. return this._bias;
  8812. },
  8813. set: function (bias) {
  8814. this._bias = bias;
  8815. },
  8816. enumerable: true,
  8817. configurable: true
  8818. });
  8819. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  8820. get: function () {
  8821. return this._blurBoxOffset;
  8822. },
  8823. set: function (value) {
  8824. var _this = this;
  8825. if (this._blurBoxOffset === value) {
  8826. return;
  8827. }
  8828. this._blurBoxOffset = value;
  8829. if (this._boxBlurPostprocess) {
  8830. this._boxBlurPostprocess.dispose();
  8831. }
  8832. 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);
  8833. this._boxBlurPostprocess.onApply = function (effect) {
  8834. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  8835. };
  8836. },
  8837. enumerable: true,
  8838. configurable: true
  8839. });
  8840. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  8841. get: function () {
  8842. return this._filter;
  8843. },
  8844. set: function (value) {
  8845. if (this._filter === value) {
  8846. return;
  8847. }
  8848. this._filter = value;
  8849. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8850. this._shadowMap.anisotropicFilteringLevel = 16;
  8851. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  8852. }
  8853. else {
  8854. this._shadowMap.anisotropicFilteringLevel = 1;
  8855. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8856. }
  8857. },
  8858. enumerable: true,
  8859. configurable: true
  8860. });
  8861. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  8862. get: function () {
  8863. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  8864. },
  8865. set: function (value) {
  8866. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8867. },
  8868. enumerable: true,
  8869. configurable: true
  8870. });
  8871. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  8872. get: function () {
  8873. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  8874. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  8875. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  8876. },
  8877. set: function (value) {
  8878. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  8879. },
  8880. enumerable: true,
  8881. configurable: true
  8882. });
  8883. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  8884. get: function () {
  8885. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  8886. },
  8887. set: function (value) {
  8888. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8889. },
  8890. enumerable: true,
  8891. configurable: true
  8892. });
  8893. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  8894. var defines = [];
  8895. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8896. defines.push("#define VSM");
  8897. }
  8898. var attribs = [BABYLON.VertexBuffer.PositionKind];
  8899. var mesh = subMesh.getMesh();
  8900. var material = subMesh.getMaterial();
  8901. // Alpha test
  8902. if (material && material.needAlphaTesting()) {
  8903. defines.push("#define ALPHATEST");
  8904. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8905. attribs.push(BABYLON.VertexBuffer.UVKind);
  8906. defines.push("#define UV1");
  8907. }
  8908. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  8909. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  8910. defines.push("#define UV2");
  8911. }
  8912. }
  8913. // Bones
  8914. if (mesh.useBones) {
  8915. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  8916. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  8917. defines.push("#define BONES");
  8918. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  8919. }
  8920. // Instances
  8921. if (useInstances) {
  8922. defines.push("#define INSTANCES");
  8923. attribs.push("world0");
  8924. attribs.push("world1");
  8925. attribs.push("world2");
  8926. attribs.push("world3");
  8927. }
  8928. // Get correct effect
  8929. var join = defines.join("\n");
  8930. if (this._cachedDefines !== join) {
  8931. this._cachedDefines = join;
  8932. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  8933. }
  8934. return this._effect.isReady();
  8935. };
  8936. ShadowGenerator.prototype.getShadowMap = function () {
  8937. return this._shadowMap;
  8938. };
  8939. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  8940. if (this._shadowMap2) {
  8941. return this._shadowMap2;
  8942. }
  8943. return this._shadowMap;
  8944. };
  8945. ShadowGenerator.prototype.getLight = function () {
  8946. return this._light;
  8947. };
  8948. // Methods
  8949. ShadowGenerator.prototype.getTransformMatrix = function () {
  8950. var scene = this._scene;
  8951. if (this._currentRenderID === scene.getRenderId()) {
  8952. return this._transformMatrix;
  8953. }
  8954. this._currentRenderID = scene.getRenderId();
  8955. var lightPosition = this._light.position;
  8956. var lightDirection = this._light.direction;
  8957. if (this._light.computeTransformedPosition()) {
  8958. lightPosition = this._light.transformedPosition;
  8959. }
  8960. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  8961. this._cachedPosition = lightPosition.clone();
  8962. this._cachedDirection = lightDirection.clone();
  8963. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  8964. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  8965. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8966. }
  8967. return this._transformMatrix;
  8968. };
  8969. ShadowGenerator.prototype.getDarkness = function () {
  8970. return this._darkness;
  8971. };
  8972. ShadowGenerator.prototype.setDarkness = function (darkness) {
  8973. if (darkness >= 1.0)
  8974. this._darkness = 1.0;
  8975. else if (darkness <= 0.0)
  8976. this._darkness = 0.0;
  8977. else
  8978. this._darkness = darkness;
  8979. };
  8980. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  8981. this._transparencyShadow = hasShadow;
  8982. };
  8983. ShadowGenerator.prototype._packHalf = function (depth) {
  8984. var scale = depth * 255.0;
  8985. var fract = scale - Math.floor(scale);
  8986. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  8987. };
  8988. ShadowGenerator.prototype.dispose = function () {
  8989. this._shadowMap.dispose();
  8990. if (this._shadowMap2) {
  8991. this._shadowMap2.dispose();
  8992. }
  8993. if (this._downSamplePostprocess) {
  8994. this._downSamplePostprocess.dispose();
  8995. }
  8996. if (this._boxBlurPostprocess) {
  8997. this._boxBlurPostprocess.dispose();
  8998. }
  8999. };
  9000. ShadowGenerator._FILTER_NONE = 0;
  9001. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  9002. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9003. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9004. return ShadowGenerator;
  9005. })();
  9006. BABYLON.ShadowGenerator = ShadowGenerator;
  9007. })(BABYLON || (BABYLON = {}));
  9008. //# sourceMappingURL=babylon.shadowGenerator.js.map
  9009. var BABYLON;
  9010. (function (BABYLON) {
  9011. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9012. if (boxMin.x > sphereCenter.x + sphereRadius)
  9013. return false;
  9014. if (sphereCenter.x - sphereRadius > boxMax.x)
  9015. return false;
  9016. if (boxMin.y > sphereCenter.y + sphereRadius)
  9017. return false;
  9018. if (sphereCenter.y - sphereRadius > boxMax.y)
  9019. return false;
  9020. if (boxMin.z > sphereCenter.z + sphereRadius)
  9021. return false;
  9022. if (sphereCenter.z - sphereRadius > boxMax.z)
  9023. return false;
  9024. return true;
  9025. };
  9026. var getLowestRoot = function (a, b, c, maxR) {
  9027. var determinant = b * b - 4.0 * a * c;
  9028. var result = { root: 0, found: false };
  9029. if (determinant < 0)
  9030. return result;
  9031. var sqrtD = Math.sqrt(determinant);
  9032. var r1 = (-b - sqrtD) / (2.0 * a);
  9033. var r2 = (-b + sqrtD) / (2.0 * a);
  9034. if (r1 > r2) {
  9035. var temp = r2;
  9036. r2 = r1;
  9037. r1 = temp;
  9038. }
  9039. if (r1 > 0 && r1 < maxR) {
  9040. result.root = r1;
  9041. result.found = true;
  9042. return result;
  9043. }
  9044. if (r2 > 0 && r2 < maxR) {
  9045. result.root = r2;
  9046. result.found = true;
  9047. return result;
  9048. }
  9049. return result;
  9050. };
  9051. var Collider = (function () {
  9052. function Collider() {
  9053. this.radius = new BABYLON.Vector3(1, 1, 1);
  9054. this.retry = 0;
  9055. this.basePointWorld = BABYLON.Vector3.Zero();
  9056. this.velocityWorld = BABYLON.Vector3.Zero();
  9057. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9058. this._collisionPoint = BABYLON.Vector3.Zero();
  9059. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9060. this._tempVector = BABYLON.Vector3.Zero();
  9061. this._tempVector2 = BABYLON.Vector3.Zero();
  9062. this._tempVector3 = BABYLON.Vector3.Zero();
  9063. this._tempVector4 = BABYLON.Vector3.Zero();
  9064. this._edge = BABYLON.Vector3.Zero();
  9065. this._baseToVertex = BABYLON.Vector3.Zero();
  9066. this._destinationPoint = BABYLON.Vector3.Zero();
  9067. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9068. this._displacementVector = BABYLON.Vector3.Zero();
  9069. }
  9070. // Methods
  9071. Collider.prototype._initialize = function (source, dir, e) {
  9072. this.velocity = dir;
  9073. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9074. this.basePoint = source;
  9075. source.multiplyToRef(this.radius, this.basePointWorld);
  9076. dir.multiplyToRef(this.radius, this.velocityWorld);
  9077. this.velocityWorldLength = this.velocityWorld.length();
  9078. this.epsilon = e;
  9079. this.collisionFound = false;
  9080. };
  9081. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9082. pa.subtractToRef(point, this._tempVector);
  9083. pb.subtractToRef(point, this._tempVector2);
  9084. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9085. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9086. if (d < 0)
  9087. return false;
  9088. pc.subtractToRef(point, this._tempVector3);
  9089. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9090. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9091. if (d < 0)
  9092. return false;
  9093. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9094. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9095. return d >= 0;
  9096. };
  9097. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9098. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9099. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9100. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9101. return false;
  9102. }
  9103. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9104. return false;
  9105. return true;
  9106. };
  9107. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9108. var t0;
  9109. var embeddedInPlane = false;
  9110. //defensive programming, actually not needed.
  9111. if (!trianglePlaneArray) {
  9112. trianglePlaneArray = [];
  9113. }
  9114. if (!trianglePlaneArray[faceIndex]) {
  9115. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9116. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9117. }
  9118. var trianglePlane = trianglePlaneArray[faceIndex];
  9119. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9120. return;
  9121. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9122. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9123. if (normalDotVelocity == 0) {
  9124. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9125. return;
  9126. embeddedInPlane = true;
  9127. t0 = 0;
  9128. }
  9129. else {
  9130. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9131. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9132. if (t0 > t1) {
  9133. var temp = t1;
  9134. t1 = t0;
  9135. t0 = temp;
  9136. }
  9137. if (t0 > 1.0 || t1 < 0.0)
  9138. return;
  9139. if (t0 < 0)
  9140. t0 = 0;
  9141. if (t0 > 1.0)
  9142. t0 = 1.0;
  9143. }
  9144. this._collisionPoint.copyFromFloats(0, 0, 0);
  9145. var found = false;
  9146. var t = 1.0;
  9147. if (!embeddedInPlane) {
  9148. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9149. this.velocity.scaleToRef(t0, this._tempVector);
  9150. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9151. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9152. found = true;
  9153. t = t0;
  9154. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9155. }
  9156. }
  9157. if (!found) {
  9158. var velocitySquaredLength = this.velocity.lengthSquared();
  9159. var a = velocitySquaredLength;
  9160. this.basePoint.subtractToRef(p1, this._tempVector);
  9161. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9162. var c = this._tempVector.lengthSquared() - 1.0;
  9163. var lowestRoot = getLowestRoot(a, b, c, t);
  9164. if (lowestRoot.found) {
  9165. t = lowestRoot.root;
  9166. found = true;
  9167. this._collisionPoint.copyFrom(p1);
  9168. }
  9169. this.basePoint.subtractToRef(p2, this._tempVector);
  9170. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9171. c = this._tempVector.lengthSquared() - 1.0;
  9172. lowestRoot = getLowestRoot(a, b, c, t);
  9173. if (lowestRoot.found) {
  9174. t = lowestRoot.root;
  9175. found = true;
  9176. this._collisionPoint.copyFrom(p2);
  9177. }
  9178. this.basePoint.subtractToRef(p3, this._tempVector);
  9179. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9180. c = this._tempVector.lengthSquared() - 1.0;
  9181. lowestRoot = getLowestRoot(a, b, c, t);
  9182. if (lowestRoot.found) {
  9183. t = lowestRoot.root;
  9184. found = true;
  9185. this._collisionPoint.copyFrom(p3);
  9186. }
  9187. p2.subtractToRef(p1, this._edge);
  9188. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9189. var edgeSquaredLength = this._edge.lengthSquared();
  9190. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9191. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9192. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9193. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9194. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9195. lowestRoot = getLowestRoot(a, b, c, t);
  9196. if (lowestRoot.found) {
  9197. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9198. if (f >= 0.0 && f <= 1.0) {
  9199. t = lowestRoot.root;
  9200. found = true;
  9201. this._edge.scaleInPlace(f);
  9202. p1.addToRef(this._edge, this._collisionPoint);
  9203. }
  9204. }
  9205. p3.subtractToRef(p2, this._edge);
  9206. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9207. edgeSquaredLength = this._edge.lengthSquared();
  9208. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9209. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9210. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9211. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9212. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9213. lowestRoot = getLowestRoot(a, b, c, t);
  9214. if (lowestRoot.found) {
  9215. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9216. if (f >= 0.0 && f <= 1.0) {
  9217. t = lowestRoot.root;
  9218. found = true;
  9219. this._edge.scaleInPlace(f);
  9220. p2.addToRef(this._edge, this._collisionPoint);
  9221. }
  9222. }
  9223. p1.subtractToRef(p3, this._edge);
  9224. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9225. edgeSquaredLength = this._edge.lengthSquared();
  9226. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9227. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9228. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9229. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9230. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9231. lowestRoot = getLowestRoot(a, b, c, t);
  9232. if (lowestRoot.found) {
  9233. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9234. if (f >= 0.0 && f <= 1.0) {
  9235. t = lowestRoot.root;
  9236. found = true;
  9237. this._edge.scaleInPlace(f);
  9238. p3.addToRef(this._edge, this._collisionPoint);
  9239. }
  9240. }
  9241. }
  9242. if (found) {
  9243. var distToCollision = t * this.velocity.length();
  9244. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9245. if (!this.intersectionPoint) {
  9246. this.intersectionPoint = this._collisionPoint.clone();
  9247. }
  9248. else {
  9249. this.intersectionPoint.copyFrom(this._collisionPoint);
  9250. }
  9251. this.nearestDistance = distToCollision;
  9252. this.collisionFound = true;
  9253. }
  9254. }
  9255. };
  9256. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9257. for (var i = indexStart; i < indexEnd; i += 3) {
  9258. var p1 = pts[indices[i] - decal];
  9259. var p2 = pts[indices[i + 1] - decal];
  9260. var p3 = pts[indices[i + 2] - decal];
  9261. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9262. }
  9263. };
  9264. Collider.prototype._getResponse = function (pos, vel) {
  9265. pos.addToRef(vel, this._destinationPoint);
  9266. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9267. this.basePoint.addToRef(vel, pos);
  9268. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9269. this._slidePlaneNormal.normalize();
  9270. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9271. pos.addInPlace(this._displacementVector);
  9272. this.intersectionPoint.addInPlace(this._displacementVector);
  9273. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9274. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9275. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9276. };
  9277. return Collider;
  9278. })();
  9279. BABYLON.Collider = Collider;
  9280. })(BABYLON || (BABYLON = {}));
  9281. //# sourceMappingURL=babylon.collider.js.map
  9282. var BABYLON;
  9283. (function (BABYLON) {
  9284. //WebWorker code will be inserted to this variable.
  9285. BABYLON.CollisionWorker = "";
  9286. (function (WorkerTaskType) {
  9287. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9288. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9289. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9290. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9291. var WorkerTaskType = BABYLON.WorkerTaskType;
  9292. (function (WorkerReplyType) {
  9293. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9294. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9295. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9296. var WorkerReplyType = BABYLON.WorkerReplyType;
  9297. var CollisionCoordinatorWorker = (function () {
  9298. function CollisionCoordinatorWorker() {
  9299. var _this = this;
  9300. this._scaledPosition = BABYLON.Vector3.Zero();
  9301. this._scaledVelocity = BABYLON.Vector3.Zero();
  9302. this.onMeshUpdated = function (mesh) {
  9303. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9304. };
  9305. this.onGeometryUpdated = function (geometry) {
  9306. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9307. };
  9308. this._afterRender = function () {
  9309. if (!_this._init)
  9310. return;
  9311. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9312. return;
  9313. }
  9314. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9315. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9316. if (_this._runningUpdated > 4) {
  9317. return;
  9318. }
  9319. ++_this._runningUpdated;
  9320. var payload = {
  9321. updatedMeshes: _this._addUpdateMeshesList,
  9322. updatedGeometries: _this._addUpdateGeometriesList,
  9323. removedGeometries: _this._toRemoveGeometryArray,
  9324. removedMeshes: _this._toRemoveMeshesArray
  9325. };
  9326. var message = {
  9327. payload: payload,
  9328. taskType: WorkerTaskType.UPDATE
  9329. };
  9330. var serializable = [];
  9331. for (var id in payload.updatedGeometries) {
  9332. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9333. //prepare transferables
  9334. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9335. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9336. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9337. }
  9338. }
  9339. _this._worker.postMessage(message, serializable);
  9340. _this._addUpdateMeshesList = {};
  9341. _this._addUpdateGeometriesList = {};
  9342. _this._toRemoveGeometryArray = [];
  9343. _this._toRemoveMeshesArray = [];
  9344. };
  9345. this._onMessageFromWorker = function (e) {
  9346. var returnData = e.data;
  9347. if (returnData.error != WorkerReplyType.SUCCESS) {
  9348. //TODO what errors can be returned from the worker?
  9349. BABYLON.Tools.Warn("error returned from worker!");
  9350. return;
  9351. }
  9352. switch (returnData.taskType) {
  9353. case WorkerTaskType.INIT:
  9354. _this._init = true;
  9355. //Update the worked with ALL of the scene's current state
  9356. _this._scene.meshes.forEach(function (mesh) {
  9357. _this.onMeshAdded(mesh);
  9358. });
  9359. _this._scene.getGeometries().forEach(function (geometry) {
  9360. _this.onGeometryAdded(geometry);
  9361. });
  9362. break;
  9363. case WorkerTaskType.UPDATE:
  9364. _this._runningUpdated--;
  9365. break;
  9366. case WorkerTaskType.COLLIDE:
  9367. _this._runningCollisionTask = false;
  9368. var returnPayload = returnData.payload;
  9369. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9370. return;
  9371. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9372. //cleanup
  9373. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9374. break;
  9375. }
  9376. };
  9377. this._collisionsCallbackArray = [];
  9378. this._init = false;
  9379. this._runningUpdated = 0;
  9380. this._runningCollisionTask = false;
  9381. this._addUpdateMeshesList = {};
  9382. this._addUpdateGeometriesList = {};
  9383. this._toRemoveGeometryArray = [];
  9384. this._toRemoveMeshesArray = [];
  9385. }
  9386. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9387. if (!this._init)
  9388. return;
  9389. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9390. return;
  9391. position.divideToRef(collider.radius, this._scaledPosition);
  9392. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9393. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9394. var payload = {
  9395. collider: {
  9396. position: this._scaledPosition.asArray(),
  9397. velocity: this._scaledVelocity.asArray(),
  9398. radius: collider.radius.asArray()
  9399. },
  9400. collisionId: collisionIndex,
  9401. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9402. maximumRetry: maximumRetry
  9403. };
  9404. var message = {
  9405. payload: payload,
  9406. taskType: WorkerTaskType.COLLIDE
  9407. };
  9408. this._worker.postMessage(message);
  9409. };
  9410. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9411. this._scene = scene;
  9412. this._scene.registerAfterRender(this._afterRender);
  9413. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9414. this._worker = new Worker(workerUrl);
  9415. this._worker.onmessage = this._onMessageFromWorker;
  9416. var message = {
  9417. payload: {},
  9418. taskType: WorkerTaskType.INIT
  9419. };
  9420. this._worker.postMessage(message);
  9421. };
  9422. CollisionCoordinatorWorker.prototype.destroy = function () {
  9423. this._scene.unregisterAfterRender(this._afterRender);
  9424. this._worker.terminate();
  9425. };
  9426. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9427. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9428. this.onMeshUpdated(mesh);
  9429. };
  9430. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9431. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9432. };
  9433. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9434. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9435. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9436. this.onGeometryUpdated(geometry);
  9437. };
  9438. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9439. this._toRemoveGeometryArray.push(geometry.id);
  9440. };
  9441. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9442. var submeshes = [];
  9443. if (mesh.subMeshes) {
  9444. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9445. return {
  9446. position: idx,
  9447. verticesStart: sm.verticesStart,
  9448. verticesCount: sm.verticesCount,
  9449. indexStart: sm.indexStart,
  9450. indexCount: sm.indexCount,
  9451. hasMaterial: !!sm.getMaterial(),
  9452. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9453. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9454. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9455. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9456. };
  9457. });
  9458. }
  9459. var geometryId = mesh.geometry ? mesh.geometry.id : null;
  9460. return {
  9461. uniqueId: mesh.uniqueId,
  9462. id: mesh.id,
  9463. name: mesh.name,
  9464. geometryId: geometryId,
  9465. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9466. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9467. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9468. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9469. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9470. subMeshes: submeshes,
  9471. checkCollisions: mesh.checkCollisions
  9472. };
  9473. };
  9474. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9475. return {
  9476. id: geometry.id,
  9477. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9478. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9479. indices: new Int32Array(geometry.getIndices() || []),
  9480. };
  9481. };
  9482. return CollisionCoordinatorWorker;
  9483. })();
  9484. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9485. var CollisionCoordinatorLegacy = (function () {
  9486. function CollisionCoordinatorLegacy() {
  9487. this._scaledPosition = BABYLON.Vector3.Zero();
  9488. this._scaledVelocity = BABYLON.Vector3.Zero();
  9489. this._finalPosition = BABYLON.Vector3.Zero();
  9490. }
  9491. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9492. position.divideToRef(collider.radius, this._scaledPosition);
  9493. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9494. collider.collidedMesh = null;
  9495. collider.retry = 0;
  9496. collider.initialVelocity = this._scaledVelocity;
  9497. collider.initialPosition = this._scaledPosition;
  9498. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9499. this._finalPosition.multiplyInPlace(collider.radius);
  9500. //run the callback
  9501. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9502. };
  9503. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9504. this._scene = scene;
  9505. };
  9506. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9507. //Legacy need no destruction method.
  9508. };
  9509. //No update in legacy mode
  9510. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9511. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9512. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9513. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9514. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9515. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9516. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9517. if (excludedMesh === void 0) { excludedMesh = null; }
  9518. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9519. if (collider.retry >= maximumRetry) {
  9520. finalPosition.copyFrom(position);
  9521. return;
  9522. }
  9523. collider._initialize(position, velocity, closeDistance);
  9524. // Check all meshes
  9525. for (var index = 0; index < this._scene.meshes.length; index++) {
  9526. var mesh = this._scene.meshes[index];
  9527. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9528. mesh._checkCollision(collider);
  9529. }
  9530. }
  9531. if (!collider.collisionFound) {
  9532. position.addToRef(velocity, finalPosition);
  9533. return;
  9534. }
  9535. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9536. collider._getResponse(position, velocity);
  9537. }
  9538. if (velocity.length() <= closeDistance) {
  9539. finalPosition.copyFrom(position);
  9540. return;
  9541. }
  9542. collider.retry++;
  9543. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9544. };
  9545. return CollisionCoordinatorLegacy;
  9546. })();
  9547. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9548. })(BABYLON || (BABYLON = {}));
  9549. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  9550. var BABYLON;
  9551. (function (BABYLON) {
  9552. var VRCameraMetrics = (function () {
  9553. function VRCameraMetrics() {
  9554. this.compensateDistorsion = true;
  9555. }
  9556. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9557. get: function () {
  9558. return this.hResolution / (2 * this.vResolution);
  9559. },
  9560. enumerable: true,
  9561. configurable: true
  9562. });
  9563. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9564. get: function () {
  9565. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9566. },
  9567. enumerable: true,
  9568. configurable: true
  9569. });
  9570. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9571. get: function () {
  9572. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9573. var h = (4 * meters) / this.hScreenSize;
  9574. return BABYLON.Matrix.Translation(h, 0, 0);
  9575. },
  9576. enumerable: true,
  9577. configurable: true
  9578. });
  9579. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9580. get: function () {
  9581. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9582. var h = (4 * meters) / this.hScreenSize;
  9583. return BABYLON.Matrix.Translation(-h, 0, 0);
  9584. },
  9585. enumerable: true,
  9586. configurable: true
  9587. });
  9588. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9589. get: function () {
  9590. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9591. },
  9592. enumerable: true,
  9593. configurable: true
  9594. });
  9595. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9596. get: function () {
  9597. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9598. },
  9599. enumerable: true,
  9600. configurable: true
  9601. });
  9602. VRCameraMetrics.GetDefault = function () {
  9603. var result = new VRCameraMetrics();
  9604. result.hResolution = 1280;
  9605. result.vResolution = 800;
  9606. result.hScreenSize = 0.149759993;
  9607. result.vScreenSize = 0.0935999975;
  9608. result.vScreenCenter = 0.0467999987,
  9609. result.eyeToScreenDistance = 0.0410000011;
  9610. result.lensSeparationDistance = 0.0635000020;
  9611. result.interpupillaryDistance = 0.0640000030;
  9612. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9613. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9614. result.postProcessScaleFactor = 1.714605507808412;
  9615. result.lensCenterOffset = 0.151976421;
  9616. return result;
  9617. };
  9618. return VRCameraMetrics;
  9619. })();
  9620. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9621. var Camera = (function (_super) {
  9622. __extends(Camera, _super);
  9623. function Camera(name, position, scene) {
  9624. _super.call(this, name, scene);
  9625. this.position = position;
  9626. // Members
  9627. this.upVector = BABYLON.Vector3.Up();
  9628. this.orthoLeft = null;
  9629. this.orthoRight = null;
  9630. this.orthoBottom = null;
  9631. this.orthoTop = null;
  9632. this.fov = 0.8;
  9633. this.minZ = 1.0;
  9634. this.maxZ = 10000.0;
  9635. this.inertia = 0.9;
  9636. this.mode = Camera.PERSPECTIVE_CAMERA;
  9637. this.isIntermediate = false;
  9638. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9639. this.layerMask = 0x0FFFFFFF;
  9640. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9641. // Subcamera members
  9642. this.subCameras = new Array();
  9643. this._subCameraMode = Camera.SUB_CAMERA_MODE_NONE;
  9644. // Cache
  9645. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9646. this._projectionMatrix = new BABYLON.Matrix();
  9647. this._postProcesses = new Array();
  9648. this._postProcessesTakenIndices = [];
  9649. this._activeMeshes = new BABYLON.SmartArray(256);
  9650. this._globalPosition = BABYLON.Vector3.Zero();
  9651. scene.addCamera(this);
  9652. if (!scene.activeCamera) {
  9653. scene.activeCamera = this;
  9654. }
  9655. }
  9656. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9657. get: function () {
  9658. return Camera._PERSPECTIVE_CAMERA;
  9659. },
  9660. enumerable: true,
  9661. configurable: true
  9662. });
  9663. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9664. get: function () {
  9665. return Camera._ORTHOGRAPHIC_CAMERA;
  9666. },
  9667. enumerable: true,
  9668. configurable: true
  9669. });
  9670. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9671. get: function () {
  9672. return Camera._FOVMODE_VERTICAL_FIXED;
  9673. },
  9674. enumerable: true,
  9675. configurable: true
  9676. });
  9677. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9678. get: function () {
  9679. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9680. },
  9681. enumerable: true,
  9682. configurable: true
  9683. });
  9684. Object.defineProperty(Camera, "SUB_CAMERA_MODE_NONE", {
  9685. get: function () {
  9686. return Camera._SUB_CAMERA_MODE_NONE;
  9687. },
  9688. enumerable: true,
  9689. configurable: true
  9690. });
  9691. Object.defineProperty(Camera, "SUB_CAMERA_MODE_ANAGLYPH", {
  9692. get: function () {
  9693. return Camera._SUB_CAMERA_MODE_ANAGLYPH;
  9694. },
  9695. enumerable: true,
  9696. configurable: true
  9697. });
  9698. Object.defineProperty(Camera, "SUB_CAMERA_MODE_CROSSEDSIDEBYSIDE_STEREOSCOPIC", {
  9699. get: function () {
  9700. return Camera._SUB_CAMERA_MODE_CROSSEDSIDEBYSIDE_STEREOSCOPIC;
  9701. },
  9702. enumerable: true,
  9703. configurable: true
  9704. });
  9705. Object.defineProperty(Camera, "SUB_CAMERA_MODE_OVERUNDER_STEREOSCOPIC", {
  9706. get: function () {
  9707. return Camera._SUB_CAMERA_MODE_OVERUNDER_STEREOSCOPIC;
  9708. },
  9709. enumerable: true,
  9710. configurable: true
  9711. });
  9712. Object.defineProperty(Camera, "SUB_CAMERA_MODE_VR", {
  9713. get: function () {
  9714. return Camera._SUB_CAMERA_MODE_VR;
  9715. },
  9716. enumerable: true,
  9717. configurable: true
  9718. });
  9719. Object.defineProperty(Camera, "SUB_CAMERAID_A", {
  9720. get: function () {
  9721. return Camera._SUB_CAMERAID_A;
  9722. },
  9723. enumerable: true,
  9724. configurable: true
  9725. });
  9726. Object.defineProperty(Camera, "SUB_CAMERAID_B", {
  9727. get: function () {
  9728. return Camera._SUB_CAMERAID_B;
  9729. },
  9730. enumerable: true,
  9731. configurable: true
  9732. });
  9733. Object.defineProperty(Camera.prototype, "globalPosition", {
  9734. get: function () {
  9735. return this._globalPosition;
  9736. },
  9737. enumerable: true,
  9738. configurable: true
  9739. });
  9740. Camera.prototype.getActiveMeshes = function () {
  9741. return this._activeMeshes;
  9742. };
  9743. Camera.prototype.isActiveMesh = function (mesh) {
  9744. return (this._activeMeshes.indexOf(mesh) !== -1);
  9745. };
  9746. //Cache
  9747. Camera.prototype._initCache = function () {
  9748. _super.prototype._initCache.call(this);
  9749. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9750. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9751. this._cache.mode = undefined;
  9752. this._cache.minZ = undefined;
  9753. this._cache.maxZ = undefined;
  9754. this._cache.fov = undefined;
  9755. this._cache.aspectRatio = undefined;
  9756. this._cache.orthoLeft = undefined;
  9757. this._cache.orthoRight = undefined;
  9758. this._cache.orthoBottom = undefined;
  9759. this._cache.orthoTop = undefined;
  9760. this._cache.renderWidth = undefined;
  9761. this._cache.renderHeight = undefined;
  9762. };
  9763. Camera.prototype._updateCache = function (ignoreParentClass) {
  9764. if (!ignoreParentClass) {
  9765. _super.prototype._updateCache.call(this);
  9766. }
  9767. var engine = this.getEngine();
  9768. this._cache.position.copyFrom(this.position);
  9769. this._cache.upVector.copyFrom(this.upVector);
  9770. this._cache.mode = this.mode;
  9771. this._cache.minZ = this.minZ;
  9772. this._cache.maxZ = this.maxZ;
  9773. this._cache.fov = this.fov;
  9774. this._cache.aspectRatio = engine.getAspectRatio(this);
  9775. this._cache.orthoLeft = this.orthoLeft;
  9776. this._cache.orthoRight = this.orthoRight;
  9777. this._cache.orthoBottom = this.orthoBottom;
  9778. this._cache.orthoTop = this.orthoTop;
  9779. this._cache.renderWidth = engine.getRenderWidth();
  9780. this._cache.renderHeight = engine.getRenderHeight();
  9781. };
  9782. Camera.prototype._updateFromScene = function () {
  9783. this.updateCache();
  9784. this._update();
  9785. };
  9786. // Synchronized
  9787. Camera.prototype._isSynchronized = function () {
  9788. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  9789. };
  9790. Camera.prototype._isSynchronizedViewMatrix = function () {
  9791. if (!_super.prototype._isSynchronized.call(this))
  9792. return false;
  9793. return this._cache.position.equals(this.position)
  9794. && this._cache.upVector.equals(this.upVector)
  9795. && this.isSynchronizedWithParent();
  9796. };
  9797. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  9798. var check = this._cache.mode === this.mode
  9799. && this._cache.minZ === this.minZ
  9800. && this._cache.maxZ === this.maxZ;
  9801. if (!check) {
  9802. return false;
  9803. }
  9804. var engine = this.getEngine();
  9805. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9806. check = this._cache.fov === this.fov
  9807. && this._cache.aspectRatio === engine.getAspectRatio(this);
  9808. }
  9809. else {
  9810. check = this._cache.orthoLeft === this.orthoLeft
  9811. && this._cache.orthoRight === this.orthoRight
  9812. && this._cache.orthoBottom === this.orthoBottom
  9813. && this._cache.orthoTop === this.orthoTop
  9814. && this._cache.renderWidth === engine.getRenderWidth()
  9815. && this._cache.renderHeight === engine.getRenderHeight();
  9816. }
  9817. return check;
  9818. };
  9819. // Controls
  9820. Camera.prototype.attachControl = function (element) {
  9821. };
  9822. Camera.prototype.detachControl = function (element) {
  9823. };
  9824. Camera.prototype._update = function () {
  9825. this._checkInputs();
  9826. if (this._subCameraMode !== Camera.SUB_CAMERA_MODE_NONE) {
  9827. this._updateSubCameras();
  9828. }
  9829. };
  9830. Camera.prototype._checkInputs = function () {
  9831. };
  9832. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  9833. if (insertAt === void 0) { insertAt = null; }
  9834. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  9835. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  9836. return 0;
  9837. }
  9838. if (insertAt == null || insertAt < 0) {
  9839. this._postProcesses.push(postProcess);
  9840. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  9841. return this._postProcesses.length - 1;
  9842. }
  9843. var add = 0;
  9844. if (this._postProcesses[insertAt]) {
  9845. var start = this._postProcesses.length - 1;
  9846. for (var i = start; i >= insertAt + 1; --i) {
  9847. this._postProcesses[i + 1] = this._postProcesses[i];
  9848. }
  9849. add = 1;
  9850. }
  9851. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9852. if (this._postProcessesTakenIndices[i] < insertAt) {
  9853. continue;
  9854. }
  9855. start = this._postProcessesTakenIndices.length - 1;
  9856. for (var j = start; j >= i; --j) {
  9857. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  9858. }
  9859. this._postProcessesTakenIndices[i] = insertAt;
  9860. break;
  9861. }
  9862. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  9863. this._postProcessesTakenIndices.push(insertAt);
  9864. }
  9865. var result = insertAt + add;
  9866. this._postProcesses[result] = postProcess;
  9867. return result;
  9868. };
  9869. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  9870. if (atIndices === void 0) { atIndices = null; }
  9871. var result = [];
  9872. if (!atIndices) {
  9873. var length = this._postProcesses.length;
  9874. for (var i = 0; i < length; i++) {
  9875. if (this._postProcesses[i] !== postProcess) {
  9876. continue;
  9877. }
  9878. delete this._postProcesses[i];
  9879. var index = this._postProcessesTakenIndices.indexOf(i);
  9880. this._postProcessesTakenIndices.splice(index, 1);
  9881. }
  9882. }
  9883. else {
  9884. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  9885. for (i = 0; i < atIndices.length; i++) {
  9886. var foundPostProcess = this._postProcesses[atIndices[i]];
  9887. if (foundPostProcess !== postProcess) {
  9888. result.push(i);
  9889. continue;
  9890. }
  9891. delete this._postProcesses[atIndices[i]];
  9892. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  9893. this._postProcessesTakenIndices.splice(index, 1);
  9894. }
  9895. }
  9896. return result;
  9897. };
  9898. Camera.prototype.getWorldMatrix = function () {
  9899. if (!this._worldMatrix) {
  9900. this._worldMatrix = BABYLON.Matrix.Identity();
  9901. }
  9902. var viewMatrix = this.getViewMatrix();
  9903. viewMatrix.invertToRef(this._worldMatrix);
  9904. return this._worldMatrix;
  9905. };
  9906. Camera.prototype._getViewMatrix = function () {
  9907. return BABYLON.Matrix.Identity();
  9908. };
  9909. Camera.prototype.getViewMatrix = function (force) {
  9910. this._computedViewMatrix = this._computeViewMatrix(force);
  9911. if (!force && this._isSynchronizedViewMatrix()) {
  9912. return this._computedViewMatrix;
  9913. }
  9914. if (!this.parent || !this.parent.getWorldMatrix) {
  9915. this._globalPosition.copyFrom(this.position);
  9916. }
  9917. else {
  9918. if (!this._worldMatrix) {
  9919. this._worldMatrix = BABYLON.Matrix.Identity();
  9920. }
  9921. this._computedViewMatrix.invertToRef(this._worldMatrix);
  9922. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  9923. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  9924. this._computedViewMatrix.invert();
  9925. this._markSyncedWithParent();
  9926. }
  9927. this._currentRenderId = this.getScene().getRenderId();
  9928. return this._computedViewMatrix;
  9929. };
  9930. Camera.prototype._computeViewMatrix = function (force) {
  9931. if (!force && this._isSynchronizedViewMatrix()) {
  9932. return this._computedViewMatrix;
  9933. }
  9934. this._computedViewMatrix = this._getViewMatrix();
  9935. this._currentRenderId = this.getScene().getRenderId();
  9936. return this._computedViewMatrix;
  9937. };
  9938. Camera.prototype.getProjectionMatrix = function (force) {
  9939. if (!force && this._isSynchronizedProjectionMatrix()) {
  9940. return this._projectionMatrix;
  9941. }
  9942. var engine = this.getEngine();
  9943. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9944. if (this.minZ <= 0) {
  9945. this.minZ = 0.1;
  9946. }
  9947. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  9948. return this._projectionMatrix;
  9949. }
  9950. var halfWidth = engine.getRenderWidth() / 2.0;
  9951. var halfHeight = engine.getRenderHeight() / 2.0;
  9952. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  9953. return this._projectionMatrix;
  9954. };
  9955. Camera.prototype.dispose = function () {
  9956. // Remove from scene
  9957. this.getScene().removeCamera(this);
  9958. while (this.subCameras.length > 0) {
  9959. this.subCameras.pop().dispose();
  9960. }
  9961. // Postprocesses
  9962. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9963. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  9964. }
  9965. };
  9966. // ---- 3D cameras section ----
  9967. Camera.prototype.setSubCameraMode = function (mode, halfSpace, metrics) {
  9968. if (halfSpace === void 0) { halfSpace = 0; }
  9969. while (this.subCameras.length > 0) {
  9970. this.subCameras.pop().dispose();
  9971. }
  9972. this._subCameraMode = mode;
  9973. this._subCamHalfSpace = BABYLON.Tools.ToRadians(halfSpace);
  9974. var camA = this.getSubCamera(this.name + "_A", true);
  9975. var camB = this.getSubCamera(this.name + "_B", false);
  9976. var postProcessA;
  9977. var postProcessB;
  9978. switch (this._subCameraMode) {
  9979. case Camera.SUB_CAMERA_MODE_ANAGLYPH:
  9980. postProcessA = new BABYLON.PassPostProcess(this.name + "_leftTexture", 1.0, camA);
  9981. camA.isIntermediate = true;
  9982. postProcessB = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, camB);
  9983. postProcessB.onApply = function (effect) {
  9984. effect.setTextureFromPostProcess("leftSampler", postProcessA);
  9985. };
  9986. break;
  9987. case Camera.SUB_CAMERA_MODE_CROSSEDSIDEBYSIDE_STEREOSCOPIC:
  9988. case Camera.SUB_CAMERA_MODE_OVERUNDER_STEREOSCOPIC:
  9989. var isStereoscopicHoriz = this._subCameraMode === Camera.SUB_CAMERA_MODE_CROSSEDSIDEBYSIDE_STEREOSCOPIC;
  9990. postProcessA = new BABYLON.PassPostProcess("passthru", 1.0, camA);
  9991. camA.isIntermediate = true;
  9992. postProcessB = new BABYLON.StereoscopicInterlacePostProcess("st_interlace", camB, postProcessA, isStereoscopicHoriz);
  9993. break;
  9994. case Camera.SUB_CAMERA_MODE_VR:
  9995. metrics = metrics || VRCameraMetrics.GetDefault();
  9996. camA._vrMetrics = metrics;
  9997. camA.viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  9998. camA._vrWorkMatrix = new BABYLON.Matrix();
  9999. camA._vrHMatrix = metrics.leftHMatrix;
  10000. camA._vrPreViewMatrix = metrics.leftPreViewMatrix;
  10001. camA.getProjectionMatrix = camA._getVRProjectionMatrix;
  10002. if (metrics.compensateDistorsion) {
  10003. postProcessA = new BABYLON.VRDistortionCorrectionPostProcess("Distortion Compensation Left", camA, false, metrics);
  10004. }
  10005. camB._vrMetrics = camA._vrMetrics;
  10006. camB.viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10007. camB._vrWorkMatrix = new BABYLON.Matrix();
  10008. camB._vrHMatrix = metrics.rightHMatrix;
  10009. camB._vrPreViewMatrix = metrics.rightPreViewMatrix;
  10010. camB.getProjectionMatrix = camB._getVRProjectionMatrix;
  10011. if (metrics.compensateDistorsion) {
  10012. postProcessB = new BABYLON.VRDistortionCorrectionPostProcess("Distortion Compensation Right", camB, true, metrics);
  10013. }
  10014. }
  10015. if (this._subCameraMode !== Camera.SUB_CAMERA_MODE_NONE) {
  10016. this.subCameras.push(camA);
  10017. this.subCameras.push(camB);
  10018. }
  10019. this._update();
  10020. };
  10021. Camera.prototype._getVRProjectionMatrix = function () {
  10022. BABYLON.Matrix.PerspectiveFovLHToRef(this._vrMetrics.aspectRatioFov, this._vrMetrics.aspectRatio, this.minZ, this.maxZ, this._vrWorkMatrix);
  10023. this._vrWorkMatrix.multiplyToRef(this._vrHMatrix, this._projectionMatrix);
  10024. return this._projectionMatrix;
  10025. };
  10026. Camera.prototype.setSubCamHalfSpace = function (halfSpace) {
  10027. this._subCamHalfSpace = BABYLON.Tools.ToRadians(halfSpace);
  10028. };
  10029. /**
  10030. * May needs to be overridden by children so sub has required properties to be copied
  10031. */
  10032. Camera.prototype.getSubCamera = function (name, isA) {
  10033. return null;
  10034. };
  10035. /**
  10036. * May needs to be overridden by children
  10037. */
  10038. Camera.prototype._updateSubCameras = function () {
  10039. var camA = this.subCameras[Camera.SUB_CAMERAID_A];
  10040. var camB = this.subCameras[Camera.SUB_CAMERAID_B];
  10041. camA.minZ = camB.minZ = this.minZ;
  10042. camA.maxZ = camB.maxZ = this.maxZ;
  10043. camA.fov = camB.fov = this.fov;
  10044. // only update viewport, when ANAGLYPH
  10045. if (this._subCameraMode === Camera.SUB_CAMERA_MODE_ANAGLYPH) {
  10046. camA.viewport = camB.viewport = this.viewport;
  10047. }
  10048. };
  10049. // Statics
  10050. Camera._PERSPECTIVE_CAMERA = 0;
  10051. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10052. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10053. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10054. Camera._SUB_CAMERA_MODE_NONE = 0;
  10055. Camera._SUB_CAMERA_MODE_ANAGLYPH = 1;
  10056. Camera._SUB_CAMERA_MODE_CROSSEDSIDEBYSIDE_STEREOSCOPIC = 2;
  10057. Camera._SUB_CAMERA_MODE_OVERUNDER_STEREOSCOPIC = 3;
  10058. Camera._SUB_CAMERA_MODE_VR = 4;
  10059. Camera._SUB_CAMERAID_A = 0;
  10060. Camera._SUB_CAMERAID_B = 1;
  10061. return Camera;
  10062. })(BABYLON.Node);
  10063. BABYLON.Camera = Camera;
  10064. })(BABYLON || (BABYLON = {}));
  10065. //# sourceMappingURL=babylon.camera.js.map
  10066. var BABYLON;
  10067. (function (BABYLON) {
  10068. var TargetCamera = (function (_super) {
  10069. __extends(TargetCamera, _super);
  10070. function TargetCamera(name, position, scene) {
  10071. _super.call(this, name, position, scene);
  10072. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10073. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10074. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10075. this.speed = 2.0;
  10076. this.noRotationConstraint = false;
  10077. this.lockedTarget = null;
  10078. this._currentTarget = BABYLON.Vector3.Zero();
  10079. this._viewMatrix = BABYLON.Matrix.Zero();
  10080. this._camMatrix = BABYLON.Matrix.Zero();
  10081. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10082. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10083. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10084. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10085. this._lookAtTemp = BABYLON.Matrix.Zero();
  10086. this._tempMatrix = BABYLON.Matrix.Zero();
  10087. }
  10088. TargetCamera.prototype._getLockedTargetPosition = function () {
  10089. if (!this.lockedTarget) {
  10090. return null;
  10091. }
  10092. return this.lockedTarget.position || this.lockedTarget;
  10093. };
  10094. // Cache
  10095. TargetCamera.prototype._initCache = function () {
  10096. _super.prototype._initCache.call(this);
  10097. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10098. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10099. };
  10100. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10101. if (!ignoreParentClass) {
  10102. _super.prototype._updateCache.call(this);
  10103. }
  10104. var lockedTargetPosition = this._getLockedTargetPosition();
  10105. if (!lockedTargetPosition) {
  10106. this._cache.lockedTarget = null;
  10107. }
  10108. else {
  10109. if (!this._cache.lockedTarget) {
  10110. this._cache.lockedTarget = lockedTargetPosition.clone();
  10111. }
  10112. else {
  10113. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10114. }
  10115. }
  10116. this._cache.rotation.copyFrom(this.rotation);
  10117. };
  10118. // Synchronized
  10119. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10120. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10121. return false;
  10122. }
  10123. var lockedTargetPosition = this._getLockedTargetPosition();
  10124. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10125. && this._cache.rotation.equals(this.rotation);
  10126. };
  10127. // Methods
  10128. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10129. var engine = this.getEngine();
  10130. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10131. };
  10132. // Target
  10133. TargetCamera.prototype.setTarget = function (target) {
  10134. this.upVector.normalize();
  10135. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10136. this._camMatrix.invert();
  10137. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10138. var vDir = target.subtract(this.position);
  10139. if (vDir.x >= 0.0) {
  10140. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10141. }
  10142. else {
  10143. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10144. }
  10145. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10146. if (isNaN(this.rotation.x)) {
  10147. this.rotation.x = 0;
  10148. }
  10149. if (isNaN(this.rotation.y)) {
  10150. this.rotation.y = 0;
  10151. }
  10152. if (isNaN(this.rotation.z)) {
  10153. this.rotation.z = 0;
  10154. }
  10155. };
  10156. TargetCamera.prototype.getTarget = function () {
  10157. return this._currentTarget;
  10158. };
  10159. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10160. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10161. };
  10162. TargetCamera.prototype._updatePosition = function () {
  10163. this.position.addInPlace(this.cameraDirection);
  10164. };
  10165. TargetCamera.prototype._checkInputs = function () {
  10166. var needToMove = this._decideIfNeedsToMove();
  10167. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10168. // Move
  10169. if (needToMove) {
  10170. this._updatePosition();
  10171. }
  10172. // Rotate
  10173. if (needToRotate) {
  10174. this.rotation.x += this.cameraRotation.x;
  10175. this.rotation.y += this.cameraRotation.y;
  10176. if (!this.noRotationConstraint) {
  10177. var limit = (Math.PI / 2) * 0.95;
  10178. if (this.rotation.x > limit)
  10179. this.rotation.x = limit;
  10180. if (this.rotation.x < -limit)
  10181. this.rotation.x = -limit;
  10182. }
  10183. }
  10184. // Inertia
  10185. if (needToMove) {
  10186. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10187. this.cameraDirection.x = 0;
  10188. }
  10189. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10190. this.cameraDirection.y = 0;
  10191. }
  10192. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10193. this.cameraDirection.z = 0;
  10194. }
  10195. this.cameraDirection.scaleInPlace(this.inertia);
  10196. }
  10197. if (needToRotate) {
  10198. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10199. this.cameraRotation.x = 0;
  10200. }
  10201. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10202. this.cameraRotation.y = 0;
  10203. }
  10204. this.cameraRotation.scaleInPlace(this.inertia);
  10205. }
  10206. _super.prototype._checkInputs.call(this);
  10207. };
  10208. TargetCamera.prototype._getViewMatrix = function () {
  10209. if (!this.lockedTarget) {
  10210. // Compute
  10211. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10212. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10213. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10214. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10215. this._lookAtTemp.invert();
  10216. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10217. }
  10218. else {
  10219. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10220. }
  10221. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10222. // Computing target and final matrix
  10223. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10224. }
  10225. else {
  10226. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10227. }
  10228. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10229. return this._viewMatrix;
  10230. };
  10231. TargetCamera.prototype._getVRViewMatrix = function () {
  10232. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10233. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10234. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._vrActualUp);
  10235. // Computing target and final matrix
  10236. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10237. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._vrActualUp, this._vrWorkMatrix);
  10238. this._vrWorkMatrix.multiplyToRef(this._vrPreViewMatrix, this._viewMatrix);
  10239. return this._viewMatrix;
  10240. };
  10241. /**
  10242. * @override
  10243. * needs to be overridden, so sub has required properties to be copied
  10244. */
  10245. TargetCamera.prototype.getSubCamera = function (name, isA) {
  10246. var subCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10247. if (this._subCameraMode === BABYLON.Camera.SUB_CAMERA_MODE_VR) {
  10248. subCamera._vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10249. subCamera._getViewMatrix = subCamera._getVRViewMatrix;
  10250. }
  10251. return subCamera;
  10252. };
  10253. /**
  10254. * @override
  10255. * needs to be overridden, adding copy of position, and rotation for VR, or target for rest
  10256. */
  10257. TargetCamera.prototype._updateSubCameras = function () {
  10258. var camA = this.subCameras[BABYLON.Camera.SUB_CAMERAID_A];
  10259. var camB = this.subCameras[BABYLON.Camera.SUB_CAMERAID_B];
  10260. if (this._subCameraMode === BABYLON.Camera.SUB_CAMERA_MODE_VR) {
  10261. camA.rotation.x = camB.rotation.x = this.rotation.x;
  10262. camA.rotation.y = camB.rotation.y = this.rotation.y;
  10263. camA.rotation.z = camB.rotation.z = this.rotation.z;
  10264. camA.position.copyFrom(this.position);
  10265. camB.position.copyFrom(this.position);
  10266. }
  10267. else {
  10268. camA.setTarget(this.getTarget());
  10269. camB.setTarget(this.getTarget());
  10270. this._getSubCamPosition(-this._subCamHalfSpace, camA.position);
  10271. this._getSubCamPosition(this._subCamHalfSpace, camB.position);
  10272. }
  10273. _super.prototype._updateSubCameras.call(this);
  10274. };
  10275. TargetCamera.prototype._getSubCamPosition = function (halfSpace, result) {
  10276. if (!this._subCamTransformMatrix) {
  10277. this._subCamTransformMatrix = new BABYLON.Matrix();
  10278. }
  10279. var target = this.getTarget();
  10280. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._subCamTransformMatrix);
  10281. this._subCamTransformMatrix = this._subCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10282. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._subCamTransformMatrix, result);
  10283. };
  10284. return TargetCamera;
  10285. })(BABYLON.Camera);
  10286. BABYLON.TargetCamera = TargetCamera;
  10287. })(BABYLON || (BABYLON = {}));
  10288. //# sourceMappingURL=babylon.targetCamera.js.map
  10289. var BABYLON;
  10290. (function (BABYLON) {
  10291. var FreeCamera = (function (_super) {
  10292. __extends(FreeCamera, _super);
  10293. function FreeCamera(name, position, scene) {
  10294. var _this = this;
  10295. _super.call(this, name, position, scene);
  10296. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10297. this.keysUp = [38];
  10298. this.keysDown = [40];
  10299. this.keysLeft = [37];
  10300. this.keysRight = [39];
  10301. this.checkCollisions = false;
  10302. this.applyGravity = false;
  10303. this.angularSensibility = 2000.0;
  10304. this._keys = [];
  10305. this._collider = new BABYLON.Collider();
  10306. this._needMoveForGravity = false;
  10307. this._oldPosition = BABYLON.Vector3.Zero();
  10308. this._diffPosition = BABYLON.Vector3.Zero();
  10309. this._newPosition = BABYLON.Vector3.Zero();
  10310. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10311. if (collidedMesh === void 0) { collidedMesh = null; }
  10312. //TODO move this to the collision coordinator!
  10313. if (_this.getScene().workerCollisions)
  10314. newPosition.multiplyInPlace(_this._collider.radius);
  10315. var updatePosition = function (newPos) {
  10316. _this._newPosition.copyFrom(newPos);
  10317. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10318. var oldPosition = _this.position.clone();
  10319. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10320. _this.position.addInPlace(_this._diffPosition);
  10321. if (_this.onCollide && collidedMesh) {
  10322. _this.onCollide(collidedMesh);
  10323. }
  10324. }
  10325. };
  10326. updatePosition(newPosition);
  10327. };
  10328. }
  10329. // Controls
  10330. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10331. var _this = this;
  10332. var previousPosition;
  10333. var engine = this.getEngine();
  10334. if (this._attachedElement) {
  10335. return;
  10336. }
  10337. this._attachedElement = element;
  10338. if (this._onMouseDown === undefined) {
  10339. this._onMouseDown = function (evt) {
  10340. previousPosition = {
  10341. x: evt.clientX,
  10342. y: evt.clientY
  10343. };
  10344. if (!noPreventDefault) {
  10345. evt.preventDefault();
  10346. }
  10347. };
  10348. this._onMouseUp = function (evt) {
  10349. previousPosition = null;
  10350. if (!noPreventDefault) {
  10351. evt.preventDefault();
  10352. }
  10353. };
  10354. this._onMouseOut = function (evt) {
  10355. previousPosition = null;
  10356. _this._keys = [];
  10357. if (!noPreventDefault) {
  10358. evt.preventDefault();
  10359. }
  10360. };
  10361. this._onMouseMove = function (evt) {
  10362. if (!previousPosition && !engine.isPointerLock) {
  10363. return;
  10364. }
  10365. var offsetX;
  10366. var offsetY;
  10367. if (!engine.isPointerLock) {
  10368. offsetX = evt.clientX - previousPosition.x;
  10369. offsetY = evt.clientY - previousPosition.y;
  10370. }
  10371. else {
  10372. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10373. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10374. }
  10375. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10376. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10377. previousPosition = {
  10378. x: evt.clientX,
  10379. y: evt.clientY
  10380. };
  10381. if (!noPreventDefault) {
  10382. evt.preventDefault();
  10383. }
  10384. };
  10385. this._onKeyDown = function (evt) {
  10386. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10387. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10388. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10389. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10390. var index = _this._keys.indexOf(evt.keyCode);
  10391. if (index === -1) {
  10392. _this._keys.push(evt.keyCode);
  10393. }
  10394. if (!noPreventDefault) {
  10395. evt.preventDefault();
  10396. }
  10397. }
  10398. };
  10399. this._onKeyUp = function (evt) {
  10400. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10401. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10402. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10403. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10404. var index = _this._keys.indexOf(evt.keyCode);
  10405. if (index >= 0) {
  10406. _this._keys.splice(index, 1);
  10407. }
  10408. if (!noPreventDefault) {
  10409. evt.preventDefault();
  10410. }
  10411. }
  10412. };
  10413. this._onLostFocus = function () {
  10414. _this._keys = [];
  10415. };
  10416. this._reset = function () {
  10417. _this._keys = [];
  10418. previousPosition = null;
  10419. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10420. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10421. };
  10422. }
  10423. element.addEventListener("mousedown", this._onMouseDown, false);
  10424. element.addEventListener("mouseup", this._onMouseUp, false);
  10425. element.addEventListener("mouseout", this._onMouseOut, false);
  10426. element.addEventListener("mousemove", this._onMouseMove, false);
  10427. BABYLON.Tools.RegisterTopRootEvents([
  10428. { name: "keydown", handler: this._onKeyDown },
  10429. { name: "keyup", handler: this._onKeyUp },
  10430. { name: "blur", handler: this._onLostFocus }
  10431. ]);
  10432. };
  10433. FreeCamera.prototype.detachControl = function (element) {
  10434. if (this._attachedElement != element) {
  10435. return;
  10436. }
  10437. element.removeEventListener("mousedown", this._onMouseDown);
  10438. element.removeEventListener("mouseup", this._onMouseUp);
  10439. element.removeEventListener("mouseout", this._onMouseOut);
  10440. element.removeEventListener("mousemove", this._onMouseMove);
  10441. BABYLON.Tools.UnregisterTopRootEvents([
  10442. { name: "keydown", handler: this._onKeyDown },
  10443. { name: "keyup", handler: this._onKeyUp },
  10444. { name: "blur", handler: this._onLostFocus }
  10445. ]);
  10446. this._attachedElement = null;
  10447. if (this._reset) {
  10448. this._reset();
  10449. }
  10450. };
  10451. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10452. var globalPosition;
  10453. if (this.parent) {
  10454. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10455. }
  10456. else {
  10457. globalPosition = this.position;
  10458. }
  10459. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10460. this._collider.radius = this.ellipsoid;
  10461. //add gravity to the velocity to prevent the dual-collision checking
  10462. if (this.applyGravity) {
  10463. velocity.addInPlace(this.getScene().gravity);
  10464. }
  10465. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, velocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10466. };
  10467. FreeCamera.prototype._checkInputs = function () {
  10468. if (!this._localDirection) {
  10469. this._localDirection = BABYLON.Vector3.Zero();
  10470. this._transformedDirection = BABYLON.Vector3.Zero();
  10471. }
  10472. // Keyboard
  10473. for (var index = 0; index < this._keys.length; index++) {
  10474. var keyCode = this._keys[index];
  10475. var speed = this._computeLocalCameraSpeed();
  10476. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10477. this._localDirection.copyFromFloats(-speed, 0, 0);
  10478. }
  10479. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10480. this._localDirection.copyFromFloats(0, 0, speed);
  10481. }
  10482. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10483. this._localDirection.copyFromFloats(speed, 0, 0);
  10484. }
  10485. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10486. this._localDirection.copyFromFloats(0, 0, -speed);
  10487. }
  10488. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10489. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10490. this.cameraDirection.addInPlace(this._transformedDirection);
  10491. }
  10492. _super.prototype._checkInputs.call(this);
  10493. };
  10494. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10495. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10496. };
  10497. FreeCamera.prototype._updatePosition = function () {
  10498. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10499. this._collideWithWorld(this.cameraDirection);
  10500. }
  10501. else {
  10502. this.position.addInPlace(this.cameraDirection);
  10503. }
  10504. };
  10505. return FreeCamera;
  10506. })(BABYLON.TargetCamera);
  10507. BABYLON.FreeCamera = FreeCamera;
  10508. })(BABYLON || (BABYLON = {}));
  10509. //# sourceMappingURL=babylon.freeCamera.js.map
  10510. var BABYLON;
  10511. (function (BABYLON) {
  10512. var FollowCamera = (function (_super) {
  10513. __extends(FollowCamera, _super);
  10514. function FollowCamera(name, position, scene) {
  10515. _super.call(this, name, position, scene);
  10516. this.radius = 12;
  10517. this.rotationOffset = 0;
  10518. this.heightOffset = 4;
  10519. this.cameraAcceleration = 0.05;
  10520. this.maxCameraSpeed = 20;
  10521. }
  10522. FollowCamera.prototype.getRadians = function (degrees) {
  10523. return degrees * Math.PI / 180;
  10524. };
  10525. FollowCamera.prototype.follow = function (cameraTarget) {
  10526. if (!cameraTarget)
  10527. return;
  10528. var yRotation;
  10529. if (cameraTarget.rotationQuaternion) {
  10530. var rotMatrix = new BABYLON.Matrix();
  10531. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10532. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10533. }
  10534. else {
  10535. yRotation = cameraTarget.rotation.y;
  10536. }
  10537. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10538. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10539. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10540. var dx = targetX - this.position.x;
  10541. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10542. var dz = (targetZ) - this.position.z;
  10543. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10544. var vy = dy * this.cameraAcceleration;
  10545. var vz = dz * this.cameraAcceleration * 2;
  10546. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10547. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10548. }
  10549. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10550. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10551. }
  10552. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10553. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10554. }
  10555. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10556. this.setTarget(cameraTarget.position);
  10557. };
  10558. FollowCamera.prototype._checkInputs = function () {
  10559. _super.prototype._checkInputs.call(this);
  10560. this.follow(this.target);
  10561. };
  10562. return FollowCamera;
  10563. })(BABYLON.TargetCamera);
  10564. BABYLON.FollowCamera = FollowCamera;
  10565. })(BABYLON || (BABYLON = {}));
  10566. //# sourceMappingURL=babylon.followCamera.js.map
  10567. var BABYLON;
  10568. (function (BABYLON) {
  10569. // We're mainly based on the logic defined into the FreeCamera code
  10570. var TouchCamera = (function (_super) {
  10571. __extends(TouchCamera, _super);
  10572. function TouchCamera(name, position, scene) {
  10573. _super.call(this, name, position, scene);
  10574. this._offsetX = null;
  10575. this._offsetY = null;
  10576. this._pointerCount = 0;
  10577. this._pointerPressed = [];
  10578. this.angularSensibility = 200000.0;
  10579. this.moveSensibility = 500.0;
  10580. }
  10581. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10582. var _this = this;
  10583. var previousPosition;
  10584. if (this._attachedCanvas) {
  10585. return;
  10586. }
  10587. this._attachedCanvas = canvas;
  10588. if (this._onPointerDown === undefined) {
  10589. this._onPointerDown = function (evt) {
  10590. if (!noPreventDefault) {
  10591. evt.preventDefault();
  10592. }
  10593. _this._pointerPressed.push(evt.pointerId);
  10594. if (_this._pointerPressed.length !== 1) {
  10595. return;
  10596. }
  10597. previousPosition = {
  10598. x: evt.clientX,
  10599. y: evt.clientY
  10600. };
  10601. };
  10602. this._onPointerUp = function (evt) {
  10603. if (!noPreventDefault) {
  10604. evt.preventDefault();
  10605. }
  10606. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10607. if (index === -1) {
  10608. return;
  10609. }
  10610. _this._pointerPressed.splice(index, 1);
  10611. if (index != 0) {
  10612. return;
  10613. }
  10614. previousPosition = null;
  10615. _this._offsetX = null;
  10616. _this._offsetY = null;
  10617. };
  10618. this._onPointerMove = function (evt) {
  10619. if (!noPreventDefault) {
  10620. evt.preventDefault();
  10621. }
  10622. if (!previousPosition) {
  10623. return;
  10624. }
  10625. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10626. if (index != 0) {
  10627. return;
  10628. }
  10629. _this._offsetX = evt.clientX - previousPosition.x;
  10630. _this._offsetY = -(evt.clientY - previousPosition.y);
  10631. };
  10632. this._onLostFocus = function () {
  10633. _this._offsetX = null;
  10634. _this._offsetY = null;
  10635. };
  10636. }
  10637. canvas.addEventListener("pointerdown", this._onPointerDown);
  10638. canvas.addEventListener("pointerup", this._onPointerUp);
  10639. canvas.addEventListener("pointerout", this._onPointerUp);
  10640. canvas.addEventListener("pointermove", this._onPointerMove);
  10641. BABYLON.Tools.RegisterTopRootEvents([
  10642. { name: "blur", handler: this._onLostFocus }
  10643. ]);
  10644. };
  10645. TouchCamera.prototype.detachControl = function (canvas) {
  10646. if (this._attachedCanvas != canvas) {
  10647. return;
  10648. }
  10649. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10650. canvas.removeEventListener("pointerup", this._onPointerUp);
  10651. canvas.removeEventListener("pointerout", this._onPointerUp);
  10652. canvas.removeEventListener("pointermove", this._onPointerMove);
  10653. BABYLON.Tools.UnregisterTopRootEvents([
  10654. { name: "blur", handler: this._onLostFocus }
  10655. ]);
  10656. this._attachedCanvas = null;
  10657. };
  10658. TouchCamera.prototype._checkInputs = function () {
  10659. if (!this._offsetX) {
  10660. return;
  10661. }
  10662. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  10663. if (this._pointerPressed.length > 1) {
  10664. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  10665. }
  10666. else {
  10667. var speed = this._computeLocalCameraSpeed();
  10668. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10669. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10670. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10671. }
  10672. _super.prototype._checkInputs.call(this);
  10673. };
  10674. return TouchCamera;
  10675. })(BABYLON.FreeCamera);
  10676. BABYLON.TouchCamera = TouchCamera;
  10677. })(BABYLON || (BABYLON = {}));
  10678. //# sourceMappingURL=babylon.touchCamera.js.map
  10679. var BABYLON;
  10680. (function (BABYLON) {
  10681. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  10682. var ArcRotateCamera = (function (_super) {
  10683. __extends(ArcRotateCamera, _super);
  10684. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  10685. var _this = this;
  10686. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10687. this.alpha = alpha;
  10688. this.beta = beta;
  10689. this.radius = radius;
  10690. this.target = target;
  10691. this.inertialAlphaOffset = 0;
  10692. this.inertialBetaOffset = 0;
  10693. this.inertialRadiusOffset = 0;
  10694. this.lowerAlphaLimit = null;
  10695. this.upperAlphaLimit = null;
  10696. this.lowerBetaLimit = 0.01;
  10697. this.upperBetaLimit = Math.PI;
  10698. this.lowerRadiusLimit = null;
  10699. this.upperRadiusLimit = null;
  10700. this.angularSensibility = 1000.0;
  10701. this.wheelPrecision = 3.0;
  10702. this.pinchPrecision = 2.0;
  10703. this.keysUp = [38];
  10704. this.keysDown = [40];
  10705. this.keysLeft = [37];
  10706. this.keysRight = [39];
  10707. this.zoomOnFactor = 1;
  10708. this.targetScreenOffset = BABYLON.Vector2.Zero();
  10709. this.pinchInwards = true;
  10710. this.allowUpsideDown = true;
  10711. this._keys = [];
  10712. this._viewMatrix = new BABYLON.Matrix();
  10713. this.checkCollisions = false;
  10714. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  10715. this._collider = new BABYLON.Collider();
  10716. this._previousPosition = BABYLON.Vector3.Zero();
  10717. this._collisionVelocity = BABYLON.Vector3.Zero();
  10718. this._newPosition = BABYLON.Vector3.Zero();
  10719. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10720. if (collidedMesh === void 0) { collidedMesh = null; }
  10721. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  10722. newPosition.multiplyInPlace(_this._collider.radius);
  10723. }
  10724. if (!collidedMesh) {
  10725. _this._previousPosition.copyFrom(_this.position);
  10726. }
  10727. else {
  10728. _this.setPosition(_this.position);
  10729. if (_this.onCollide) {
  10730. _this.onCollide(collidedMesh);
  10731. }
  10732. }
  10733. // Recompute because of constraints
  10734. var cosa = Math.cos(_this.alpha);
  10735. var sina = Math.sin(_this.alpha);
  10736. var cosb = Math.cos(_this.beta);
  10737. var sinb = Math.sin(_this.beta);
  10738. var target = _this._getTargetPosition();
  10739. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  10740. _this.position.copyFrom(_this._newPosition);
  10741. var up = _this.upVector;
  10742. if (_this.allowUpsideDown && _this.beta < 0) {
  10743. var up = up.clone();
  10744. up = up.negate();
  10745. }
  10746. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  10747. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  10748. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  10749. _this._collisionTriggered = false;
  10750. };
  10751. if (!this.target) {
  10752. this.target = BABYLON.Vector3.Zero();
  10753. }
  10754. this.getViewMatrix();
  10755. }
  10756. ArcRotateCamera.prototype._getTargetPosition = function () {
  10757. return this.target.position || this.target;
  10758. };
  10759. // Cache
  10760. ArcRotateCamera.prototype._initCache = function () {
  10761. _super.prototype._initCache.call(this);
  10762. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10763. this._cache.alpha = undefined;
  10764. this._cache.beta = undefined;
  10765. this._cache.radius = undefined;
  10766. this._cache.targetScreenOffset = undefined;
  10767. };
  10768. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  10769. if (!ignoreParentClass) {
  10770. _super.prototype._updateCache.call(this);
  10771. }
  10772. this._cache.target.copyFrom(this._getTargetPosition());
  10773. this._cache.alpha = this.alpha;
  10774. this._cache.beta = this.beta;
  10775. this._cache.radius = this.radius;
  10776. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  10777. };
  10778. // Synchronized
  10779. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  10780. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  10781. return false;
  10782. return this._cache.target.equals(this._getTargetPosition())
  10783. && this._cache.alpha === this.alpha
  10784. && this._cache.beta === this.beta
  10785. && this._cache.radius === this.radius
  10786. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  10787. };
  10788. // Methods
  10789. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  10790. var _this = this;
  10791. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  10792. var previousPinchDistance = 0;
  10793. var pointers = new BABYLON.SmartCollection();
  10794. if (this._attachedElement) {
  10795. return;
  10796. }
  10797. this._attachedElement = element;
  10798. var engine = this.getEngine();
  10799. if (this._onPointerDown === undefined) {
  10800. this._onPointerDown = function (evt) {
  10801. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  10802. cacheSoloPointer = pointers.item(evt.pointerId);
  10803. if (!noPreventDefault) {
  10804. evt.preventDefault();
  10805. }
  10806. };
  10807. this._onPointerUp = function (evt) {
  10808. cacheSoloPointer = null;
  10809. previousPinchDistance = 0;
  10810. pointers.remove(evt.pointerId);
  10811. if (!noPreventDefault) {
  10812. evt.preventDefault();
  10813. }
  10814. };
  10815. this._onPointerMove = function (evt) {
  10816. if (!noPreventDefault) {
  10817. evt.preventDefault();
  10818. }
  10819. switch (pointers.count) {
  10820. case 1:
  10821. var offsetX = evt.clientX - cacheSoloPointer.x;
  10822. var offsetY = evt.clientY - cacheSoloPointer.y;
  10823. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  10824. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  10825. cacheSoloPointer.x = evt.clientX;
  10826. cacheSoloPointer.y = evt.clientY;
  10827. break;
  10828. case 2:
  10829. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  10830. pointers.item(evt.pointerId).x = evt.clientX;
  10831. pointers.item(evt.pointerId).y = evt.clientY;
  10832. var direction = _this.pinchInwards ? 1 : -1;
  10833. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  10834. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  10835. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  10836. if (previousPinchDistance === 0) {
  10837. previousPinchDistance = pinchSquaredDistance;
  10838. return;
  10839. }
  10840. if (pinchSquaredDistance !== previousPinchDistance) {
  10841. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * _this.angularSensibility * direction);
  10842. previousPinchDistance = pinchSquaredDistance;
  10843. }
  10844. break;
  10845. default:
  10846. if (pointers.item(evt.pointerId)) {
  10847. pointers.item(evt.pointerId).x = evt.clientX;
  10848. pointers.item(evt.pointerId).y = evt.clientY;
  10849. }
  10850. }
  10851. };
  10852. this._onMouseMove = function (evt) {
  10853. if (!engine.isPointerLock) {
  10854. return;
  10855. }
  10856. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10857. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10858. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  10859. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  10860. if (!noPreventDefault) {
  10861. evt.preventDefault();
  10862. }
  10863. };
  10864. this._wheel = function (event) {
  10865. var delta = 0;
  10866. if (event.wheelDelta) {
  10867. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  10868. }
  10869. else if (event.detail) {
  10870. delta = -event.detail / _this.wheelPrecision;
  10871. }
  10872. if (delta)
  10873. _this.inertialRadiusOffset += delta;
  10874. if (event.preventDefault) {
  10875. if (!noPreventDefault) {
  10876. event.preventDefault();
  10877. }
  10878. }
  10879. };
  10880. this._onKeyDown = function (evt) {
  10881. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10882. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10883. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10884. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10885. var index = _this._keys.indexOf(evt.keyCode);
  10886. if (index === -1) {
  10887. _this._keys.push(evt.keyCode);
  10888. }
  10889. if (evt.preventDefault) {
  10890. if (!noPreventDefault) {
  10891. evt.preventDefault();
  10892. }
  10893. }
  10894. }
  10895. };
  10896. this._onKeyUp = function (evt) {
  10897. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10898. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10899. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10900. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10901. var index = _this._keys.indexOf(evt.keyCode);
  10902. if (index >= 0) {
  10903. _this._keys.splice(index, 1);
  10904. }
  10905. if (evt.preventDefault) {
  10906. if (!noPreventDefault) {
  10907. evt.preventDefault();
  10908. }
  10909. }
  10910. }
  10911. };
  10912. this._onLostFocus = function () {
  10913. _this._keys = [];
  10914. pointers.empty();
  10915. previousPinchDistance = 0;
  10916. cacheSoloPointer = null;
  10917. };
  10918. this._onGestureStart = function (e) {
  10919. if (window.MSGesture === undefined) {
  10920. return;
  10921. }
  10922. if (!_this._MSGestureHandler) {
  10923. _this._MSGestureHandler = new MSGesture();
  10924. _this._MSGestureHandler.target = element;
  10925. }
  10926. _this._MSGestureHandler.addPointer(e.pointerId);
  10927. };
  10928. this._onGesture = function (e) {
  10929. _this.radius *= e.scale;
  10930. if (e.preventDefault) {
  10931. if (!noPreventDefault) {
  10932. e.stopPropagation();
  10933. e.preventDefault();
  10934. }
  10935. }
  10936. };
  10937. this._reset = function () {
  10938. _this._keys = [];
  10939. _this.inertialAlphaOffset = 0;
  10940. _this.inertialBetaOffset = 0;
  10941. _this.inertialRadiusOffset = 0;
  10942. pointers.empty();
  10943. previousPinchDistance = 0;
  10944. cacheSoloPointer = null;
  10945. };
  10946. }
  10947. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  10948. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  10949. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  10950. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  10951. element.addEventListener("mousemove", this._onMouseMove, false);
  10952. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  10953. element.addEventListener("MSGestureChange", this._onGesture, false);
  10954. element.addEventListener('mousewheel', this._wheel, false);
  10955. element.addEventListener('DOMMouseScroll', this._wheel, false);
  10956. BABYLON.Tools.RegisterTopRootEvents([
  10957. { name: "keydown", handler: this._onKeyDown },
  10958. { name: "keyup", handler: this._onKeyUp },
  10959. { name: "blur", handler: this._onLostFocus }
  10960. ]);
  10961. };
  10962. ArcRotateCamera.prototype.detachControl = function (element) {
  10963. if (this._attachedElement !== element) {
  10964. return;
  10965. }
  10966. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  10967. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  10968. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  10969. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  10970. element.removeEventListener("mousemove", this._onMouseMove);
  10971. element.removeEventListener("MSPointerDown", this._onGestureStart);
  10972. element.removeEventListener("MSGestureChange", this._onGesture);
  10973. element.removeEventListener('mousewheel', this._wheel);
  10974. element.removeEventListener('DOMMouseScroll', this._wheel);
  10975. BABYLON.Tools.UnregisterTopRootEvents([
  10976. { name: "keydown", handler: this._onKeyDown },
  10977. { name: "keyup", handler: this._onKeyUp },
  10978. { name: "blur", handler: this._onLostFocus }
  10979. ]);
  10980. this._MSGestureHandler = null;
  10981. this._attachedElement = null;
  10982. if (this._reset) {
  10983. this._reset();
  10984. }
  10985. };
  10986. ArcRotateCamera.prototype._checkInputs = function () {
  10987. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  10988. if (this._collisionTriggered) {
  10989. return;
  10990. }
  10991. // Keyboard
  10992. for (var index = 0; index < this._keys.length; index++) {
  10993. var keyCode = this._keys[index];
  10994. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10995. this.inertialAlphaOffset -= 0.01;
  10996. }
  10997. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10998. this.inertialBetaOffset -= 0.01;
  10999. }
  11000. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11001. this.inertialAlphaOffset += 0.01;
  11002. }
  11003. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11004. this.inertialBetaOffset += 0.01;
  11005. }
  11006. }
  11007. // Inertia
  11008. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  11009. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11010. this.beta += this.inertialBetaOffset;
  11011. this.radius -= this.inertialRadiusOffset;
  11012. this.inertialAlphaOffset *= this.inertia;
  11013. this.inertialBetaOffset *= this.inertia;
  11014. this.inertialRadiusOffset *= this.inertia;
  11015. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11016. this.inertialAlphaOffset = 0;
  11017. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11018. this.inertialBetaOffset = 0;
  11019. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11020. this.inertialRadiusOffset = 0;
  11021. }
  11022. // Limits
  11023. this._checkLimits();
  11024. _super.prototype._checkInputs.call(this);
  11025. };
  11026. ArcRotateCamera.prototype._checkLimits = function () {
  11027. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11028. if (this.allowUpsideDown && this.beta > Math.PI) {
  11029. this.beta = this.beta - (2 * Math.PI);
  11030. }
  11031. }
  11032. else {
  11033. if (this.beta < this.lowerBetaLimit) {
  11034. this.beta = this.lowerBetaLimit;
  11035. }
  11036. }
  11037. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11038. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11039. this.beta = this.beta + (2 * Math.PI);
  11040. }
  11041. }
  11042. else {
  11043. if (this.beta > this.upperBetaLimit) {
  11044. this.beta = this.upperBetaLimit;
  11045. }
  11046. }
  11047. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11048. this.alpha = this.lowerAlphaLimit;
  11049. }
  11050. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11051. this.alpha = this.upperAlphaLimit;
  11052. }
  11053. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11054. this.radius = this.lowerRadiusLimit;
  11055. }
  11056. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11057. this.radius = this.upperRadiusLimit;
  11058. }
  11059. };
  11060. ArcRotateCamera.prototype.setPosition = function (position) {
  11061. var radiusv3 = position.subtract(this._getTargetPosition());
  11062. this.radius = radiusv3.length();
  11063. // Alpha
  11064. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11065. if (radiusv3.z < 0) {
  11066. this.alpha = 2 * Math.PI - this.alpha;
  11067. }
  11068. // Beta
  11069. this.beta = Math.acos(radiusv3.y / this.radius);
  11070. this._checkLimits();
  11071. };
  11072. ArcRotateCamera.prototype._getViewMatrix = function () {
  11073. // Compute
  11074. var cosa = Math.cos(this.alpha);
  11075. var sina = Math.sin(this.alpha);
  11076. var cosb = Math.cos(this.beta);
  11077. var sinb = Math.sin(this.beta);
  11078. var target = this._getTargetPosition();
  11079. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11080. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11081. this._collider.radius = this.collisionRadius;
  11082. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11083. this._collisionTriggered = true;
  11084. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11085. }
  11086. else {
  11087. this.position.copyFrom(this._newPosition);
  11088. var up = this.upVector;
  11089. if (this.allowUpsideDown && this.beta < 0) {
  11090. var up = up.clone();
  11091. up = up.negate();
  11092. }
  11093. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11094. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11095. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11096. }
  11097. return this._viewMatrix;
  11098. };
  11099. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  11100. meshes = meshes || this.getScene().meshes;
  11101. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11102. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11103. this.radius = distance * this.zoomOnFactor;
  11104. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  11105. };
  11106. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  11107. var meshesOrMinMaxVector;
  11108. var distance;
  11109. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11110. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11111. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11112. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11113. }
  11114. else {
  11115. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11116. distance = meshesOrMinMaxVectorAndDistance.distance;
  11117. }
  11118. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11119. this.maxZ = distance * 2;
  11120. };
  11121. /**
  11122. * @override
  11123. * needs to be overridden, so sub has required properties to be copied
  11124. */
  11125. ArcRotateCamera.prototype.getSubCamera = function (name, isA) {
  11126. var alphaSpace = this._subCamHalfSpace * (isA ? -1 : 1);
  11127. return new ArcRotateCamera(name, this.alpha + alphaSpace, this.beta, this.radius, this.target, this.getScene());
  11128. };
  11129. /**
  11130. * @override
  11131. * needs to be overridden, adding copy of alpha, beta & radius
  11132. */
  11133. ArcRotateCamera.prototype._updateSubCameras = function () {
  11134. var camA = this.subCameras[BABYLON.Camera.SUB_CAMERAID_A];
  11135. var camB = this.subCameras[BABYLON.Camera.SUB_CAMERAID_B];
  11136. camA.alpha = this.alpha - this._subCamHalfSpace;
  11137. camB.alpha = this.alpha + this._subCamHalfSpace;
  11138. camA.beta = camB.beta = this.beta;
  11139. camA.radius = camB.radius = this.radius;
  11140. _super.prototype._updateSubCameras.call(this);
  11141. };
  11142. return ArcRotateCamera;
  11143. })(BABYLON.Camera);
  11144. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11145. })(BABYLON || (BABYLON = {}));
  11146. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  11147. var BABYLON;
  11148. (function (BABYLON) {
  11149. // We're mainly based on the logic defined into the FreeCamera code
  11150. var DeviceOrientationCamera = (function (_super) {
  11151. __extends(DeviceOrientationCamera, _super);
  11152. function DeviceOrientationCamera(name, position, scene) {
  11153. var _this = this;
  11154. _super.call(this, name, position, scene);
  11155. this._offsetX = null;
  11156. this._offsetY = null;
  11157. this._orientationGamma = 0;
  11158. this._orientationBeta = 0;
  11159. this._initialOrientationGamma = 0;
  11160. this._initialOrientationBeta = 0;
  11161. this.angularSensibility = 10000.0;
  11162. this.moveSensibility = 50.0;
  11163. window.addEventListener("resize", function () {
  11164. _this._initialOrientationGamma = null;
  11165. }, false);
  11166. }
  11167. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11168. var _this = this;
  11169. if (this._attachedCanvas) {
  11170. return;
  11171. }
  11172. this._attachedCanvas = canvas;
  11173. if (!this._orientationChanged) {
  11174. this._orientationChanged = function (evt) {
  11175. if (!_this._initialOrientationGamma) {
  11176. _this._initialOrientationGamma = evt.gamma;
  11177. _this._initialOrientationBeta = evt.beta;
  11178. }
  11179. _this._orientationGamma = evt.gamma;
  11180. _this._orientationBeta = evt.beta;
  11181. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  11182. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  11183. };
  11184. }
  11185. window.addEventListener("deviceorientation", this._orientationChanged);
  11186. };
  11187. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  11188. if (this._attachedCanvas != canvas) {
  11189. return;
  11190. }
  11191. window.removeEventListener("deviceorientation", this._orientationChanged);
  11192. this._attachedCanvas = null;
  11193. this._orientationGamma = 0;
  11194. this._orientationBeta = 0;
  11195. this._initialOrientationGamma = 0;
  11196. this._initialOrientationBeta = 0;
  11197. };
  11198. DeviceOrientationCamera.prototype._checkInputs = function () {
  11199. if (!this._offsetX) {
  11200. return;
  11201. }
  11202. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11203. var speed = this._computeLocalCameraSpeed();
  11204. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11205. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11206. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11207. _super.prototype._checkInputs.call(this);
  11208. };
  11209. return DeviceOrientationCamera;
  11210. })(BABYLON.FreeCamera);
  11211. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  11212. })(BABYLON || (BABYLON = {}));
  11213. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  11214. var BABYLON;
  11215. (function (BABYLON) {
  11216. var Gamepads = (function () {
  11217. function Gamepads(ongamedpadconnected) {
  11218. var _this = this;
  11219. this.babylonGamepads = [];
  11220. this.oneGamepadConnected = false;
  11221. this.isMonitoring = false;
  11222. this.gamepadEventSupported = 'GamepadEvent' in window;
  11223. this.gamepadSupportAvailable = (navigator.getGamepads ||
  11224. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  11225. 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=";
  11226. this._callbackGamepadConnected = ongamedpadconnected;
  11227. if (this.gamepadSupportAvailable) {
  11228. // Checking if the gamepad connected event is supported (like in Firefox)
  11229. if (this.gamepadEventSupported) {
  11230. window.addEventListener('gamepadconnected', function (evt) {
  11231. _this._onGamepadConnected(evt);
  11232. }, false);
  11233. window.addEventListener('gamepaddisconnected', function (evt) {
  11234. _this._onGamepadDisconnected(evt);
  11235. }, false);
  11236. }
  11237. else {
  11238. this._startMonitoringGamepads();
  11239. }
  11240. if (!this.oneGamepadConnected) {
  11241. this._insertGamepadDOMInstructions();
  11242. }
  11243. }
  11244. else {
  11245. this._insertGamepadDOMNotSupported();
  11246. }
  11247. }
  11248. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  11249. Gamepads.gamepadDOMInfo = document.createElement("div");
  11250. var buttonAImage = document.createElement("img");
  11251. buttonAImage.src = this.buttonADataURL;
  11252. var spanMessage = document.createElement("span");
  11253. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  11254. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  11255. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11256. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11257. Gamepads.gamepadDOMInfo.style.width = "100%";
  11258. Gamepads.gamepadDOMInfo.style.height = "48px";
  11259. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11260. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11261. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11262. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11263. buttonAImage.style.position = "relative";
  11264. buttonAImage.style.bottom = "8px";
  11265. spanMessage.style.position = "relative";
  11266. spanMessage.style.fontSize = "32px";
  11267. spanMessage.style.bottom = "32px";
  11268. spanMessage.style.color = "green";
  11269. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11270. };
  11271. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  11272. Gamepads.gamepadDOMInfo = document.createElement("div");
  11273. var spanMessage = document.createElement("span");
  11274. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  11275. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11276. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11277. Gamepads.gamepadDOMInfo.style.width = "100%";
  11278. Gamepads.gamepadDOMInfo.style.height = "40px";
  11279. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11280. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11281. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11282. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11283. spanMessage.style.position = "relative";
  11284. spanMessage.style.fontSize = "32px";
  11285. spanMessage.style.color = "red";
  11286. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11287. };
  11288. Gamepads.prototype.dispose = function () {
  11289. if (Gamepads.gamepadDOMInfo) {
  11290. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11291. }
  11292. };
  11293. Gamepads.prototype._onGamepadConnected = function (evt) {
  11294. var newGamepad = this._addNewGamepad(evt.gamepad);
  11295. if (this._callbackGamepadConnected)
  11296. this._callbackGamepadConnected(newGamepad);
  11297. this._startMonitoringGamepads();
  11298. };
  11299. Gamepads.prototype._addNewGamepad = function (gamepad) {
  11300. if (!this.oneGamepadConnected) {
  11301. this.oneGamepadConnected = true;
  11302. if (Gamepads.gamepadDOMInfo) {
  11303. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11304. Gamepads.gamepadDOMInfo = null;
  11305. }
  11306. }
  11307. var newGamepad;
  11308. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  11309. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  11310. }
  11311. else {
  11312. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  11313. }
  11314. this.babylonGamepads.push(newGamepad);
  11315. return newGamepad;
  11316. };
  11317. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  11318. // Remove the gamepad from the list of gamepads to monitor.
  11319. for (var i in this.babylonGamepads) {
  11320. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  11321. this.babylonGamepads.splice(i, 1);
  11322. break;
  11323. }
  11324. }
  11325. // If no gamepads are left, stop the polling loop.
  11326. if (this.babylonGamepads.length == 0) {
  11327. this._stopMonitoringGamepads();
  11328. }
  11329. };
  11330. Gamepads.prototype._startMonitoringGamepads = function () {
  11331. if (!this.isMonitoring) {
  11332. this.isMonitoring = true;
  11333. this._checkGamepadsStatus();
  11334. }
  11335. };
  11336. Gamepads.prototype._stopMonitoringGamepads = function () {
  11337. this.isMonitoring = false;
  11338. };
  11339. Gamepads.prototype._checkGamepadsStatus = function () {
  11340. var _this = this;
  11341. // updating gamepad objects
  11342. this._updateGamepadObjects();
  11343. for (var i in this.babylonGamepads) {
  11344. this.babylonGamepads[i].update();
  11345. }
  11346. if (this.isMonitoring) {
  11347. if (window.requestAnimationFrame) {
  11348. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11349. }
  11350. else if (window.mozRequestAnimationFrame) {
  11351. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11352. }
  11353. else if (window.webkitRequestAnimationFrame) {
  11354. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11355. }
  11356. }
  11357. };
  11358. // This function is called only on Chrome, which does not yet support
  11359. // connection/disconnection events, but requires you to monitor
  11360. // an array for changes.
  11361. Gamepads.prototype._updateGamepadObjects = function () {
  11362. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  11363. for (var i = 0; i < gamepads.length; i++) {
  11364. if (gamepads[i]) {
  11365. if (!(gamepads[i].index in this.babylonGamepads)) {
  11366. var newGamepad = this._addNewGamepad(gamepads[i]);
  11367. if (this._callbackGamepadConnected) {
  11368. this._callbackGamepadConnected(newGamepad);
  11369. }
  11370. }
  11371. else {
  11372. this.babylonGamepads[i].browserGamepad = gamepads[i];
  11373. }
  11374. }
  11375. }
  11376. };
  11377. return Gamepads;
  11378. })();
  11379. BABYLON.Gamepads = Gamepads;
  11380. var StickValues = (function () {
  11381. function StickValues(x, y) {
  11382. this.x = x;
  11383. this.y = y;
  11384. }
  11385. return StickValues;
  11386. })();
  11387. BABYLON.StickValues = StickValues;
  11388. var Gamepad = (function () {
  11389. function Gamepad(id, index, browserGamepad) {
  11390. this.id = id;
  11391. this.index = index;
  11392. this.browserGamepad = browserGamepad;
  11393. if (this.browserGamepad.axes.length >= 2) {
  11394. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11395. }
  11396. if (this.browserGamepad.axes.length >= 4) {
  11397. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11398. }
  11399. }
  11400. Gamepad.prototype.onleftstickchanged = function (callback) {
  11401. this._onleftstickchanged = callback;
  11402. };
  11403. Gamepad.prototype.onrightstickchanged = function (callback) {
  11404. this._onrightstickchanged = callback;
  11405. };
  11406. Object.defineProperty(Gamepad.prototype, "leftStick", {
  11407. get: function () {
  11408. return this._leftStick;
  11409. },
  11410. set: function (newValues) {
  11411. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  11412. this._onleftstickchanged(newValues);
  11413. }
  11414. this._leftStick = newValues;
  11415. },
  11416. enumerable: true,
  11417. configurable: true
  11418. });
  11419. Object.defineProperty(Gamepad.prototype, "rightStick", {
  11420. get: function () {
  11421. return this._rightStick;
  11422. },
  11423. set: function (newValues) {
  11424. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  11425. this._onrightstickchanged(newValues);
  11426. }
  11427. this._rightStick = newValues;
  11428. },
  11429. enumerable: true,
  11430. configurable: true
  11431. });
  11432. Gamepad.prototype.update = function () {
  11433. if (this._leftStick) {
  11434. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11435. }
  11436. if (this._rightStick) {
  11437. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11438. }
  11439. };
  11440. return Gamepad;
  11441. })();
  11442. BABYLON.Gamepad = Gamepad;
  11443. var GenericPad = (function (_super) {
  11444. __extends(GenericPad, _super);
  11445. function GenericPad(id, index, gamepad) {
  11446. _super.call(this, id, index, gamepad);
  11447. this.id = id;
  11448. this.index = index;
  11449. this.gamepad = gamepad;
  11450. this._buttons = new Array(gamepad.buttons.length);
  11451. }
  11452. GenericPad.prototype.onbuttondown = function (callback) {
  11453. this._onbuttondown = callback;
  11454. };
  11455. GenericPad.prototype.onbuttonup = function (callback) {
  11456. this._onbuttonup = callback;
  11457. };
  11458. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  11459. if (newValue !== currentValue) {
  11460. if (this._onbuttondown && newValue === 1) {
  11461. this._onbuttondown(buttonIndex);
  11462. }
  11463. if (this._onbuttonup && newValue === 0) {
  11464. this._onbuttonup(buttonIndex);
  11465. }
  11466. }
  11467. return newValue;
  11468. };
  11469. GenericPad.prototype.update = function () {
  11470. _super.prototype.update.call(this);
  11471. for (var index = 0; index < this._buttons.length; index++) {
  11472. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  11473. }
  11474. };
  11475. return GenericPad;
  11476. })(Gamepad);
  11477. BABYLON.GenericPad = GenericPad;
  11478. (function (Xbox360Button) {
  11479. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  11480. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  11481. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  11482. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  11483. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  11484. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  11485. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  11486. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  11487. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  11488. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  11489. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  11490. var Xbox360Button = BABYLON.Xbox360Button;
  11491. (function (Xbox360Dpad) {
  11492. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  11493. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  11494. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  11495. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  11496. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  11497. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  11498. var Xbox360Pad = (function (_super) {
  11499. __extends(Xbox360Pad, _super);
  11500. function Xbox360Pad() {
  11501. _super.apply(this, arguments);
  11502. this._leftTrigger = 0;
  11503. this._rightTrigger = 0;
  11504. this._buttonA = 0;
  11505. this._buttonB = 0;
  11506. this._buttonX = 0;
  11507. this._buttonY = 0;
  11508. this._buttonBack = 0;
  11509. this._buttonStart = 0;
  11510. this._buttonLB = 0;
  11511. this._buttonRB = 0;
  11512. this._buttonLeftStick = 0;
  11513. this._buttonRightStick = 0;
  11514. this._dPadUp = 0;
  11515. this._dPadDown = 0;
  11516. this._dPadLeft = 0;
  11517. this._dPadRight = 0;
  11518. }
  11519. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  11520. this._onlefttriggerchanged = callback;
  11521. };
  11522. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  11523. this._onrighttriggerchanged = callback;
  11524. };
  11525. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  11526. get: function () {
  11527. return this._leftTrigger;
  11528. },
  11529. set: function (newValue) {
  11530. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  11531. this._onlefttriggerchanged(newValue);
  11532. }
  11533. this._leftTrigger = newValue;
  11534. },
  11535. enumerable: true,
  11536. configurable: true
  11537. });
  11538. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  11539. get: function () {
  11540. return this._rightTrigger;
  11541. },
  11542. set: function (newValue) {
  11543. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  11544. this._onrighttriggerchanged(newValue);
  11545. }
  11546. this._rightTrigger = newValue;
  11547. },
  11548. enumerable: true,
  11549. configurable: true
  11550. });
  11551. Xbox360Pad.prototype.onbuttondown = function (callback) {
  11552. this._onbuttondown = callback;
  11553. };
  11554. Xbox360Pad.prototype.onbuttonup = function (callback) {
  11555. this._onbuttonup = callback;
  11556. };
  11557. Xbox360Pad.prototype.ondpaddown = function (callback) {
  11558. this._ondpaddown = callback;
  11559. };
  11560. Xbox360Pad.prototype.ondpadup = function (callback) {
  11561. this._ondpadup = callback;
  11562. };
  11563. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  11564. if (newValue !== currentValue) {
  11565. if (this._onbuttondown && newValue === 1) {
  11566. this._onbuttondown(buttonType);
  11567. }
  11568. if (this._onbuttonup && newValue === 0) {
  11569. this._onbuttonup(buttonType);
  11570. }
  11571. }
  11572. return newValue;
  11573. };
  11574. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  11575. if (newValue !== currentValue) {
  11576. if (this._ondpaddown && newValue === 1) {
  11577. this._ondpaddown(buttonType);
  11578. }
  11579. if (this._ondpadup && newValue === 0) {
  11580. this._ondpadup(buttonType);
  11581. }
  11582. }
  11583. return newValue;
  11584. };
  11585. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  11586. get: function () {
  11587. return this._buttonA;
  11588. },
  11589. set: function (value) {
  11590. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  11591. },
  11592. enumerable: true,
  11593. configurable: true
  11594. });
  11595. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  11596. get: function () {
  11597. return this._buttonB;
  11598. },
  11599. set: function (value) {
  11600. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  11601. },
  11602. enumerable: true,
  11603. configurable: true
  11604. });
  11605. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  11606. get: function () {
  11607. return this._buttonX;
  11608. },
  11609. set: function (value) {
  11610. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  11611. },
  11612. enumerable: true,
  11613. configurable: true
  11614. });
  11615. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  11616. get: function () {
  11617. return this._buttonY;
  11618. },
  11619. set: function (value) {
  11620. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  11621. },
  11622. enumerable: true,
  11623. configurable: true
  11624. });
  11625. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  11626. get: function () {
  11627. return this._buttonStart;
  11628. },
  11629. set: function (value) {
  11630. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  11631. },
  11632. enumerable: true,
  11633. configurable: true
  11634. });
  11635. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  11636. get: function () {
  11637. return this._buttonBack;
  11638. },
  11639. set: function (value) {
  11640. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  11641. },
  11642. enumerable: true,
  11643. configurable: true
  11644. });
  11645. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  11646. get: function () {
  11647. return this._buttonLB;
  11648. },
  11649. set: function (value) {
  11650. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  11651. },
  11652. enumerable: true,
  11653. configurable: true
  11654. });
  11655. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  11656. get: function () {
  11657. return this._buttonRB;
  11658. },
  11659. set: function (value) {
  11660. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  11661. },
  11662. enumerable: true,
  11663. configurable: true
  11664. });
  11665. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  11666. get: function () {
  11667. return this._buttonLeftStick;
  11668. },
  11669. set: function (value) {
  11670. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  11671. },
  11672. enumerable: true,
  11673. configurable: true
  11674. });
  11675. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  11676. get: function () {
  11677. return this._buttonRightStick;
  11678. },
  11679. set: function (value) {
  11680. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  11681. },
  11682. enumerable: true,
  11683. configurable: true
  11684. });
  11685. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  11686. get: function () {
  11687. return this._dPadUp;
  11688. },
  11689. set: function (value) {
  11690. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  11691. },
  11692. enumerable: true,
  11693. configurable: true
  11694. });
  11695. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  11696. get: function () {
  11697. return this._dPadDown;
  11698. },
  11699. set: function (value) {
  11700. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  11701. },
  11702. enumerable: true,
  11703. configurable: true
  11704. });
  11705. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  11706. get: function () {
  11707. return this._dPadLeft;
  11708. },
  11709. set: function (value) {
  11710. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  11711. },
  11712. enumerable: true,
  11713. configurable: true
  11714. });
  11715. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  11716. get: function () {
  11717. return this._dPadRight;
  11718. },
  11719. set: function (value) {
  11720. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  11721. },
  11722. enumerable: true,
  11723. configurable: true
  11724. });
  11725. Xbox360Pad.prototype.update = function () {
  11726. _super.prototype.update.call(this);
  11727. this.buttonA = this.browserGamepad.buttons[0].value;
  11728. this.buttonB = this.browserGamepad.buttons[1].value;
  11729. this.buttonX = this.browserGamepad.buttons[2].value;
  11730. this.buttonY = this.browserGamepad.buttons[3].value;
  11731. this.buttonLB = this.browserGamepad.buttons[4].value;
  11732. this.buttonRB = this.browserGamepad.buttons[5].value;
  11733. this.leftTrigger = this.browserGamepad.buttons[6].value;
  11734. this.rightTrigger = this.browserGamepad.buttons[7].value;
  11735. this.buttonBack = this.browserGamepad.buttons[8].value;
  11736. this.buttonStart = this.browserGamepad.buttons[9].value;
  11737. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  11738. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  11739. this.dPadUp = this.browserGamepad.buttons[12].value;
  11740. this.dPadDown = this.browserGamepad.buttons[13].value;
  11741. this.dPadLeft = this.browserGamepad.buttons[14].value;
  11742. this.dPadRight = this.browserGamepad.buttons[15].value;
  11743. };
  11744. return Xbox360Pad;
  11745. })(Gamepad);
  11746. BABYLON.Xbox360Pad = Xbox360Pad;
  11747. })(BABYLON || (BABYLON = {}));
  11748. //# sourceMappingURL=babylon.gamepads.js.map
  11749. var BABYLON;
  11750. (function (BABYLON) {
  11751. // We're mainly based on the logic defined into the FreeCamera code
  11752. var GamepadCamera = (function (_super) {
  11753. __extends(GamepadCamera, _super);
  11754. function GamepadCamera(name, position, scene) {
  11755. var _this = this;
  11756. _super.call(this, name, position, scene);
  11757. this.angularSensibility = 200;
  11758. this.moveSensibility = 75;
  11759. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  11760. }
  11761. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  11762. // Only the first gamepad can control the camera
  11763. if (gamepad.index === 0) {
  11764. this._gamepad = gamepad;
  11765. }
  11766. };
  11767. GamepadCamera.prototype._checkInputs = function () {
  11768. if (this._gamepad) {
  11769. var LSValues = this._gamepad.leftStick;
  11770. var normalizedLX = LSValues.x / this.moveSensibility;
  11771. var normalizedLY = LSValues.y / this.moveSensibility;
  11772. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  11773. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  11774. var RSValues = this._gamepad.rightStick;
  11775. var normalizedRX = RSValues.x / this.angularSensibility;
  11776. var normalizedRY = RSValues.y / this.angularSensibility;
  11777. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  11778. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  11779. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  11780. var speed = this._computeLocalCameraSpeed() * 50.0;
  11781. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  11782. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  11783. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  11784. }
  11785. _super.prototype._checkInputs.call(this);
  11786. };
  11787. GamepadCamera.prototype.dispose = function () {
  11788. this._gamepads.dispose();
  11789. _super.prototype.dispose.call(this);
  11790. };
  11791. return GamepadCamera;
  11792. })(BABYLON.FreeCamera);
  11793. BABYLON.GamepadCamera = GamepadCamera;
  11794. })(BABYLON || (BABYLON = {}));
  11795. //# sourceMappingURL=babylon.gamepadCamera.js.map
  11796. var BABYLON;
  11797. (function (BABYLON) {
  11798. var RenderingManager = (function () {
  11799. function RenderingManager(scene) {
  11800. this._renderingGroups = new Array();
  11801. this._scene = scene;
  11802. }
  11803. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11804. if (this._scene._activeParticleSystems.length === 0) {
  11805. return;
  11806. }
  11807. // Particles
  11808. var beforeParticlesDate = BABYLON.Tools.Now;
  11809. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11810. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11811. if (particleSystem.renderingGroupId !== index) {
  11812. continue;
  11813. }
  11814. this._clearDepthBuffer();
  11815. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11816. this._scene._activeParticles += particleSystem.render();
  11817. }
  11818. }
  11819. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11820. };
  11821. RenderingManager.prototype._renderSprites = function (index) {
  11822. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11823. return;
  11824. }
  11825. // Sprites
  11826. var beforeSpritessDate = BABYLON.Tools.Now;
  11827. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11828. var spriteManager = this._scene.spriteManagers[id];
  11829. if (spriteManager.renderingGroupId === index) {
  11830. this._clearDepthBuffer();
  11831. spriteManager.render();
  11832. }
  11833. }
  11834. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11835. };
  11836. RenderingManager.prototype._clearDepthBuffer = function () {
  11837. if (this._depthBufferAlreadyCleaned) {
  11838. return;
  11839. }
  11840. this._scene.getEngine().clear(0, false, true);
  11841. this._depthBufferAlreadyCleaned = true;
  11842. };
  11843. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11844. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11845. this._depthBufferAlreadyCleaned = false;
  11846. var renderingGroup = this._renderingGroups[index];
  11847. var needToStepBack = false;
  11848. if (renderingGroup) {
  11849. this._clearDepthBuffer();
  11850. if (!renderingGroup.render(customRenderFunction)) {
  11851. this._renderingGroups.splice(index, 1);
  11852. needToStepBack = true;
  11853. }
  11854. }
  11855. if (renderSprites) {
  11856. this._renderSprites(index);
  11857. }
  11858. if (renderParticles) {
  11859. this._renderParticles(index, activeMeshes);
  11860. }
  11861. if (needToStepBack) {
  11862. index--;
  11863. }
  11864. }
  11865. };
  11866. RenderingManager.prototype.reset = function () {
  11867. for (var index in this._renderingGroups) {
  11868. var renderingGroup = this._renderingGroups[index];
  11869. renderingGroup.prepare();
  11870. }
  11871. };
  11872. RenderingManager.prototype.dispatch = function (subMesh) {
  11873. var mesh = subMesh.getMesh();
  11874. var renderingGroupId = mesh.renderingGroupId || 0;
  11875. if (!this._renderingGroups[renderingGroupId]) {
  11876. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11877. }
  11878. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11879. };
  11880. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11881. return RenderingManager;
  11882. })();
  11883. BABYLON.RenderingManager = RenderingManager;
  11884. })(BABYLON || (BABYLON = {}));
  11885. //# sourceMappingURL=babylon.renderingManager.js.map
  11886. var BABYLON;
  11887. (function (BABYLON) {
  11888. var RenderingGroup = (function () {
  11889. function RenderingGroup(index, scene) {
  11890. this.index = index;
  11891. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11892. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11893. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11894. this._scene = scene;
  11895. }
  11896. RenderingGroup.prototype.render = function (customRenderFunction) {
  11897. if (customRenderFunction) {
  11898. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11899. return true;
  11900. }
  11901. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11902. return false;
  11903. }
  11904. var engine = this._scene.getEngine();
  11905. // Opaque
  11906. var subIndex;
  11907. var submesh;
  11908. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11909. submesh = this._opaqueSubMeshes.data[subIndex];
  11910. submesh.render();
  11911. }
  11912. // Alpha test
  11913. engine.setAlphaTesting(true);
  11914. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11915. submesh = this._alphaTestSubMeshes.data[subIndex];
  11916. submesh.render();
  11917. }
  11918. engine.setAlphaTesting(false);
  11919. // Transparent
  11920. if (this._transparentSubMeshes.length) {
  11921. // Sorting
  11922. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11923. submesh = this._transparentSubMeshes.data[subIndex];
  11924. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11925. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  11926. }
  11927. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11928. sortedArray.sort(function (a, b) {
  11929. // Alpha index first
  11930. if (a._alphaIndex > b._alphaIndex) {
  11931. return 1;
  11932. }
  11933. if (a._alphaIndex < b._alphaIndex) {
  11934. return -1;
  11935. }
  11936. // Then distance to camera
  11937. if (a._distanceToCamera < b._distanceToCamera) {
  11938. return 1;
  11939. }
  11940. if (a._distanceToCamera > b._distanceToCamera) {
  11941. return -1;
  11942. }
  11943. return 0;
  11944. });
  11945. // Rendering
  11946. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11947. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11948. submesh = sortedArray[subIndex];
  11949. submesh.render();
  11950. }
  11951. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11952. }
  11953. return true;
  11954. };
  11955. RenderingGroup.prototype.prepare = function () {
  11956. this._opaqueSubMeshes.reset();
  11957. this._transparentSubMeshes.reset();
  11958. this._alphaTestSubMeshes.reset();
  11959. };
  11960. RenderingGroup.prototype.dispatch = function (subMesh) {
  11961. var material = subMesh.getMaterial();
  11962. var mesh = subMesh.getMesh();
  11963. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11964. this._transparentSubMeshes.push(subMesh);
  11965. }
  11966. else if (material.needAlphaTesting()) {
  11967. this._alphaTestSubMeshes.push(subMesh);
  11968. }
  11969. else {
  11970. this._opaqueSubMeshes.push(subMesh); // Opaque
  11971. }
  11972. };
  11973. return RenderingGroup;
  11974. })();
  11975. BABYLON.RenderingGroup = RenderingGroup;
  11976. })(BABYLON || (BABYLON = {}));
  11977. //# sourceMappingURL=babylon.renderingGroup.js.map
  11978. var BABYLON;
  11979. (function (BABYLON) {
  11980. /**
  11981. * Represents a scene to be rendered by the engine.
  11982. * @see http://doc.babylonjs.com/page.php?p=21911
  11983. */
  11984. var Scene = (function () {
  11985. /**
  11986. * @constructor
  11987. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  11988. */
  11989. function Scene(engine) {
  11990. // Members
  11991. this.autoClear = true;
  11992. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  11993. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  11994. this.forceWireframe = false;
  11995. this.forcePointsCloud = false;
  11996. this.forceShowBoundingBoxes = false;
  11997. this.animationsEnabled = true;
  11998. 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
  11999. // Fog
  12000. /**
  12001. * is fog enabled on this scene.
  12002. * @type {boolean}
  12003. */
  12004. this.fogEnabled = true;
  12005. this.fogMode = Scene.FOGMODE_NONE;
  12006. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12007. this.fogDensity = 0.1;
  12008. this.fogStart = 0;
  12009. this.fogEnd = 1000.0;
  12010. // Lights
  12011. /**
  12012. * is shadow enabled on this scene.
  12013. * @type {boolean}
  12014. */
  12015. this.shadowsEnabled = true;
  12016. /**
  12017. * is light enabled on this scene.
  12018. * @type {boolean}
  12019. */
  12020. this.lightsEnabled = true;
  12021. /**
  12022. * All of the lights added to this scene.
  12023. * @see BABYLON.Light
  12024. * @type {BABYLON.Light[]}
  12025. */
  12026. this.lights = new Array();
  12027. // Cameras
  12028. /**
  12029. * All of the cameras added to this scene.
  12030. * @see BABYLON.Camera
  12031. * @type {BABYLON.Camera[]}
  12032. */
  12033. this.cameras = new Array();
  12034. this.activeCameras = new Array();
  12035. // Meshes
  12036. /**
  12037. * All of the (abstract) meshes added to this scene.
  12038. * @see BABYLON.AbstractMesh
  12039. * @type {BABYLON.AbstractMesh[]}
  12040. */
  12041. this.meshes = new Array();
  12042. // Geometries
  12043. this._geometries = new Array();
  12044. this.materials = new Array();
  12045. this.multiMaterials = new Array();
  12046. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12047. // Textures
  12048. this.texturesEnabled = true;
  12049. this.textures = new Array();
  12050. // Particles
  12051. this.particlesEnabled = true;
  12052. this.particleSystems = new Array();
  12053. // Sprites
  12054. this.spritesEnabled = true;
  12055. this.spriteManagers = new Array();
  12056. // Layers
  12057. this.layers = new Array();
  12058. // Skeletons
  12059. this.skeletonsEnabled = true;
  12060. this.skeletons = new Array();
  12061. // Lens flares
  12062. this.lensFlaresEnabled = true;
  12063. this.lensFlareSystems = new Array();
  12064. // Collisions
  12065. this.collisionsEnabled = true;
  12066. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  12067. // Postprocesses
  12068. this.postProcessesEnabled = true;
  12069. // Customs render targets
  12070. this.renderTargetsEnabled = true;
  12071. this.dumpNextRenderTargets = false;
  12072. this.customRenderTargets = new Array();
  12073. // Imported meshes
  12074. this.importedMeshesFiles = new Array();
  12075. this._actionManagers = new Array();
  12076. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12077. // Procedural textures
  12078. this.proceduralTexturesEnabled = true;
  12079. this._proceduralTextures = new Array();
  12080. this.soundTracks = new Array();
  12081. this._audioEnabled = true;
  12082. this._headphone = false;
  12083. this._totalVertices = 0;
  12084. this._activeIndices = 0;
  12085. this._activeParticles = 0;
  12086. this._lastFrameDuration = 0;
  12087. this._evaluateActiveMeshesDuration = 0;
  12088. this._renderTargetsDuration = 0;
  12089. this._particlesDuration = 0;
  12090. this._renderDuration = 0;
  12091. this._spritesDuration = 0;
  12092. this._animationRatio = 0;
  12093. this._renderId = 0;
  12094. this._executeWhenReadyTimeoutId = -1;
  12095. this._toBeDisposed = new BABYLON.SmartArray(256);
  12096. this._onReadyCallbacks = new Array();
  12097. this._pendingData = []; //ANY
  12098. this._onBeforeRenderCallbacks = new Array();
  12099. this._onAfterRenderCallbacks = new Array();
  12100. this._activeMeshes = new BABYLON.SmartArray(256);
  12101. this._processedMaterials = new BABYLON.SmartArray(256);
  12102. this._renderTargets = new BABYLON.SmartArray(256);
  12103. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12104. this._activeSkeletons = new BABYLON.SmartArray(32);
  12105. this._activeBones = 0;
  12106. this._activeAnimatables = new Array();
  12107. this._transformMatrix = BABYLON.Matrix.Zero();
  12108. this._uniqueIdCounter = 0;
  12109. this._engine = engine;
  12110. engine.scenes.push(this);
  12111. this._renderingManager = new BABYLON.RenderingManager(this);
  12112. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12113. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12114. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12115. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12116. this.attachControl();
  12117. this._debugLayer = new BABYLON.DebugLayer(this);
  12118. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12119. //simplification queue
  12120. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12121. //collision coordinator initialization. For now legacy per default.
  12122. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12123. }
  12124. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12125. get: function () {
  12126. return Scene._FOGMODE_NONE;
  12127. },
  12128. enumerable: true,
  12129. configurable: true
  12130. });
  12131. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12132. get: function () {
  12133. return Scene._FOGMODE_EXP;
  12134. },
  12135. enumerable: true,
  12136. configurable: true
  12137. });
  12138. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12139. get: function () {
  12140. return Scene._FOGMODE_EXP2;
  12141. },
  12142. enumerable: true,
  12143. configurable: true
  12144. });
  12145. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12146. get: function () {
  12147. return Scene._FOGMODE_LINEAR;
  12148. },
  12149. enumerable: true,
  12150. configurable: true
  12151. });
  12152. Object.defineProperty(Scene.prototype, "debugLayer", {
  12153. // Properties
  12154. get: function () {
  12155. return this._debugLayer;
  12156. },
  12157. enumerable: true,
  12158. configurable: true
  12159. });
  12160. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12161. get: function () {
  12162. return this._workerCollisions;
  12163. },
  12164. set: function (enabled) {
  12165. enabled = (enabled && !!Worker);
  12166. this._workerCollisions = enabled;
  12167. if (this.collisionCoordinator) {
  12168. this.collisionCoordinator.destroy();
  12169. }
  12170. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12171. this.collisionCoordinator.init(this);
  12172. },
  12173. enumerable: true,
  12174. configurable: true
  12175. });
  12176. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12177. /**
  12178. * The mesh that is currently under the pointer.
  12179. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12180. */
  12181. get: function () {
  12182. return this._meshUnderPointer;
  12183. },
  12184. enumerable: true,
  12185. configurable: true
  12186. });
  12187. Object.defineProperty(Scene.prototype, "pointerX", {
  12188. /**
  12189. * Current on-screen X position of the pointer
  12190. * @return {number} X position of the pointer
  12191. */
  12192. get: function () {
  12193. return this._pointerX;
  12194. },
  12195. enumerable: true,
  12196. configurable: true
  12197. });
  12198. Object.defineProperty(Scene.prototype, "pointerY", {
  12199. /**
  12200. * Current on-screen Y position of the pointer
  12201. * @return {number} Y position of the pointer
  12202. */
  12203. get: function () {
  12204. return this._pointerY;
  12205. },
  12206. enumerable: true,
  12207. configurable: true
  12208. });
  12209. Scene.prototype.getCachedMaterial = function () {
  12210. return this._cachedMaterial;
  12211. };
  12212. Scene.prototype.getBoundingBoxRenderer = function () {
  12213. return this._boundingBoxRenderer;
  12214. };
  12215. Scene.prototype.getOutlineRenderer = function () {
  12216. return this._outlineRenderer;
  12217. };
  12218. Scene.prototype.getEngine = function () {
  12219. return this._engine;
  12220. };
  12221. Scene.prototype.getTotalVertices = function () {
  12222. return this._totalVertices;
  12223. };
  12224. Scene.prototype.getActiveIndices = function () {
  12225. return this._activeIndices;
  12226. };
  12227. Scene.prototype.getActiveParticles = function () {
  12228. return this._activeParticles;
  12229. };
  12230. Scene.prototype.getActiveBones = function () {
  12231. return this._activeBones;
  12232. };
  12233. // Stats
  12234. Scene.prototype.getLastFrameDuration = function () {
  12235. return this._lastFrameDuration;
  12236. };
  12237. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12238. return this._evaluateActiveMeshesDuration;
  12239. };
  12240. Scene.prototype.getActiveMeshes = function () {
  12241. return this._activeMeshes;
  12242. };
  12243. Scene.prototype.getRenderTargetsDuration = function () {
  12244. return this._renderTargetsDuration;
  12245. };
  12246. Scene.prototype.getRenderDuration = function () {
  12247. return this._renderDuration;
  12248. };
  12249. Scene.prototype.getParticlesDuration = function () {
  12250. return this._particlesDuration;
  12251. };
  12252. Scene.prototype.getSpritesDuration = function () {
  12253. return this._spritesDuration;
  12254. };
  12255. Scene.prototype.getAnimationRatio = function () {
  12256. return this._animationRatio;
  12257. };
  12258. Scene.prototype.getRenderId = function () {
  12259. return this._renderId;
  12260. };
  12261. Scene.prototype.incrementRenderId = function () {
  12262. this._renderId++;
  12263. };
  12264. Scene.prototype._updatePointerPosition = function (evt) {
  12265. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12266. this._pointerX = evt.clientX - canvasRect.left;
  12267. this._pointerY = evt.clientY - canvasRect.top;
  12268. if (this.cameraToUseForPointers) {
  12269. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12270. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12271. }
  12272. };
  12273. // Pointers handling
  12274. Scene.prototype.attachControl = function () {
  12275. var _this = this;
  12276. this._onPointerMove = function (evt) {
  12277. var canvas = _this._engine.getRenderingCanvas();
  12278. _this._updatePointerPosition(evt);
  12279. 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);
  12280. if (pickResult.hit) {
  12281. _this._meshUnderPointer = pickResult.pickedMesh;
  12282. _this.setPointerOverMesh(pickResult.pickedMesh);
  12283. canvas.style.cursor = "pointer";
  12284. }
  12285. else {
  12286. _this.setPointerOverMesh(null);
  12287. canvas.style.cursor = "";
  12288. _this._meshUnderPointer = null;
  12289. }
  12290. };
  12291. this._onPointerDown = function (evt) {
  12292. var predicate = null;
  12293. if (!_this.onPointerDown) {
  12294. predicate = function (mesh) {
  12295. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  12296. };
  12297. }
  12298. _this._updatePointerPosition(evt);
  12299. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12300. if (pickResult.hit) {
  12301. if (pickResult.pickedMesh.actionManager) {
  12302. switch (evt.button) {
  12303. case 0:
  12304. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12305. break;
  12306. case 1:
  12307. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12308. break;
  12309. case 2:
  12310. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12311. break;
  12312. }
  12313. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12314. }
  12315. }
  12316. if (_this.onPointerDown) {
  12317. _this.onPointerDown(evt, pickResult);
  12318. }
  12319. };
  12320. this._onPointerUp = function (evt) {
  12321. var predicate = null;
  12322. if (!_this.onPointerUp) {
  12323. predicate = function (mesh) {
  12324. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  12325. };
  12326. }
  12327. _this._updatePointerPosition(evt);
  12328. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12329. if (pickResult.hit) {
  12330. if (pickResult.pickedMesh.actionManager) {
  12331. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12332. }
  12333. }
  12334. if (_this.onPointerUp) {
  12335. _this.onPointerUp(evt, pickResult);
  12336. }
  12337. };
  12338. this._onKeyDown = function (evt) {
  12339. if (_this.actionManager) {
  12340. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12341. }
  12342. };
  12343. this._onKeyUp = function (evt) {
  12344. if (_this.actionManager) {
  12345. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12346. }
  12347. };
  12348. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12349. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12350. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12351. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12352. BABYLON.Tools.RegisterTopRootEvents([
  12353. { name: "keydown", handler: this._onKeyDown },
  12354. { name: "keyup", handler: this._onKeyUp }
  12355. ]);
  12356. };
  12357. Scene.prototype.detachControl = function () {
  12358. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12359. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12360. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12361. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12362. BABYLON.Tools.UnregisterTopRootEvents([
  12363. { name: "keydown", handler: this._onKeyDown },
  12364. { name: "keyup", handler: this._onKeyUp }
  12365. ]);
  12366. };
  12367. // Ready
  12368. Scene.prototype.isReady = function () {
  12369. if (this._pendingData.length > 0) {
  12370. return false;
  12371. }
  12372. for (var index = 0; index < this._geometries.length; index++) {
  12373. var geometry = this._geometries[index];
  12374. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12375. return false;
  12376. }
  12377. }
  12378. for (index = 0; index < this.meshes.length; index++) {
  12379. var mesh = this.meshes[index];
  12380. if (!mesh.isReady()) {
  12381. return false;
  12382. }
  12383. var mat = mesh.material;
  12384. if (mat) {
  12385. if (!mat.isReady(mesh)) {
  12386. return false;
  12387. }
  12388. }
  12389. }
  12390. return true;
  12391. };
  12392. Scene.prototype.resetCachedMaterial = function () {
  12393. this._cachedMaterial = null;
  12394. };
  12395. Scene.prototype.registerBeforeRender = function (func) {
  12396. this._onBeforeRenderCallbacks.push(func);
  12397. };
  12398. Scene.prototype.unregisterBeforeRender = function (func) {
  12399. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12400. if (index > -1) {
  12401. this._onBeforeRenderCallbacks.splice(index, 1);
  12402. }
  12403. };
  12404. Scene.prototype.registerAfterRender = function (func) {
  12405. this._onAfterRenderCallbacks.push(func);
  12406. };
  12407. Scene.prototype.unregisterAfterRender = function (func) {
  12408. var index = this._onAfterRenderCallbacks.indexOf(func);
  12409. if (index > -1) {
  12410. this._onAfterRenderCallbacks.splice(index, 1);
  12411. }
  12412. };
  12413. Scene.prototype._addPendingData = function (data) {
  12414. this._pendingData.push(data);
  12415. };
  12416. Scene.prototype._removePendingData = function (data) {
  12417. var index = this._pendingData.indexOf(data);
  12418. if (index !== -1) {
  12419. this._pendingData.splice(index, 1);
  12420. }
  12421. };
  12422. Scene.prototype.getWaitingItemsCount = function () {
  12423. return this._pendingData.length;
  12424. };
  12425. /**
  12426. * Registers a function to be executed when the scene is ready.
  12427. * @param {Function} func - the function to be executed.
  12428. */
  12429. Scene.prototype.executeWhenReady = function (func) {
  12430. var _this = this;
  12431. this._onReadyCallbacks.push(func);
  12432. if (this._executeWhenReadyTimeoutId !== -1) {
  12433. return;
  12434. }
  12435. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12436. _this._checkIsReady();
  12437. }, 150);
  12438. };
  12439. Scene.prototype._checkIsReady = function () {
  12440. var _this = this;
  12441. if (this.isReady()) {
  12442. this._onReadyCallbacks.forEach(function (func) {
  12443. func();
  12444. });
  12445. this._onReadyCallbacks = [];
  12446. this._executeWhenReadyTimeoutId = -1;
  12447. return;
  12448. }
  12449. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12450. _this._checkIsReady();
  12451. }, 150);
  12452. };
  12453. // Animations
  12454. /**
  12455. * Will start the animation sequence of a given target
  12456. * @param target - the target
  12457. * @param {number} from - from which frame should animation start
  12458. * @param {number} to - till which frame should animation run.
  12459. * @param {boolean} [loop] - should the animation loop
  12460. * @param {number} [speedRatio] - the speed in which to run the animation
  12461. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12462. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12463. * @return {BABYLON.Animatable} the animatable object created for this animation
  12464. * @see BABYLON.Animatable
  12465. * @see http://doc.babylonjs.com/page.php?p=22081
  12466. */
  12467. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12468. if (speedRatio === undefined) {
  12469. speedRatio = 1.0;
  12470. }
  12471. this.stopAnimation(target);
  12472. if (!animatable) {
  12473. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12474. }
  12475. // Local animations
  12476. if (target.animations) {
  12477. animatable.appendAnimations(target, target.animations);
  12478. }
  12479. // Children animations
  12480. if (target.getAnimatables) {
  12481. var animatables = target.getAnimatables();
  12482. for (var index = 0; index < animatables.length; index++) {
  12483. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12484. }
  12485. }
  12486. return animatable;
  12487. };
  12488. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12489. if (speedRatio === undefined) {
  12490. speedRatio = 1.0;
  12491. }
  12492. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12493. return animatable;
  12494. };
  12495. Scene.prototype.getAnimatableByTarget = function (target) {
  12496. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12497. if (this._activeAnimatables[index].target === target) {
  12498. return this._activeAnimatables[index];
  12499. }
  12500. }
  12501. return null;
  12502. };
  12503. /**
  12504. * Will stop the animation of the given target
  12505. * @param target - the target
  12506. * @see beginAnimation
  12507. */
  12508. Scene.prototype.stopAnimation = function (target) {
  12509. var animatable = this.getAnimatableByTarget(target);
  12510. if (animatable) {
  12511. animatable.stop();
  12512. }
  12513. };
  12514. Scene.prototype._animate = function () {
  12515. if (!this.animationsEnabled) {
  12516. return;
  12517. }
  12518. if (!this._animationStartDate) {
  12519. this._animationStartDate = BABYLON.Tools.Now;
  12520. }
  12521. // Getting time
  12522. var now = BABYLON.Tools.Now;
  12523. var delay = now - this._animationStartDate;
  12524. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12525. this._activeAnimatables[index]._animate(delay);
  12526. }
  12527. };
  12528. // Matrix
  12529. Scene.prototype.getViewMatrix = function () {
  12530. return this._viewMatrix;
  12531. };
  12532. Scene.prototype.getProjectionMatrix = function () {
  12533. return this._projectionMatrix;
  12534. };
  12535. Scene.prototype.getTransformMatrix = function () {
  12536. return this._transformMatrix;
  12537. };
  12538. Scene.prototype.setTransformMatrix = function (view, projection) {
  12539. this._viewMatrix = view;
  12540. this._projectionMatrix = projection;
  12541. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12542. };
  12543. // Methods
  12544. Scene.prototype.addMesh = function (newMesh) {
  12545. newMesh.uniqueId = this._uniqueIdCounter++;
  12546. var position = this.meshes.push(newMesh);
  12547. //notify the collision coordinator
  12548. this.collisionCoordinator.onMeshAdded(newMesh);
  12549. if (this.onNewMeshAdded) {
  12550. this.onNewMeshAdded(newMesh, position, this);
  12551. }
  12552. };
  12553. Scene.prototype.removeMesh = function (toRemove) {
  12554. var index = this.meshes.indexOf(toRemove);
  12555. if (index !== -1) {
  12556. // Remove from the scene if mesh found
  12557. this.meshes.splice(index, 1);
  12558. }
  12559. //notify the collision coordinator
  12560. this.collisionCoordinator.onMeshRemoved(toRemove);
  12561. if (this.onMeshRemoved) {
  12562. this.onMeshRemoved(toRemove);
  12563. }
  12564. return index;
  12565. };
  12566. Scene.prototype.removeLight = function (toRemove) {
  12567. var index = this.lights.indexOf(toRemove);
  12568. if (index !== -1) {
  12569. // Remove from the scene if mesh found
  12570. this.lights.splice(index, 1);
  12571. }
  12572. if (this.onLightRemoved) {
  12573. this.onLightRemoved(toRemove);
  12574. }
  12575. return index;
  12576. };
  12577. Scene.prototype.removeCamera = function (toRemove) {
  12578. var index = this.cameras.indexOf(toRemove);
  12579. if (index !== -1) {
  12580. // Remove from the scene if mesh found
  12581. this.cameras.splice(index, 1);
  12582. }
  12583. // Remove from activeCameras
  12584. var index2 = this.activeCameras.indexOf(toRemove);
  12585. if (index2 !== -1) {
  12586. // Remove from the scene if mesh found
  12587. this.activeCameras.splice(index2, 1);
  12588. }
  12589. // Reset the activeCamera
  12590. if (this.activeCamera === toRemove) {
  12591. if (this.cameras.length > 0) {
  12592. this.activeCamera = this.cameras[0];
  12593. }
  12594. else {
  12595. this.activeCamera = null;
  12596. }
  12597. }
  12598. if (this.onCameraRemoved) {
  12599. this.onCameraRemoved(toRemove);
  12600. }
  12601. return index;
  12602. };
  12603. Scene.prototype.addLight = function (newLight) {
  12604. newLight.uniqueId = this._uniqueIdCounter++;
  12605. var position = this.lights.push(newLight);
  12606. if (this.onNewLightAdded) {
  12607. this.onNewLightAdded(newLight, position, this);
  12608. }
  12609. };
  12610. Scene.prototype.addCamera = function (newCamera) {
  12611. newCamera.uniqueId = this._uniqueIdCounter++;
  12612. var position = this.cameras.push(newCamera);
  12613. if (this.onNewCameraAdded) {
  12614. this.onNewCameraAdded(newCamera, position, this);
  12615. }
  12616. };
  12617. /**
  12618. * sets the active camera of the scene using its ID
  12619. * @param {string} id - the camera's ID
  12620. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12621. * @see activeCamera
  12622. */
  12623. Scene.prototype.setActiveCameraByID = function (id) {
  12624. var camera = this.getCameraByID(id);
  12625. if (camera) {
  12626. this.activeCamera = camera;
  12627. return camera;
  12628. }
  12629. return null;
  12630. };
  12631. /**
  12632. * sets the active camera of the scene using its name
  12633. * @param {string} name - the camera's name
  12634. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12635. * @see activeCamera
  12636. */
  12637. Scene.prototype.setActiveCameraByName = function (name) {
  12638. var camera = this.getCameraByName(name);
  12639. if (camera) {
  12640. this.activeCamera = camera;
  12641. return camera;
  12642. }
  12643. return null;
  12644. };
  12645. /**
  12646. * get a material using its id
  12647. * @param {string} the material's ID
  12648. * @return {BABYLON.Material|null} the material or null if none found.
  12649. */
  12650. Scene.prototype.getMaterialByID = function (id) {
  12651. for (var index = 0; index < this.materials.length; index++) {
  12652. if (this.materials[index].id === id) {
  12653. return this.materials[index];
  12654. }
  12655. }
  12656. return null;
  12657. };
  12658. /**
  12659. * get a material using its name
  12660. * @param {string} the material's name
  12661. * @return {BABYLON.Material|null} the material or null if none found.
  12662. */
  12663. Scene.prototype.getMaterialByName = function (name) {
  12664. for (var index = 0; index < this.materials.length; index++) {
  12665. if (this.materials[index].name === name) {
  12666. return this.materials[index];
  12667. }
  12668. }
  12669. return null;
  12670. };
  12671. Scene.prototype.getCameraByID = function (id) {
  12672. for (var index = 0; index < this.cameras.length; index++) {
  12673. if (this.cameras[index].id === id) {
  12674. return this.cameras[index];
  12675. }
  12676. }
  12677. return null;
  12678. };
  12679. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  12680. for (var index = 0; index < this.cameras.length; index++) {
  12681. if (this.cameras[index].uniqueId === uniqueId) {
  12682. return this.cameras[index];
  12683. }
  12684. }
  12685. return null;
  12686. };
  12687. /**
  12688. * get a camera using its name
  12689. * @param {string} the camera's name
  12690. * @return {BABYLON.Camera|null} the camera or null if none found.
  12691. */
  12692. Scene.prototype.getCameraByName = function (name) {
  12693. for (var index = 0; index < this.cameras.length; index++) {
  12694. if (this.cameras[index].name === name) {
  12695. return this.cameras[index];
  12696. }
  12697. }
  12698. return null;
  12699. };
  12700. /**
  12701. * get a light node using its name
  12702. * @param {string} the light's name
  12703. * @return {BABYLON.Light|null} the light or null if none found.
  12704. */
  12705. Scene.prototype.getLightByName = function (name) {
  12706. for (var index = 0; index < this.lights.length; index++) {
  12707. if (this.lights[index].name === name) {
  12708. return this.lights[index];
  12709. }
  12710. }
  12711. return null;
  12712. };
  12713. /**
  12714. * get a light node using its ID
  12715. * @param {string} the light's id
  12716. * @return {BABYLON.Light|null} the light or null if none found.
  12717. */
  12718. Scene.prototype.getLightByID = function (id) {
  12719. for (var index = 0; index < this.lights.length; index++) {
  12720. if (this.lights[index].id === id) {
  12721. return this.lights[index];
  12722. }
  12723. }
  12724. return null;
  12725. };
  12726. /**
  12727. * get a light node using its scene-generated unique ID
  12728. * @param {number} the light's unique id
  12729. * @return {BABYLON.Light|null} the light or null if none found.
  12730. */
  12731. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  12732. for (var index = 0; index < this.lights.length; index++) {
  12733. if (this.lights[index].uniqueId === uniqueId) {
  12734. return this.lights[index];
  12735. }
  12736. }
  12737. return null;
  12738. };
  12739. /**
  12740. * get a geometry using its ID
  12741. * @param {string} the geometry's id
  12742. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  12743. */
  12744. Scene.prototype.getGeometryByID = function (id) {
  12745. for (var index = 0; index < this._geometries.length; index++) {
  12746. if (this._geometries[index].id === id) {
  12747. return this._geometries[index];
  12748. }
  12749. }
  12750. return null;
  12751. };
  12752. /**
  12753. * add a new geometry to this scene.
  12754. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  12755. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  12756. * @return {boolean} was the geometry added or not
  12757. */
  12758. Scene.prototype.pushGeometry = function (geometry, force) {
  12759. if (!force && this.getGeometryByID(geometry.id)) {
  12760. return false;
  12761. }
  12762. this._geometries.push(geometry);
  12763. //notify the collision coordinator
  12764. this.collisionCoordinator.onGeometryAdded(geometry);
  12765. if (this.onGeometryAdded) {
  12766. this.onGeometryAdded(geometry);
  12767. }
  12768. return true;
  12769. };
  12770. /**
  12771. * Removes an existing geometry
  12772. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  12773. * @return {boolean} was the geometry removed or not
  12774. */
  12775. Scene.prototype.removeGeometry = function (geometry) {
  12776. var index = this._geometries.indexOf(geometry);
  12777. if (index > -1) {
  12778. this._geometries.splice(index, 1);
  12779. //notify the collision coordinator
  12780. this.collisionCoordinator.onGeometryDeleted(geometry);
  12781. if (this.onGeometryRemoved) {
  12782. this.onGeometryRemoved(geometry);
  12783. }
  12784. return true;
  12785. }
  12786. return false;
  12787. };
  12788. Scene.prototype.getGeometries = function () {
  12789. return this._geometries;
  12790. };
  12791. /**
  12792. * Get the first added mesh found of a given ID
  12793. * @param {string} id - the id to search for
  12794. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12795. */
  12796. Scene.prototype.getMeshByID = function (id) {
  12797. for (var index = 0; index < this.meshes.length; index++) {
  12798. if (this.meshes[index].id === id) {
  12799. return this.meshes[index];
  12800. }
  12801. }
  12802. return null;
  12803. };
  12804. /**
  12805. * Get a mesh with its auto-generated unique id
  12806. * @param {number} uniqueId - the unique id to search for
  12807. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12808. */
  12809. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  12810. for (var index = 0; index < this.meshes.length; index++) {
  12811. if (this.meshes[index].uniqueId === uniqueId) {
  12812. return this.meshes[index];
  12813. }
  12814. }
  12815. return null;
  12816. };
  12817. /**
  12818. * Get a the last added mesh found of a given ID
  12819. * @param {string} id - the id to search for
  12820. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12821. */
  12822. Scene.prototype.getLastMeshByID = function (id) {
  12823. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12824. if (this.meshes[index].id === id) {
  12825. return this.meshes[index];
  12826. }
  12827. }
  12828. return null;
  12829. };
  12830. /**
  12831. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  12832. * @param {string} id - the id to search for
  12833. * @return {BABYLON.Node|null} the node found or null if not found at all.
  12834. */
  12835. Scene.prototype.getLastEntryByID = function (id) {
  12836. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12837. if (this.meshes[index].id === id) {
  12838. return this.meshes[index];
  12839. }
  12840. }
  12841. for (index = this.cameras.length - 1; index >= 0; index--) {
  12842. if (this.cameras[index].id === id) {
  12843. return this.cameras[index];
  12844. }
  12845. }
  12846. for (index = this.lights.length - 1; index >= 0; index--) {
  12847. if (this.lights[index].id === id) {
  12848. return this.lights[index];
  12849. }
  12850. }
  12851. return null;
  12852. };
  12853. Scene.prototype.getNodeByName = function (name) {
  12854. var mesh = this.getMeshByName(name);
  12855. if (mesh) {
  12856. return mesh;
  12857. }
  12858. var light = this.getLightByName(name);
  12859. if (light) {
  12860. return light;
  12861. }
  12862. return this.getCameraByName(name);
  12863. };
  12864. Scene.prototype.getMeshByName = function (name) {
  12865. for (var index = 0; index < this.meshes.length; index++) {
  12866. if (this.meshes[index].name === name) {
  12867. return this.meshes[index];
  12868. }
  12869. }
  12870. return null;
  12871. };
  12872. Scene.prototype.getSoundByName = function (name) {
  12873. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  12874. if (this.mainSoundTrack.soundCollection[index].name === name) {
  12875. return this.mainSoundTrack.soundCollection[index];
  12876. }
  12877. }
  12878. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  12879. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  12880. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  12881. return this.soundTracks[sdIndex].soundCollection[index];
  12882. }
  12883. }
  12884. }
  12885. return null;
  12886. };
  12887. Scene.prototype.getLastSkeletonByID = function (id) {
  12888. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  12889. if (this.skeletons[index].id === id) {
  12890. return this.skeletons[index];
  12891. }
  12892. }
  12893. return null;
  12894. };
  12895. Scene.prototype.getSkeletonById = function (id) {
  12896. for (var index = 0; index < this.skeletons.length; index++) {
  12897. if (this.skeletons[index].id === id) {
  12898. return this.skeletons[index];
  12899. }
  12900. }
  12901. return null;
  12902. };
  12903. Scene.prototype.getSkeletonByName = function (name) {
  12904. for (var index = 0; index < this.skeletons.length; index++) {
  12905. if (this.skeletons[index].name === name) {
  12906. return this.skeletons[index];
  12907. }
  12908. }
  12909. return null;
  12910. };
  12911. Scene.prototype.isActiveMesh = function (mesh) {
  12912. return (this._activeMeshes.indexOf(mesh) !== -1);
  12913. };
  12914. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  12915. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  12916. var material = subMesh.getMaterial();
  12917. if (mesh.showSubMeshesBoundingBox) {
  12918. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  12919. }
  12920. if (material) {
  12921. // Render targets
  12922. if (material.getRenderTargetTextures) {
  12923. if (this._processedMaterials.indexOf(material) === -1) {
  12924. this._processedMaterials.push(material);
  12925. this._renderTargets.concat(material.getRenderTargetTextures());
  12926. }
  12927. }
  12928. // Dispatch
  12929. this._activeIndices += subMesh.indexCount;
  12930. this._renderingManager.dispatch(subMesh);
  12931. }
  12932. }
  12933. };
  12934. Scene.prototype._evaluateActiveMeshes = function () {
  12935. this.activeCamera._activeMeshes.reset();
  12936. this._activeMeshes.reset();
  12937. this._renderingManager.reset();
  12938. this._processedMaterials.reset();
  12939. this._activeParticleSystems.reset();
  12940. this._activeSkeletons.reset();
  12941. this._boundingBoxRenderer.reset();
  12942. if (!this._frustumPlanes) {
  12943. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12944. }
  12945. else {
  12946. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12947. }
  12948. // Meshes
  12949. var meshes;
  12950. var len;
  12951. if (this._selectionOctree) {
  12952. var selection = this._selectionOctree.select(this._frustumPlanes);
  12953. meshes = selection.data;
  12954. len = selection.length;
  12955. }
  12956. else {
  12957. len = this.meshes.length;
  12958. meshes = this.meshes;
  12959. }
  12960. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  12961. var mesh = meshes[meshIndex];
  12962. if (mesh.isBlocked) {
  12963. continue;
  12964. }
  12965. this._totalVertices += mesh.getTotalVertices();
  12966. if (!mesh.isReady() || !mesh.isEnabled()) {
  12967. continue;
  12968. }
  12969. mesh.computeWorldMatrix();
  12970. // Intersections
  12971. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  12972. this._meshesForIntersections.pushNoDuplicate(mesh);
  12973. }
  12974. // Switch to current LOD
  12975. var meshLOD = mesh.getLOD(this.activeCamera);
  12976. if (!meshLOD) {
  12977. continue;
  12978. }
  12979. mesh._preActivate();
  12980. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  12981. this._activeMeshes.push(mesh);
  12982. this.activeCamera._activeMeshes.push(mesh);
  12983. mesh._activate(this._renderId);
  12984. this._activeMesh(meshLOD);
  12985. }
  12986. }
  12987. // Particle systems
  12988. var beforeParticlesDate = BABYLON.Tools.Now;
  12989. if (this.particlesEnabled) {
  12990. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  12991. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  12992. var particleSystem = this.particleSystems[particleIndex];
  12993. if (!particleSystem.isStarted()) {
  12994. continue;
  12995. }
  12996. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  12997. this._activeParticleSystems.push(particleSystem);
  12998. particleSystem.animate();
  12999. }
  13000. }
  13001. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13002. }
  13003. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13004. };
  13005. Scene.prototype._activeMesh = function (mesh) {
  13006. if (mesh.skeleton && this.skeletonsEnabled) {
  13007. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13008. }
  13009. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13010. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13011. }
  13012. if (mesh && mesh.subMeshes) {
  13013. // Submeshes Octrees
  13014. var len;
  13015. var subMeshes;
  13016. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13017. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13018. len = intersections.length;
  13019. subMeshes = intersections.data;
  13020. }
  13021. else {
  13022. subMeshes = mesh.subMeshes;
  13023. len = subMeshes.length;
  13024. }
  13025. for (var subIndex = 0; subIndex < len; subIndex++) {
  13026. var subMesh = subMeshes[subIndex];
  13027. this._evaluateSubMesh(subMesh, mesh);
  13028. }
  13029. }
  13030. };
  13031. Scene.prototype.updateTransformMatrix = function (force) {
  13032. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13033. };
  13034. Scene.prototype._renderForCamera = function (camera) {
  13035. var engine = this._engine;
  13036. this.activeCamera = camera;
  13037. if (!this.activeCamera)
  13038. throw new Error("Active camera not set");
  13039. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13040. // Viewport
  13041. engine.setViewport(this.activeCamera.viewport);
  13042. // Camera
  13043. this.resetCachedMaterial();
  13044. this._renderId++;
  13045. this.updateTransformMatrix();
  13046. if (this.beforeCameraRender) {
  13047. this.beforeCameraRender(this.activeCamera);
  13048. }
  13049. // Meshes
  13050. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13051. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13052. this._evaluateActiveMeshes();
  13053. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13054. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13055. // Skeletons
  13056. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13057. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13058. skeleton.prepare();
  13059. }
  13060. // Render targets
  13061. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13062. if (this.renderTargetsEnabled) {
  13063. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13064. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13065. var renderTarget = this._renderTargets.data[renderIndex];
  13066. if (renderTarget._shouldRender()) {
  13067. this._renderId++;
  13068. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13069. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13070. }
  13071. }
  13072. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13073. this._renderId++;
  13074. }
  13075. if (this._renderTargets.length > 0) {
  13076. engine.restoreDefaultFramebuffer();
  13077. }
  13078. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13079. // Prepare Frame
  13080. this.postProcessManager._prepareFrame();
  13081. var beforeRenderDate = BABYLON.Tools.Now;
  13082. // Backgrounds
  13083. if (this.layers.length) {
  13084. engine.setDepthBuffer(false);
  13085. var layerIndex;
  13086. var layer;
  13087. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13088. layer = this.layers[layerIndex];
  13089. if (layer.isBackground) {
  13090. layer.render();
  13091. }
  13092. }
  13093. engine.setDepthBuffer(true);
  13094. }
  13095. // Render
  13096. BABYLON.Tools.StartPerformanceCounter("Main render");
  13097. this._renderingManager.render(null, null, true, true);
  13098. BABYLON.Tools.EndPerformanceCounter("Main render");
  13099. // Bounding boxes
  13100. this._boundingBoxRenderer.render();
  13101. // Lens flares
  13102. if (this.lensFlaresEnabled) {
  13103. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13104. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13105. this.lensFlareSystems[lensFlareSystemIndex].render();
  13106. }
  13107. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13108. }
  13109. // Foregrounds
  13110. if (this.layers.length) {
  13111. engine.setDepthBuffer(false);
  13112. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13113. layer = this.layers[layerIndex];
  13114. if (!layer.isBackground) {
  13115. layer.render();
  13116. }
  13117. }
  13118. engine.setDepthBuffer(true);
  13119. }
  13120. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13121. // Finalize frame
  13122. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13123. // Update camera
  13124. this.activeCamera._updateFromScene();
  13125. // Reset some special arrays
  13126. this._renderTargets.reset();
  13127. if (this.afterCameraRender) {
  13128. this.afterCameraRender(this.activeCamera);
  13129. }
  13130. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13131. };
  13132. Scene.prototype._processSubCameras = function (camera) {
  13133. if (camera.subCameras.length === 0) {
  13134. this._renderForCamera(camera);
  13135. return;
  13136. }
  13137. // Sub-cameras
  13138. for (var index = 0; index < camera.subCameras.length; index++) {
  13139. this._renderForCamera(camera.subCameras[index]);
  13140. }
  13141. this.activeCamera = camera;
  13142. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13143. // Update camera
  13144. this.activeCamera._updateFromScene();
  13145. };
  13146. Scene.prototype._checkIntersections = function () {
  13147. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13148. var sourceMesh = this._meshesForIntersections.data[index];
  13149. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13150. var action = sourceMesh.actionManager.actions[actionIndex];
  13151. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13152. var parameters = action.getTriggerParameter();
  13153. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13154. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13155. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13156. if (areIntersecting && currentIntersectionInProgress === -1) {
  13157. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13158. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  13159. sourceMesh._intersectionsInProgress.push(otherMesh);
  13160. }
  13161. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13162. sourceMesh._intersectionsInProgress.push(otherMesh);
  13163. }
  13164. }
  13165. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13166. //They intersected, and now they don't.
  13167. //is this trigger an exit trigger? execute an event.
  13168. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13169. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  13170. }
  13171. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13172. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13173. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13174. }
  13175. }
  13176. }
  13177. }
  13178. }
  13179. };
  13180. Scene.prototype.render = function () {
  13181. var startDate = BABYLON.Tools.Now;
  13182. this._particlesDuration = 0;
  13183. this._spritesDuration = 0;
  13184. this._activeParticles = 0;
  13185. this._renderDuration = 0;
  13186. this._renderTargetsDuration = 0;
  13187. this._evaluateActiveMeshesDuration = 0;
  13188. this._totalVertices = 0;
  13189. this._activeIndices = 0;
  13190. this._activeBones = 0;
  13191. this.getEngine().resetDrawCalls();
  13192. this._meshesForIntersections.reset();
  13193. this.resetCachedMaterial();
  13194. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13195. // Actions
  13196. if (this.actionManager) {
  13197. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13198. }
  13199. //Simplification Queue
  13200. if (!this.simplificationQueue.running) {
  13201. this.simplificationQueue.executeNext();
  13202. }
  13203. // Before render
  13204. if (this.beforeRender) {
  13205. this.beforeRender();
  13206. }
  13207. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13208. this._onBeforeRenderCallbacks[callbackIndex]();
  13209. }
  13210. // Animations
  13211. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13212. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13213. this._animate();
  13214. // Physics
  13215. if (this._physicsEngine) {
  13216. BABYLON.Tools.StartPerformanceCounter("Physics");
  13217. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13218. BABYLON.Tools.EndPerformanceCounter("Physics");
  13219. }
  13220. // Customs render targets
  13221. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13222. var engine = this.getEngine();
  13223. var currentActiveCamera = this.activeCamera;
  13224. if (this.renderTargetsEnabled) {
  13225. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13226. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13227. var renderTarget = this.customRenderTargets[customIndex];
  13228. if (renderTarget._shouldRender()) {
  13229. this._renderId++;
  13230. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13231. if (!this.activeCamera)
  13232. throw new Error("Active camera not set");
  13233. // Viewport
  13234. engine.setViewport(this.activeCamera.viewport);
  13235. // Camera
  13236. this.updateTransformMatrix();
  13237. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13238. }
  13239. }
  13240. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13241. this._renderId++;
  13242. }
  13243. if (this.customRenderTargets.length > 0) {
  13244. engine.restoreDefaultFramebuffer();
  13245. }
  13246. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13247. this.activeCamera = currentActiveCamera;
  13248. // Procedural textures
  13249. if (this.proceduralTexturesEnabled) {
  13250. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13251. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13252. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13253. if (proceduralTexture._shouldRender()) {
  13254. proceduralTexture.render();
  13255. }
  13256. }
  13257. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13258. }
  13259. // Clear
  13260. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13261. // Shadows
  13262. if (this.shadowsEnabled) {
  13263. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13264. var light = this.lights[lightIndex];
  13265. var shadowGenerator = light.getShadowGenerator();
  13266. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13267. this._renderTargets.push(shadowGenerator.getShadowMap());
  13268. }
  13269. }
  13270. }
  13271. // Depth renderer
  13272. if (this._depthRenderer) {
  13273. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13274. }
  13275. // RenderPipeline
  13276. this.postProcessRenderPipelineManager.update();
  13277. // Multi-cameras?
  13278. if (this.activeCameras.length > 0) {
  13279. var currentRenderId = this._renderId;
  13280. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13281. this._renderId = currentRenderId;
  13282. this._processSubCameras(this.activeCameras[cameraIndex]);
  13283. }
  13284. }
  13285. else {
  13286. if (!this.activeCamera) {
  13287. throw new Error("No camera defined");
  13288. }
  13289. this._processSubCameras(this.activeCamera);
  13290. }
  13291. // Intersection checks
  13292. this._checkIntersections();
  13293. // Update the audio listener attached to the camera
  13294. this._updateAudioParameters();
  13295. // After render
  13296. if (this.afterRender) {
  13297. this.afterRender();
  13298. }
  13299. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13300. this._onAfterRenderCallbacks[callbackIndex]();
  13301. }
  13302. // Cleaning
  13303. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13304. this._toBeDisposed.data[index].dispose();
  13305. this._toBeDisposed[index] = null;
  13306. }
  13307. this._toBeDisposed.reset();
  13308. if (this.dumpNextRenderTargets) {
  13309. this.dumpNextRenderTargets = false;
  13310. }
  13311. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13312. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13313. };
  13314. Scene.prototype._updateAudioParameters = function () {
  13315. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  13316. return;
  13317. }
  13318. var listeningCamera;
  13319. var audioEngine = BABYLON.Engine.audioEngine;
  13320. if (this.activeCameras.length > 0) {
  13321. listeningCamera = this.activeCameras[0];
  13322. }
  13323. else {
  13324. listeningCamera = this.activeCamera;
  13325. }
  13326. if (listeningCamera && audioEngine.canUseWebAudio) {
  13327. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13328. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13329. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13330. cameraDirection.normalize();
  13331. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13332. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13333. var sound = this.mainSoundTrack.soundCollection[i];
  13334. if (sound.useCustomAttenuation) {
  13335. sound.updateDistanceFromListener();
  13336. }
  13337. }
  13338. for (i = 0; i < this.soundTracks.length; i++) {
  13339. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13340. sound = this.soundTracks[i].soundCollection[j];
  13341. if (sound.useCustomAttenuation) {
  13342. sound.updateDistanceFromListener();
  13343. }
  13344. }
  13345. }
  13346. }
  13347. };
  13348. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13349. // Audio
  13350. get: function () {
  13351. return this._audioEnabled;
  13352. },
  13353. set: function (value) {
  13354. this._audioEnabled = value;
  13355. if (this._audioEnabled) {
  13356. this._enableAudio();
  13357. }
  13358. else {
  13359. this._disableAudio();
  13360. }
  13361. },
  13362. enumerable: true,
  13363. configurable: true
  13364. });
  13365. Scene.prototype._disableAudio = function () {
  13366. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13367. this.mainSoundTrack.soundCollection[i].pause();
  13368. }
  13369. for (i = 0; i < this.soundTracks.length; i++) {
  13370. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13371. this.soundTracks[i].soundCollection[j].pause();
  13372. }
  13373. }
  13374. };
  13375. Scene.prototype._enableAudio = function () {
  13376. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13377. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13378. this.mainSoundTrack.soundCollection[i].play();
  13379. }
  13380. }
  13381. for (i = 0; i < this.soundTracks.length; i++) {
  13382. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13383. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13384. this.soundTracks[i].soundCollection[j].play();
  13385. }
  13386. }
  13387. }
  13388. };
  13389. Object.defineProperty(Scene.prototype, "headphone", {
  13390. get: function () {
  13391. return this._headphone;
  13392. },
  13393. set: function (value) {
  13394. this._headphone = value;
  13395. if (this._headphone) {
  13396. this._switchAudioModeForHeadphones();
  13397. }
  13398. else {
  13399. this._switchAudioModeForNormalSpeakers();
  13400. }
  13401. },
  13402. enumerable: true,
  13403. configurable: true
  13404. });
  13405. Scene.prototype._switchAudioModeForHeadphones = function () {
  13406. this.mainSoundTrack.switchPanningModelToHRTF();
  13407. for (var i = 0; i < this.soundTracks.length; i++) {
  13408. this.soundTracks[i].switchPanningModelToHRTF();
  13409. }
  13410. };
  13411. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13412. this.mainSoundTrack.switchPanningModelToEqualPower();
  13413. for (var i = 0; i < this.soundTracks.length; i++) {
  13414. this.soundTracks[i].switchPanningModelToEqualPower();
  13415. }
  13416. };
  13417. Scene.prototype.enableDepthRenderer = function () {
  13418. if (this._depthRenderer) {
  13419. return this._depthRenderer;
  13420. }
  13421. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13422. return this._depthRenderer;
  13423. };
  13424. Scene.prototype.disableDepthRenderer = function () {
  13425. if (!this._depthRenderer) {
  13426. return;
  13427. }
  13428. this._depthRenderer.dispose();
  13429. this._depthRenderer = null;
  13430. };
  13431. Scene.prototype.dispose = function () {
  13432. this.beforeRender = null;
  13433. this.afterRender = null;
  13434. this.skeletons = [];
  13435. this._boundingBoxRenderer.dispose();
  13436. if (this._depthRenderer) {
  13437. this._depthRenderer.dispose();
  13438. }
  13439. // Debug layer
  13440. this.debugLayer.hide();
  13441. // Events
  13442. if (this.onDispose) {
  13443. this.onDispose();
  13444. }
  13445. this._onBeforeRenderCallbacks = [];
  13446. this._onAfterRenderCallbacks = [];
  13447. this.detachControl();
  13448. // Release sounds & sounds tracks
  13449. this.disposeSounds();
  13450. // Detach cameras
  13451. var canvas = this._engine.getRenderingCanvas();
  13452. var index;
  13453. for (index = 0; index < this.cameras.length; index++) {
  13454. this.cameras[index].detachControl(canvas);
  13455. }
  13456. // Release lights
  13457. while (this.lights.length) {
  13458. this.lights[0].dispose();
  13459. }
  13460. // Release meshes
  13461. while (this.meshes.length) {
  13462. this.meshes[0].dispose(true);
  13463. }
  13464. // Release cameras
  13465. while (this.cameras.length) {
  13466. this.cameras[0].dispose();
  13467. }
  13468. // Release materials
  13469. while (this.materials.length) {
  13470. this.materials[0].dispose();
  13471. }
  13472. // Release particles
  13473. while (this.particleSystems.length) {
  13474. this.particleSystems[0].dispose();
  13475. }
  13476. // Release sprites
  13477. while (this.spriteManagers.length) {
  13478. this.spriteManagers[0].dispose();
  13479. }
  13480. // Release layers
  13481. while (this.layers.length) {
  13482. this.layers[0].dispose();
  13483. }
  13484. // Release textures
  13485. while (this.textures.length) {
  13486. this.textures[0].dispose();
  13487. }
  13488. // Post-processes
  13489. this.postProcessManager.dispose();
  13490. // Physics
  13491. if (this._physicsEngine) {
  13492. this.disablePhysicsEngine();
  13493. }
  13494. // Remove from engine
  13495. index = this._engine.scenes.indexOf(this);
  13496. if (index > -1) {
  13497. this._engine.scenes.splice(index, 1);
  13498. }
  13499. this._engine.wipeCaches();
  13500. };
  13501. // Release sounds & sounds tracks
  13502. Scene.prototype.disposeSounds = function () {
  13503. this.mainSoundTrack.dispose();
  13504. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13505. this.soundTracks[scIndex].dispose();
  13506. }
  13507. };
  13508. // Octrees
  13509. Scene.prototype.getWorldExtends = function () {
  13510. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13511. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13512. for (var index = 0; index < this.meshes.length; index++) {
  13513. var mesh = this.meshes[index];
  13514. mesh.computeWorldMatrix(true);
  13515. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13516. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13517. BABYLON.Tools.CheckExtends(minBox, min, max);
  13518. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13519. }
  13520. return {
  13521. min: min,
  13522. max: max
  13523. };
  13524. };
  13525. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13526. if (maxCapacity === void 0) { maxCapacity = 64; }
  13527. if (maxDepth === void 0) { maxDepth = 2; }
  13528. if (!this._selectionOctree) {
  13529. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13530. }
  13531. var worldExtends = this.getWorldExtends();
  13532. // Update octree
  13533. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13534. return this._selectionOctree;
  13535. };
  13536. // Picking
  13537. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  13538. var engine = this._engine;
  13539. if (!camera) {
  13540. if (!this.activeCamera)
  13541. throw new Error("Active camera not set");
  13542. camera = this.activeCamera;
  13543. }
  13544. var cameraViewport = camera.viewport;
  13545. var viewport = cameraViewport.toGlobal(engine);
  13546. // Moving coordinates to local viewport world
  13547. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13548. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13549. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13550. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13551. };
  13552. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13553. var pickingInfo = null;
  13554. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13555. var mesh = this.meshes[meshIndex];
  13556. if (predicate) {
  13557. if (!predicate(mesh)) {
  13558. continue;
  13559. }
  13560. }
  13561. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13562. continue;
  13563. }
  13564. var world = mesh.getWorldMatrix();
  13565. var ray = rayFunction(world);
  13566. var result = mesh.intersects(ray, fastCheck);
  13567. if (!result || !result.hit)
  13568. continue;
  13569. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13570. continue;
  13571. pickingInfo = result;
  13572. if (fastCheck) {
  13573. break;
  13574. }
  13575. }
  13576. return pickingInfo || new BABYLON.PickingInfo();
  13577. };
  13578. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13579. var _this = this;
  13580. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13581. /// <param name="x">X position on screen</param>
  13582. /// <param name="y">Y position on screen</param>
  13583. /// <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>
  13584. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13585. /// <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>
  13586. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  13587. };
  13588. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  13589. var _this = this;
  13590. return this._internalPick(function (world) {
  13591. if (!_this._pickWithRayInverseMatrix) {
  13592. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  13593. }
  13594. world.invertToRef(_this._pickWithRayInverseMatrix);
  13595. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  13596. }, predicate, fastCheck);
  13597. };
  13598. Scene.prototype.setPointerOverMesh = function (mesh) {
  13599. if (this._pointerOverMesh === mesh) {
  13600. return;
  13601. }
  13602. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13603. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13604. }
  13605. this._pointerOverMesh = mesh;
  13606. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13607. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13608. }
  13609. };
  13610. Scene.prototype.getPointerOverMesh = function () {
  13611. return this._pointerOverMesh;
  13612. };
  13613. // Physics
  13614. Scene.prototype.getPhysicsEngine = function () {
  13615. return this._physicsEngine;
  13616. };
  13617. Scene.prototype.enablePhysics = function (gravity, plugin) {
  13618. if (this._physicsEngine) {
  13619. return true;
  13620. }
  13621. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  13622. if (!this._physicsEngine.isSupported()) {
  13623. this._physicsEngine = null;
  13624. return false;
  13625. }
  13626. this._physicsEngine._initialize(gravity);
  13627. return true;
  13628. };
  13629. Scene.prototype.disablePhysicsEngine = function () {
  13630. if (!this._physicsEngine) {
  13631. return;
  13632. }
  13633. this._physicsEngine.dispose();
  13634. this._physicsEngine = undefined;
  13635. };
  13636. Scene.prototype.isPhysicsEnabled = function () {
  13637. return this._physicsEngine !== undefined;
  13638. };
  13639. Scene.prototype.setGravity = function (gravity) {
  13640. if (!this._physicsEngine) {
  13641. return;
  13642. }
  13643. this._physicsEngine._setGravity(gravity);
  13644. };
  13645. Scene.prototype.createCompoundImpostor = function (parts, options) {
  13646. if (parts.parts) {
  13647. options = parts;
  13648. parts = parts.parts;
  13649. }
  13650. if (!this._physicsEngine) {
  13651. return null;
  13652. }
  13653. for (var index = 0; index < parts.length; index++) {
  13654. var mesh = parts[index].mesh;
  13655. mesh._physicImpostor = parts[index].impostor;
  13656. mesh._physicsMass = options.mass / parts.length;
  13657. mesh._physicsFriction = options.friction;
  13658. mesh._physicRestitution = options.restitution;
  13659. }
  13660. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  13661. };
  13662. Scene.prototype.deleteCompoundImpostor = function (compound) {
  13663. for (var index = 0; index < compound.parts.length; index++) {
  13664. var mesh = compound.parts[index].mesh;
  13665. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  13666. this._physicsEngine._unregisterMesh(mesh);
  13667. }
  13668. };
  13669. // Misc.
  13670. Scene.prototype.createDefaultCameraOrLight = function () {
  13671. // Light
  13672. if (this.lights.length === 0) {
  13673. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  13674. }
  13675. // Camera
  13676. if (!this.activeCamera) {
  13677. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  13678. // Compute position
  13679. var worldExtends = this.getWorldExtends();
  13680. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  13681. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  13682. camera.setTarget(worldCenter);
  13683. this.activeCamera = camera;
  13684. }
  13685. };
  13686. // Tags
  13687. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  13688. if (tagsQuery === undefined) {
  13689. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  13690. return list;
  13691. }
  13692. var listByTags = [];
  13693. forEach = forEach || (function (item) { return; });
  13694. for (var i in list) {
  13695. var item = list[i];
  13696. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  13697. listByTags.push(item);
  13698. forEach(item);
  13699. }
  13700. }
  13701. return listByTags;
  13702. };
  13703. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  13704. return this._getByTags(this.meshes, tagsQuery, forEach);
  13705. };
  13706. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  13707. return this._getByTags(this.cameras, tagsQuery, forEach);
  13708. };
  13709. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  13710. return this._getByTags(this.lights, tagsQuery, forEach);
  13711. };
  13712. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  13713. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  13714. };
  13715. // Statics
  13716. Scene._FOGMODE_NONE = 0;
  13717. Scene._FOGMODE_EXP = 1;
  13718. Scene._FOGMODE_EXP2 = 2;
  13719. Scene._FOGMODE_LINEAR = 3;
  13720. Scene.MinDeltaTime = 1.0;
  13721. Scene.MaxDeltaTime = 1000.0;
  13722. return Scene;
  13723. })();
  13724. BABYLON.Scene = Scene;
  13725. })(BABYLON || (BABYLON = {}));
  13726. //# sourceMappingURL=babylon.scene.js.map
  13727. var BABYLON;
  13728. (function (BABYLON) {
  13729. var VertexBuffer = (function () {
  13730. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  13731. if (engine instanceof BABYLON.Mesh) {
  13732. this._engine = engine.getScene().getEngine();
  13733. }
  13734. else {
  13735. this._engine = engine;
  13736. }
  13737. this._updatable = updatable;
  13738. this._data = data;
  13739. if (!postponeInternalCreation) {
  13740. this.create();
  13741. }
  13742. this._kind = kind;
  13743. if (stride) {
  13744. this._strideSize = stride;
  13745. return;
  13746. }
  13747. // Deduce stride from kind
  13748. switch (kind) {
  13749. case VertexBuffer.PositionKind:
  13750. this._strideSize = 3;
  13751. break;
  13752. case VertexBuffer.NormalKind:
  13753. this._strideSize = 3;
  13754. break;
  13755. case VertexBuffer.UVKind:
  13756. this._strideSize = 2;
  13757. break;
  13758. case VertexBuffer.UV2Kind:
  13759. this._strideSize = 2;
  13760. break;
  13761. case VertexBuffer.ColorKind:
  13762. this._strideSize = 4;
  13763. break;
  13764. case VertexBuffer.MatricesIndicesKind:
  13765. this._strideSize = 4;
  13766. break;
  13767. case VertexBuffer.MatricesWeightsKind:
  13768. this._strideSize = 4;
  13769. break;
  13770. }
  13771. }
  13772. // Properties
  13773. VertexBuffer.prototype.isUpdatable = function () {
  13774. return this._updatable;
  13775. };
  13776. VertexBuffer.prototype.getData = function () {
  13777. return this._data;
  13778. };
  13779. VertexBuffer.prototype.getBuffer = function () {
  13780. return this._buffer;
  13781. };
  13782. VertexBuffer.prototype.getStrideSize = function () {
  13783. return this._strideSize;
  13784. };
  13785. // Methods
  13786. VertexBuffer.prototype.create = function (data) {
  13787. if (!data && this._buffer) {
  13788. return; // nothing to do
  13789. }
  13790. data = data || this._data;
  13791. if (!this._buffer) {
  13792. if (this._updatable) {
  13793. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  13794. }
  13795. else {
  13796. this._buffer = this._engine.createVertexBuffer(data);
  13797. }
  13798. }
  13799. if (this._updatable) {
  13800. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  13801. this._data = data;
  13802. }
  13803. };
  13804. VertexBuffer.prototype.update = function (data) {
  13805. this.create(data);
  13806. };
  13807. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  13808. if (!this._buffer) {
  13809. return;
  13810. }
  13811. if (this._updatable) {
  13812. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  13813. this._data = null;
  13814. }
  13815. };
  13816. VertexBuffer.prototype.dispose = function () {
  13817. if (!this._buffer) {
  13818. return;
  13819. }
  13820. if (this._engine._releaseBuffer(this._buffer)) {
  13821. this._buffer = null;
  13822. }
  13823. };
  13824. Object.defineProperty(VertexBuffer, "PositionKind", {
  13825. get: function () {
  13826. return VertexBuffer._PositionKind;
  13827. },
  13828. enumerable: true,
  13829. configurable: true
  13830. });
  13831. Object.defineProperty(VertexBuffer, "NormalKind", {
  13832. get: function () {
  13833. return VertexBuffer._NormalKind;
  13834. },
  13835. enumerable: true,
  13836. configurable: true
  13837. });
  13838. Object.defineProperty(VertexBuffer, "UVKind", {
  13839. get: function () {
  13840. return VertexBuffer._UVKind;
  13841. },
  13842. enumerable: true,
  13843. configurable: true
  13844. });
  13845. Object.defineProperty(VertexBuffer, "UV2Kind", {
  13846. get: function () {
  13847. return VertexBuffer._UV2Kind;
  13848. },
  13849. enumerable: true,
  13850. configurable: true
  13851. });
  13852. Object.defineProperty(VertexBuffer, "ColorKind", {
  13853. get: function () {
  13854. return VertexBuffer._ColorKind;
  13855. },
  13856. enumerable: true,
  13857. configurable: true
  13858. });
  13859. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  13860. get: function () {
  13861. return VertexBuffer._MatricesIndicesKind;
  13862. },
  13863. enumerable: true,
  13864. configurable: true
  13865. });
  13866. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  13867. get: function () {
  13868. return VertexBuffer._MatricesWeightsKind;
  13869. },
  13870. enumerable: true,
  13871. configurable: true
  13872. });
  13873. // Enums
  13874. VertexBuffer._PositionKind = "position";
  13875. VertexBuffer._NormalKind = "normal";
  13876. VertexBuffer._UVKind = "uv";
  13877. VertexBuffer._UV2Kind = "uv2";
  13878. VertexBuffer._ColorKind = "color";
  13879. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  13880. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  13881. return VertexBuffer;
  13882. })();
  13883. BABYLON.VertexBuffer = VertexBuffer;
  13884. })(BABYLON || (BABYLON = {}));
  13885. //# sourceMappingURL=babylon.vertexBuffer.js.map
  13886. var BABYLON;
  13887. (function (BABYLON) {
  13888. /**
  13889. * Creates an instance based on a source mesh.
  13890. */
  13891. var InstancedMesh = (function (_super) {
  13892. __extends(InstancedMesh, _super);
  13893. function InstancedMesh(name, source) {
  13894. _super.call(this, name, source.getScene());
  13895. source.instances.push(this);
  13896. this._sourceMesh = source;
  13897. this.position.copyFrom(source.position);
  13898. this.rotation.copyFrom(source.rotation);
  13899. this.scaling.copyFrom(source.scaling);
  13900. if (source.rotationQuaternion) {
  13901. this.rotationQuaternion = source.rotationQuaternion.clone();
  13902. }
  13903. this.infiniteDistance = source.infiniteDistance;
  13904. this.setPivotMatrix(source.getPivotMatrix());
  13905. this.refreshBoundingInfo();
  13906. this._syncSubMeshes();
  13907. }
  13908. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  13909. // Methods
  13910. get: function () {
  13911. return this._sourceMesh.receiveShadows;
  13912. },
  13913. enumerable: true,
  13914. configurable: true
  13915. });
  13916. Object.defineProperty(InstancedMesh.prototype, "material", {
  13917. get: function () {
  13918. return this._sourceMesh.material;
  13919. },
  13920. enumerable: true,
  13921. configurable: true
  13922. });
  13923. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  13924. get: function () {
  13925. return this._sourceMesh.visibility;
  13926. },
  13927. enumerable: true,
  13928. configurable: true
  13929. });
  13930. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  13931. get: function () {
  13932. return this._sourceMesh.skeleton;
  13933. },
  13934. enumerable: true,
  13935. configurable: true
  13936. });
  13937. InstancedMesh.prototype.getTotalVertices = function () {
  13938. return this._sourceMesh.getTotalVertices();
  13939. };
  13940. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  13941. get: function () {
  13942. return this._sourceMesh;
  13943. },
  13944. enumerable: true,
  13945. configurable: true
  13946. });
  13947. InstancedMesh.prototype.getVerticesData = function (kind) {
  13948. return this._sourceMesh.getVerticesData(kind);
  13949. };
  13950. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  13951. return this._sourceMesh.isVerticesDataPresent(kind);
  13952. };
  13953. InstancedMesh.prototype.getIndices = function () {
  13954. return this._sourceMesh.getIndices();
  13955. };
  13956. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  13957. get: function () {
  13958. return this._sourceMesh._positions;
  13959. },
  13960. enumerable: true,
  13961. configurable: true
  13962. });
  13963. InstancedMesh.prototype.refreshBoundingInfo = function () {
  13964. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13965. if (data) {
  13966. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  13967. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  13968. }
  13969. this._updateBoundingInfo();
  13970. };
  13971. InstancedMesh.prototype._preActivate = function () {
  13972. if (this._currentLOD) {
  13973. this._currentLOD._preActivate();
  13974. }
  13975. };
  13976. InstancedMesh.prototype._activate = function (renderId) {
  13977. if (this._currentLOD) {
  13978. this._currentLOD._registerInstanceForRenderId(this, renderId);
  13979. }
  13980. };
  13981. InstancedMesh.prototype.getLOD = function (camera) {
  13982. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  13983. if (this._currentLOD === this.sourceMesh) {
  13984. return this;
  13985. }
  13986. return this._currentLOD;
  13987. };
  13988. InstancedMesh.prototype._syncSubMeshes = function () {
  13989. this.releaseSubMeshes();
  13990. if (this._sourceMesh.subMeshes) {
  13991. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  13992. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  13993. }
  13994. }
  13995. };
  13996. InstancedMesh.prototype._generatePointsArray = function () {
  13997. return this._sourceMesh._generatePointsArray();
  13998. };
  13999. // Clone
  14000. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14001. var result = this._sourceMesh.createInstance(name);
  14002. // Deep copy
  14003. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14004. // Bounding info
  14005. this.refreshBoundingInfo();
  14006. // Parent
  14007. if (newParent) {
  14008. result.parent = newParent;
  14009. }
  14010. if (!doNotCloneChildren) {
  14011. // Children
  14012. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14013. var mesh = this.getScene().meshes[index];
  14014. if (mesh.parent === this) {
  14015. mesh.clone(mesh.name, result);
  14016. }
  14017. }
  14018. }
  14019. result.computeWorldMatrix(true);
  14020. return result;
  14021. };
  14022. // Dispoe
  14023. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14024. // Remove from mesh
  14025. var index = this._sourceMesh.instances.indexOf(this);
  14026. this._sourceMesh.instances.splice(index, 1);
  14027. _super.prototype.dispose.call(this, doNotRecurse);
  14028. };
  14029. return InstancedMesh;
  14030. })(BABYLON.AbstractMesh);
  14031. BABYLON.InstancedMesh = InstancedMesh;
  14032. })(BABYLON || (BABYLON = {}));
  14033. //# sourceMappingURL=babylon.instancedMesh.js.map
  14034. var BABYLON;
  14035. (function (BABYLON) {
  14036. var _InstancesBatch = (function () {
  14037. function _InstancesBatch() {
  14038. this.mustReturn = false;
  14039. this.visibleInstances = new Array();
  14040. this.renderSelf = new Array();
  14041. }
  14042. return _InstancesBatch;
  14043. })();
  14044. BABYLON._InstancesBatch = _InstancesBatch;
  14045. var Mesh = (function (_super) {
  14046. __extends(Mesh, _super);
  14047. /**
  14048. * @constructor
  14049. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14050. * @param {Scene} scene - The scene to add this mesh to.
  14051. * @param {Node} parent - The parent of this mesh, if it has one
  14052. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14053. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14054. * When false, achieved by calling a clone(), also passing False.
  14055. * This will make creation of children, recursive.
  14056. */
  14057. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14058. if (parent === void 0) { parent = null; }
  14059. _super.call(this, name, scene);
  14060. // Members
  14061. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14062. this.instances = new Array();
  14063. this._LODLevels = new Array();
  14064. this._onBeforeRenderCallbacks = new Array();
  14065. this._onAfterRenderCallbacks = new Array();
  14066. this._visibleInstances = {};
  14067. this._renderIdForInstances = new Array();
  14068. this._batchCache = new _InstancesBatch();
  14069. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14070. this._sideOrientation = Mesh._DEFAULTSIDE;
  14071. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14072. if (source) {
  14073. // Geometry
  14074. if (source._geometry) {
  14075. source._geometry.applyToMesh(this);
  14076. }
  14077. // Deep copy
  14078. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14079. // Material
  14080. this.material = source.material;
  14081. if (!doNotCloneChildren) {
  14082. // Children
  14083. for (var index = 0; index < scene.meshes.length; index++) {
  14084. var mesh = scene.meshes[index];
  14085. if (mesh.parent === source) {
  14086. // doNotCloneChildren is always going to be False
  14087. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14088. }
  14089. }
  14090. }
  14091. // Particles
  14092. for (index = 0; index < scene.particleSystems.length; index++) {
  14093. var system = scene.particleSystems[index];
  14094. if (system.emitter === source) {
  14095. system.clone(system.name, this);
  14096. }
  14097. }
  14098. this.computeWorldMatrix(true);
  14099. }
  14100. // Parent
  14101. if (parent !== null) {
  14102. this.parent = parent;
  14103. }
  14104. }
  14105. Object.defineProperty(Mesh, "FRONTSIDE", {
  14106. get: function () {
  14107. return Mesh._FRONTSIDE;
  14108. },
  14109. enumerable: true,
  14110. configurable: true
  14111. });
  14112. Object.defineProperty(Mesh, "BACKSIDE", {
  14113. get: function () {
  14114. return Mesh._BACKSIDE;
  14115. },
  14116. enumerable: true,
  14117. configurable: true
  14118. });
  14119. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14120. get: function () {
  14121. return Mesh._DOUBLESIDE;
  14122. },
  14123. enumerable: true,
  14124. configurable: true
  14125. });
  14126. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14127. get: function () {
  14128. return Mesh._DEFAULTSIDE;
  14129. },
  14130. enumerable: true,
  14131. configurable: true
  14132. });
  14133. Object.defineProperty(Mesh, "NO_CAP", {
  14134. get: function () {
  14135. return Mesh._NO_CAP;
  14136. },
  14137. enumerable: true,
  14138. configurable: true
  14139. });
  14140. Object.defineProperty(Mesh, "CAP_START", {
  14141. get: function () {
  14142. return Mesh._CAP_START;
  14143. },
  14144. enumerable: true,
  14145. configurable: true
  14146. });
  14147. Object.defineProperty(Mesh, "CAP_END", {
  14148. get: function () {
  14149. return Mesh._CAP_END;
  14150. },
  14151. enumerable: true,
  14152. configurable: true
  14153. });
  14154. Object.defineProperty(Mesh, "CAP_ALL", {
  14155. get: function () {
  14156. return Mesh._CAP_ALL;
  14157. },
  14158. enumerable: true,
  14159. configurable: true
  14160. });
  14161. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14162. // Methods
  14163. get: function () {
  14164. return this._LODLevels.length > 0;
  14165. },
  14166. enumerable: true,
  14167. configurable: true
  14168. });
  14169. Mesh.prototype._sortLODLevels = function () {
  14170. this._LODLevels.sort(function (a, b) {
  14171. if (a.distance < b.distance) {
  14172. return 1;
  14173. }
  14174. if (a.distance > b.distance) {
  14175. return -1;
  14176. }
  14177. return 0;
  14178. });
  14179. };
  14180. /**
  14181. * Add a mesh as LOD level triggered at the given distance.
  14182. * @param {number} distance - the distance from the center of the object to show this level
  14183. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  14184. * @return {BABYLON.Mesh} this mesh (for chaining)
  14185. */
  14186. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14187. if (mesh && mesh._masterMesh) {
  14188. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14189. return this;
  14190. }
  14191. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14192. this._LODLevels.push(level);
  14193. if (mesh) {
  14194. mesh._masterMesh = this;
  14195. }
  14196. this._sortLODLevels();
  14197. return this;
  14198. };
  14199. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14200. for (var index = 0; index < this._LODLevels.length; index++) {
  14201. var level = this._LODLevels[index];
  14202. if (level.distance === distance) {
  14203. return level.mesh;
  14204. }
  14205. }
  14206. return null;
  14207. };
  14208. /**
  14209. * Remove a mesh from the LOD array
  14210. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  14211. * @return {BABYLON.Mesh} this mesh (for chaining)
  14212. */
  14213. Mesh.prototype.removeLODLevel = function (mesh) {
  14214. for (var index = 0; index < this._LODLevels.length; index++) {
  14215. if (this._LODLevels[index].mesh === mesh) {
  14216. this._LODLevels.splice(index, 1);
  14217. if (mesh) {
  14218. mesh._masterMesh = null;
  14219. }
  14220. }
  14221. }
  14222. this._sortLODLevels();
  14223. return this;
  14224. };
  14225. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14226. if (!this._LODLevels || this._LODLevels.length === 0) {
  14227. return this;
  14228. }
  14229. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14230. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14231. if (this.onLODLevelSelection) {
  14232. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14233. }
  14234. return this;
  14235. }
  14236. for (var index = 0; index < this._LODLevels.length; index++) {
  14237. var level = this._LODLevels[index];
  14238. if (level.distance < distanceToCamera) {
  14239. if (level.mesh) {
  14240. level.mesh._preActivate();
  14241. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14242. }
  14243. if (this.onLODLevelSelection) {
  14244. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14245. }
  14246. return level.mesh;
  14247. }
  14248. }
  14249. if (this.onLODLevelSelection) {
  14250. this.onLODLevelSelection(distanceToCamera, this, this);
  14251. }
  14252. return this;
  14253. };
  14254. Object.defineProperty(Mesh.prototype, "geometry", {
  14255. get: function () {
  14256. return this._geometry;
  14257. },
  14258. enumerable: true,
  14259. configurable: true
  14260. });
  14261. Mesh.prototype.getTotalVertices = function () {
  14262. if (!this._geometry) {
  14263. return 0;
  14264. }
  14265. return this._geometry.getTotalVertices();
  14266. };
  14267. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14268. if (!this._geometry) {
  14269. return null;
  14270. }
  14271. return this._geometry.getVerticesData(kind, copyWhenShared);
  14272. };
  14273. Mesh.prototype.getVertexBuffer = function (kind) {
  14274. if (!this._geometry) {
  14275. return undefined;
  14276. }
  14277. return this._geometry.getVertexBuffer(kind);
  14278. };
  14279. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14280. if (!this._geometry) {
  14281. if (this._delayInfo) {
  14282. return this._delayInfo.indexOf(kind) !== -1;
  14283. }
  14284. return false;
  14285. }
  14286. return this._geometry.isVerticesDataPresent(kind);
  14287. };
  14288. Mesh.prototype.getVerticesDataKinds = function () {
  14289. if (!this._geometry) {
  14290. var result = [];
  14291. if (this._delayInfo) {
  14292. for (var kind in this._delayInfo) {
  14293. result.push(kind);
  14294. }
  14295. }
  14296. return result;
  14297. }
  14298. return this._geometry.getVerticesDataKinds();
  14299. };
  14300. Mesh.prototype.getTotalIndices = function () {
  14301. if (!this._geometry) {
  14302. return 0;
  14303. }
  14304. return this._geometry.getTotalIndices();
  14305. };
  14306. Mesh.prototype.getIndices = function (copyWhenShared) {
  14307. if (!this._geometry) {
  14308. return [];
  14309. }
  14310. return this._geometry.getIndices(copyWhenShared);
  14311. };
  14312. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14313. get: function () {
  14314. return this._masterMesh !== null && this._masterMesh !== undefined;
  14315. },
  14316. enumerable: true,
  14317. configurable: true
  14318. });
  14319. Mesh.prototype.isReady = function () {
  14320. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14321. return false;
  14322. }
  14323. return _super.prototype.isReady.call(this);
  14324. };
  14325. Mesh.prototype.isDisposed = function () {
  14326. return this._isDisposed;
  14327. };
  14328. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14329. get: function () {
  14330. return this._sideOrientation;
  14331. },
  14332. set: function (sideO) {
  14333. this._sideOrientation = sideO;
  14334. },
  14335. enumerable: true,
  14336. configurable: true
  14337. });
  14338. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14339. get: function () {
  14340. return this._areNormalsFrozen;
  14341. },
  14342. enumerable: true,
  14343. configurable: true
  14344. });
  14345. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14346. Mesh.prototype.freezeNormals = function () {
  14347. this._areNormalsFrozen = true;
  14348. };
  14349. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14350. Mesh.prototype.unfreezeNormals = function () {
  14351. this._areNormalsFrozen = false;
  14352. };
  14353. // Methods
  14354. Mesh.prototype._preActivate = function () {
  14355. var sceneRenderId = this.getScene().getRenderId();
  14356. if (this._preActivateId === sceneRenderId) {
  14357. return;
  14358. }
  14359. this._preActivateId = sceneRenderId;
  14360. this._visibleInstances = null;
  14361. };
  14362. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14363. if (!this._visibleInstances) {
  14364. this._visibleInstances = {};
  14365. this._visibleInstances.defaultRenderId = renderId;
  14366. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14367. }
  14368. if (!this._visibleInstances[renderId]) {
  14369. this._visibleInstances[renderId] = new Array();
  14370. }
  14371. this._visibleInstances[renderId].push(instance);
  14372. };
  14373. Mesh.prototype.refreshBoundingInfo = function () {
  14374. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14375. if (data) {
  14376. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14377. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14378. }
  14379. if (this.subMeshes) {
  14380. for (var index = 0; index < this.subMeshes.length; index++) {
  14381. this.subMeshes[index].refreshBoundingInfo();
  14382. }
  14383. }
  14384. this._updateBoundingInfo();
  14385. };
  14386. Mesh.prototype._createGlobalSubMesh = function () {
  14387. var totalVertices = this.getTotalVertices();
  14388. if (!totalVertices || !this.getIndices()) {
  14389. return null;
  14390. }
  14391. this.releaseSubMeshes();
  14392. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14393. };
  14394. Mesh.prototype.subdivide = function (count) {
  14395. if (count < 1) {
  14396. return;
  14397. }
  14398. var totalIndices = this.getTotalIndices();
  14399. var subdivisionSize = (totalIndices / count) | 0;
  14400. var offset = 0;
  14401. // Ensure that subdivisionSize is a multiple of 3
  14402. while (subdivisionSize % 3 !== 0) {
  14403. subdivisionSize++;
  14404. }
  14405. this.releaseSubMeshes();
  14406. for (var index = 0; index < count; index++) {
  14407. if (offset >= totalIndices) {
  14408. break;
  14409. }
  14410. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14411. offset += subdivisionSize;
  14412. }
  14413. this.synchronizeInstances();
  14414. };
  14415. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14416. if (kind instanceof Array) {
  14417. var temp = data;
  14418. data = kind;
  14419. kind = temp;
  14420. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  14421. }
  14422. if (!this._geometry) {
  14423. var vertexData = new BABYLON.VertexData();
  14424. vertexData.set(data, kind);
  14425. var scene = this.getScene();
  14426. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14427. }
  14428. else {
  14429. this._geometry.setVerticesData(kind, data, updatable, stride);
  14430. }
  14431. };
  14432. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14433. if (!this._geometry) {
  14434. return;
  14435. }
  14436. if (!makeItUnique) {
  14437. this._geometry.updateVerticesData(kind, data, updateExtends);
  14438. }
  14439. else {
  14440. this.makeGeometryUnique();
  14441. this.updateVerticesData(kind, data, updateExtends, false);
  14442. }
  14443. };
  14444. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14445. if (!this._geometry) {
  14446. return;
  14447. }
  14448. if (!makeItUnique) {
  14449. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14450. }
  14451. else {
  14452. this.makeGeometryUnique();
  14453. this.updateVerticesDataDirectly(kind, data, offset, false);
  14454. }
  14455. };
  14456. // Mesh positions update function :
  14457. // updates the mesh positions according to the positionFunction returned values.
  14458. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14459. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14460. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14461. if (computeNormals === void 0) { computeNormals = true; }
  14462. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14463. positionFunction(positions);
  14464. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14465. if (computeNormals) {
  14466. var indices = this.getIndices();
  14467. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14468. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14469. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14470. }
  14471. };
  14472. Mesh.prototype.makeGeometryUnique = function () {
  14473. if (!this._geometry) {
  14474. return;
  14475. }
  14476. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14477. geometry.applyToMesh(this);
  14478. };
  14479. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14480. if (!this._geometry) {
  14481. var vertexData = new BABYLON.VertexData();
  14482. vertexData.indices = indices;
  14483. var scene = this.getScene();
  14484. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14485. }
  14486. else {
  14487. this._geometry.setIndices(indices, totalVertices);
  14488. }
  14489. };
  14490. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14491. var engine = this.getScene().getEngine();
  14492. // Wireframe
  14493. var indexToBind;
  14494. switch (fillMode) {
  14495. case BABYLON.Material.PointFillMode:
  14496. indexToBind = null;
  14497. break;
  14498. case BABYLON.Material.WireFrameFillMode:
  14499. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14500. break;
  14501. default:
  14502. case BABYLON.Material.TriangleFillMode:
  14503. indexToBind = this._geometry.getIndexBuffer();
  14504. break;
  14505. }
  14506. // VBOs
  14507. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14508. };
  14509. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14510. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14511. return;
  14512. }
  14513. var engine = this.getScene().getEngine();
  14514. // Draw order
  14515. switch (fillMode) {
  14516. case BABYLON.Material.PointFillMode:
  14517. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14518. break;
  14519. case BABYLON.Material.WireFrameFillMode:
  14520. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14521. break;
  14522. default:
  14523. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14524. }
  14525. };
  14526. Mesh.prototype.registerBeforeRender = function (func) {
  14527. this._onBeforeRenderCallbacks.push(func);
  14528. };
  14529. Mesh.prototype.unregisterBeforeRender = function (func) {
  14530. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14531. if (index > -1) {
  14532. this._onBeforeRenderCallbacks.splice(index, 1);
  14533. }
  14534. };
  14535. Mesh.prototype.registerAfterRender = function (func) {
  14536. this._onAfterRenderCallbacks.push(func);
  14537. };
  14538. Mesh.prototype.unregisterAfterRender = function (func) {
  14539. var index = this._onAfterRenderCallbacks.indexOf(func);
  14540. if (index > -1) {
  14541. this._onAfterRenderCallbacks.splice(index, 1);
  14542. }
  14543. };
  14544. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14545. var scene = this.getScene();
  14546. this._batchCache.mustReturn = false;
  14547. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14548. this._batchCache.visibleInstances[subMeshId] = null;
  14549. if (this._visibleInstances) {
  14550. var currentRenderId = scene.getRenderId();
  14551. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  14552. var selfRenderId = this._renderId;
  14553. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  14554. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  14555. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  14556. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  14557. }
  14558. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  14559. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  14560. this._batchCache.mustReturn = true;
  14561. return this._batchCache;
  14562. }
  14563. if (currentRenderId !== selfRenderId) {
  14564. this._batchCache.renderSelf[subMeshId] = false;
  14565. }
  14566. }
  14567. this._renderIdForInstances[subMeshId] = currentRenderId;
  14568. }
  14569. return this._batchCache;
  14570. };
  14571. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  14572. var visibleInstances = batch.visibleInstances[subMesh._id];
  14573. var matricesCount = visibleInstances.length + 1;
  14574. var bufferSize = matricesCount * 16 * 4;
  14575. while (this._instancesBufferSize < bufferSize) {
  14576. this._instancesBufferSize *= 2;
  14577. }
  14578. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  14579. if (this._worldMatricesInstancesBuffer) {
  14580. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14581. }
  14582. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  14583. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  14584. }
  14585. var offset = 0;
  14586. var instancesCount = 0;
  14587. var world = this.getWorldMatrix();
  14588. if (batch.renderSelf[subMesh._id]) {
  14589. world.copyToArray(this._worldMatricesInstancesArray, offset);
  14590. offset += 16;
  14591. instancesCount++;
  14592. }
  14593. if (visibleInstances) {
  14594. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  14595. var instance = visibleInstances[instanceIndex];
  14596. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  14597. offset += 16;
  14598. instancesCount++;
  14599. }
  14600. }
  14601. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  14602. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  14603. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  14604. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  14605. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  14606. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  14607. this._draw(subMesh, fillMode, instancesCount);
  14608. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  14609. };
  14610. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  14611. var scene = this.getScene();
  14612. var engine = scene.getEngine();
  14613. if (hardwareInstancedRendering) {
  14614. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  14615. }
  14616. else {
  14617. if (batch.renderSelf[subMesh._id]) {
  14618. // Draw
  14619. if (onBeforeDraw) {
  14620. onBeforeDraw(false, this.getWorldMatrix());
  14621. }
  14622. this._draw(subMesh, fillMode);
  14623. }
  14624. if (batch.visibleInstances[subMesh._id]) {
  14625. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  14626. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  14627. // World
  14628. var world = instance.getWorldMatrix();
  14629. if (onBeforeDraw) {
  14630. onBeforeDraw(true, world);
  14631. }
  14632. // Draw
  14633. this._draw(subMesh, fillMode);
  14634. }
  14635. }
  14636. }
  14637. };
  14638. Mesh.prototype.render = function (subMesh) {
  14639. var scene = this.getScene();
  14640. // Managing instances
  14641. var batch = this._getInstancesRenderList(subMesh._id);
  14642. if (batch.mustReturn) {
  14643. return;
  14644. }
  14645. // Checking geometry state
  14646. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14647. return;
  14648. }
  14649. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14650. this._onBeforeRenderCallbacks[callbackIndex](this);
  14651. }
  14652. var engine = scene.getEngine();
  14653. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14654. // Material
  14655. var effectiveMaterial = subMesh.getMaterial();
  14656. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  14657. return;
  14658. }
  14659. // Outline - step 1
  14660. var savedDepthWrite = engine.getDepthWrite();
  14661. if (this.renderOutline) {
  14662. engine.setDepthWrite(false);
  14663. scene.getOutlineRenderer().render(subMesh, batch);
  14664. engine.setDepthWrite(savedDepthWrite);
  14665. }
  14666. effectiveMaterial._preBind();
  14667. var effect = effectiveMaterial.getEffect();
  14668. // Bind
  14669. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  14670. this._bind(subMesh, effect, fillMode);
  14671. var world = this.getWorldMatrix();
  14672. effectiveMaterial.bind(world, this);
  14673. // Draw
  14674. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  14675. if (isInstance) {
  14676. effectiveMaterial.bindOnlyWorldMatrix(world);
  14677. }
  14678. });
  14679. // Unbind
  14680. effectiveMaterial.unbind();
  14681. // Outline - step 2
  14682. if (this.renderOutline && savedDepthWrite) {
  14683. engine.setDepthWrite(true);
  14684. engine.setColorWrite(false);
  14685. scene.getOutlineRenderer().render(subMesh, batch);
  14686. engine.setColorWrite(true);
  14687. }
  14688. // Overlay
  14689. if (this.renderOverlay) {
  14690. var currentMode = engine.getAlphaMode();
  14691. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14692. scene.getOutlineRenderer().render(subMesh, batch, true);
  14693. engine.setAlphaMode(currentMode);
  14694. }
  14695. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14696. this._onAfterRenderCallbacks[callbackIndex](this);
  14697. }
  14698. };
  14699. Mesh.prototype.getEmittedParticleSystems = function () {
  14700. var results = new Array();
  14701. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14702. var particleSystem = this.getScene().particleSystems[index];
  14703. if (particleSystem.emitter === this) {
  14704. results.push(particleSystem);
  14705. }
  14706. }
  14707. return results;
  14708. };
  14709. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  14710. var results = new Array();
  14711. var descendants = this.getDescendants();
  14712. descendants.push(this);
  14713. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14714. var particleSystem = this.getScene().particleSystems[index];
  14715. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  14716. results.push(particleSystem);
  14717. }
  14718. }
  14719. return results;
  14720. };
  14721. Mesh.prototype.getChildren = function () {
  14722. var results = [];
  14723. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14724. var mesh = this.getScene().meshes[index];
  14725. if (mesh.parent === this) {
  14726. results.push(mesh);
  14727. }
  14728. }
  14729. return results;
  14730. };
  14731. Mesh.prototype._checkDelayState = function () {
  14732. var _this = this;
  14733. var that = this;
  14734. var scene = this.getScene();
  14735. if (this._geometry) {
  14736. this._geometry.load(scene);
  14737. }
  14738. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14739. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  14740. scene._addPendingData(that);
  14741. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  14742. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  14743. if (data instanceof ArrayBuffer) {
  14744. _this._delayLoadingFunction(data, _this);
  14745. }
  14746. else {
  14747. _this._delayLoadingFunction(JSON.parse(data), _this);
  14748. }
  14749. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  14750. scene._removePendingData(_this);
  14751. }, function () { }, scene.database, getBinaryData);
  14752. }
  14753. };
  14754. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  14755. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14756. return false;
  14757. }
  14758. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  14759. return false;
  14760. }
  14761. this._checkDelayState();
  14762. return true;
  14763. };
  14764. Mesh.prototype.setMaterialByID = function (id) {
  14765. var materials = this.getScene().materials;
  14766. for (var index = 0; index < materials.length; index++) {
  14767. if (materials[index].id === id) {
  14768. this.material = materials[index];
  14769. return;
  14770. }
  14771. }
  14772. // Multi
  14773. var multiMaterials = this.getScene().multiMaterials;
  14774. for (index = 0; index < multiMaterials.length; index++) {
  14775. if (multiMaterials[index].id === id) {
  14776. this.material = multiMaterials[index];
  14777. return;
  14778. }
  14779. }
  14780. };
  14781. Mesh.prototype.getAnimatables = function () {
  14782. var results = [];
  14783. if (this.material) {
  14784. results.push(this.material);
  14785. }
  14786. if (this.skeleton) {
  14787. results.push(this.skeleton);
  14788. }
  14789. return results;
  14790. };
  14791. // Geometry
  14792. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  14793. // Position
  14794. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  14795. return;
  14796. }
  14797. this._resetPointsArrayCache();
  14798. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14799. var temp = [];
  14800. for (var index = 0; index < data.length; index += 3) {
  14801. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  14802. }
  14803. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  14804. // Normals
  14805. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14806. return;
  14807. }
  14808. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14809. temp = [];
  14810. for (index = 0; index < data.length; index += 3) {
  14811. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  14812. }
  14813. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  14814. };
  14815. // Cache
  14816. Mesh.prototype._resetPointsArrayCache = function () {
  14817. this._positions = null;
  14818. };
  14819. Mesh.prototype._generatePointsArray = function () {
  14820. if (this._positions)
  14821. return true;
  14822. this._positions = [];
  14823. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14824. if (!data) {
  14825. return false;
  14826. }
  14827. for (var index = 0; index < data.length; index += 3) {
  14828. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  14829. }
  14830. return true;
  14831. };
  14832. // Clone
  14833. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14834. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  14835. };
  14836. // Dispose
  14837. Mesh.prototype.dispose = function (doNotRecurse) {
  14838. if (this._geometry) {
  14839. this._geometry.releaseForMesh(this, true);
  14840. }
  14841. // Instances
  14842. if (this._worldMatricesInstancesBuffer) {
  14843. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14844. this._worldMatricesInstancesBuffer = null;
  14845. }
  14846. while (this.instances.length) {
  14847. this.instances[0].dispose();
  14848. }
  14849. _super.prototype.dispose.call(this, doNotRecurse);
  14850. };
  14851. // Geometric tools
  14852. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  14853. var _this = this;
  14854. var scene = this.getScene();
  14855. var onload = function (img) {
  14856. // Getting height map data
  14857. var canvas = document.createElement("canvas");
  14858. var context = canvas.getContext("2d");
  14859. var heightMapWidth = img.width;
  14860. var heightMapHeight = img.height;
  14861. canvas.width = heightMapWidth;
  14862. canvas.height = heightMapHeight;
  14863. context.drawImage(img, 0, 0);
  14864. // Create VertexData from map data
  14865. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  14866. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  14867. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  14868. //execute success callback, if set
  14869. if (onSuccess) {
  14870. onSuccess(_this);
  14871. }
  14872. };
  14873. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  14874. };
  14875. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  14876. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  14877. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  14878. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14879. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  14880. return;
  14881. }
  14882. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14883. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14884. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14885. var position = BABYLON.Vector3.Zero();
  14886. var normal = BABYLON.Vector3.Zero();
  14887. var uv = BABYLON.Vector2.Zero();
  14888. for (var index = 0; index < positions.length; index += 3) {
  14889. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  14890. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  14891. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  14892. // Compute height
  14893. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  14894. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  14895. var pos = (u + v * heightMapWidth) * 4;
  14896. var r = buffer[pos] / 255.0;
  14897. var g = buffer[pos + 1] / 255.0;
  14898. var b = buffer[pos + 2] / 255.0;
  14899. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  14900. normal.normalize();
  14901. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  14902. position = position.add(normal);
  14903. position.toArray(positions, index);
  14904. }
  14905. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  14906. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  14907. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  14908. };
  14909. Mesh.prototype.convertToFlatShadedMesh = function () {
  14910. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  14911. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  14912. var kinds = this.getVerticesDataKinds();
  14913. var vbs = [];
  14914. var data = [];
  14915. var newdata = [];
  14916. var updatableNormals = false;
  14917. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14918. var kind = kinds[kindIndex];
  14919. var vertexBuffer = this.getVertexBuffer(kind);
  14920. if (kind === BABYLON.VertexBuffer.NormalKind) {
  14921. updatableNormals = vertexBuffer.isUpdatable();
  14922. kinds.splice(kindIndex, 1);
  14923. kindIndex--;
  14924. continue;
  14925. }
  14926. vbs[kind] = vertexBuffer;
  14927. data[kind] = vbs[kind].getData();
  14928. newdata[kind] = [];
  14929. }
  14930. // Save previous submeshes
  14931. var previousSubmeshes = this.subMeshes.slice(0);
  14932. var indices = this.getIndices();
  14933. var totalIndices = this.getTotalIndices();
  14934. // Generating unique vertices per face
  14935. for (var index = 0; index < totalIndices; index++) {
  14936. var vertexIndex = indices[index];
  14937. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14938. kind = kinds[kindIndex];
  14939. var stride = vbs[kind].getStrideSize();
  14940. for (var offset = 0; offset < stride; offset++) {
  14941. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  14942. }
  14943. }
  14944. }
  14945. // Updating faces & normal
  14946. var normals = [];
  14947. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  14948. for (index = 0; index < totalIndices; index += 3) {
  14949. indices[index] = index;
  14950. indices[index + 1] = index + 1;
  14951. indices[index + 2] = index + 2;
  14952. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  14953. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  14954. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  14955. var p1p2 = p1.subtract(p2);
  14956. var p3p2 = p3.subtract(p2);
  14957. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  14958. // Store same normals for every vertex
  14959. for (var localIndex = 0; localIndex < 3; localIndex++) {
  14960. normals.push(normal.x);
  14961. normals.push(normal.y);
  14962. normals.push(normal.z);
  14963. }
  14964. }
  14965. this.setIndices(indices);
  14966. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  14967. // Updating vertex buffers
  14968. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14969. kind = kinds[kindIndex];
  14970. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  14971. }
  14972. // Updating submeshes
  14973. this.releaseSubMeshes();
  14974. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  14975. var previousOne = previousSubmeshes[submeshIndex];
  14976. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  14977. }
  14978. this.synchronizeInstances();
  14979. };
  14980. // Instances
  14981. Mesh.prototype.createInstance = function (name) {
  14982. return new BABYLON.InstancedMesh(name, this);
  14983. };
  14984. Mesh.prototype.synchronizeInstances = function () {
  14985. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  14986. var instance = this.instances[instanceIndex];
  14987. instance._syncSubMeshes();
  14988. }
  14989. };
  14990. /**
  14991. * Simplify the mesh according to the given array of settings.
  14992. * Function will return immediately and will simplify async.
  14993. * @param settings a collection of simplification settings.
  14994. * @param parallelProcessing should all levels calculate parallel or one after the other.
  14995. * @param type the type of simplification to run.
  14996. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  14997. */
  14998. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  14999. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15000. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15001. this.getScene().simplificationQueue.addTask({
  15002. settings: settings,
  15003. parallelProcessing: parallelProcessing,
  15004. mesh: this,
  15005. simplificationType: simplificationType,
  15006. successCallback: successCallback
  15007. });
  15008. };
  15009. /**
  15010. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15011. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15012. * This should be used together with the simplification to avoid disappearing triangles.
  15013. * @param successCallback an optional success callback to be called after the optimization finished.
  15014. */
  15015. Mesh.prototype.optimizeIndices = function (successCallback) {
  15016. var _this = this;
  15017. var indices = this.getIndices();
  15018. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15019. var vectorPositions = [];
  15020. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15021. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15022. }
  15023. var dupes = [];
  15024. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15025. var realPos = vectorPositions.length - 1 - iteration;
  15026. var testedPosition = vectorPositions[realPos];
  15027. for (var j = 0; j < realPos; ++j) {
  15028. var againstPosition = vectorPositions[j];
  15029. if (testedPosition.equals(againstPosition)) {
  15030. dupes[realPos] = j;
  15031. break;
  15032. }
  15033. }
  15034. }, function () {
  15035. for (var i = 0; i < indices.length; ++i) {
  15036. indices[i] = dupes[indices[i]] || indices[i];
  15037. }
  15038. //indices are now reordered
  15039. var originalSubMeshes = _this.subMeshes.slice(0);
  15040. _this.setIndices(indices);
  15041. _this.subMeshes = originalSubMeshes;
  15042. if (successCallback) {
  15043. successCallback(_this);
  15044. }
  15045. });
  15046. };
  15047. // Statics
  15048. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  15049. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15050. if (ribbonInstance === void 0) { ribbonInstance = null; }
  15051. if (ribbonInstance) {
  15052. // positionFunction : ribbon case
  15053. // only pathArray and sideOrientation parameters are taken into account for positions update
  15054. var positionFunction = function (positions) {
  15055. var minlg = pathArray[0].length;
  15056. var i = 0;
  15057. var ns = (ribbonInstance.sideOrientation === Mesh.DOUBLESIDE) ? 2 : 1;
  15058. for (var si = 1; si <= ns; si++) {
  15059. for (var p = 0; p < pathArray.length; p++) {
  15060. var path = pathArray[p];
  15061. var l = path.length;
  15062. minlg = (minlg < l) ? minlg : l;
  15063. var j = 0;
  15064. while (j < minlg) {
  15065. positions[i] = path[j].x;
  15066. positions[i + 1] = path[j].y;
  15067. positions[i + 2] = path[j].z;
  15068. j++;
  15069. i += 3;
  15070. }
  15071. }
  15072. }
  15073. };
  15074. var computeNormals = !(ribbonInstance.areNormalsFrozen);
  15075. ribbonInstance.updateMeshPositions(positionFunction, computeNormals);
  15076. return ribbonInstance;
  15077. }
  15078. else {
  15079. var ribbon = new Mesh(name, scene);
  15080. ribbon.sideOrientation = sideOrientation;
  15081. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  15082. vertexData.applyToMesh(ribbon, updatable);
  15083. return ribbon;
  15084. }
  15085. };
  15086. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  15087. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15088. var disc = new Mesh(name, scene);
  15089. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  15090. vertexData.applyToMesh(disc, updatable);
  15091. return disc;
  15092. };
  15093. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  15094. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15095. var box = new Mesh(name, scene);
  15096. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  15097. vertexData.applyToMesh(box, updatable);
  15098. return box;
  15099. };
  15100. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  15101. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15102. var sphere = new Mesh(name, scene);
  15103. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  15104. vertexData.applyToMesh(sphere, updatable);
  15105. return sphere;
  15106. };
  15107. // Cylinder and cone (Code inspired by SharpDX.org)
  15108. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15109. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15110. // subdivisions is a new parameter, we need to support old signature
  15111. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15112. if (scene !== undefined) {
  15113. updatable = scene;
  15114. }
  15115. scene = subdivisions;
  15116. subdivisions = 1;
  15117. }
  15118. var cylinder = new Mesh(name, scene);
  15119. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  15120. vertexData.applyToMesh(cylinder, updatable);
  15121. return cylinder;
  15122. };
  15123. // Torus (Code from SharpDX.org)
  15124. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  15125. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15126. var torus = new Mesh(name, scene);
  15127. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  15128. vertexData.applyToMesh(torus, updatable);
  15129. return torus;
  15130. };
  15131. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15132. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15133. var torusKnot = new Mesh(name, scene);
  15134. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  15135. vertexData.applyToMesh(torusKnot, updatable);
  15136. return torusKnot;
  15137. };
  15138. // Lines
  15139. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  15140. if (linesInstance === void 0) { linesInstance = null; }
  15141. if (linesInstance) {
  15142. var positionFunction = function (positions) {
  15143. var i = 0;
  15144. for (var p = 0; p < points.length; p++) {
  15145. positions[i] = points[p].x;
  15146. positions[i + 1] = points[p].y;
  15147. positions[i + 2] = points[p].z;
  15148. i += 3;
  15149. }
  15150. };
  15151. linesInstance.updateMeshPositions(positionFunction, false);
  15152. return linesInstance;
  15153. }
  15154. // lines creation
  15155. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  15156. var vertexData = BABYLON.VertexData.CreateLines(points);
  15157. vertexData.applyToMesh(lines, updatable);
  15158. return lines;
  15159. };
  15160. // Dashed Lines
  15161. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, linesInstance) {
  15162. if (linesInstance === void 0) { linesInstance = null; }
  15163. if (linesInstance) {
  15164. var positionFunction = function (positions) {
  15165. var curvect = BABYLON.Vector3.Zero();
  15166. var nbSeg = positions.length / 6;
  15167. var lg = 0;
  15168. var nb = 0;
  15169. var shft = 0;
  15170. var dashshft = 0;
  15171. var curshft = 0;
  15172. var p = 0;
  15173. var i = 0;
  15174. var j = 0;
  15175. for (i = 0; i < points.length - 1; i++) {
  15176. points[i + 1].subtractToRef(points[i], curvect);
  15177. lg += curvect.length();
  15178. }
  15179. shft = lg / nbSeg;
  15180. dashshft = linesInstance.dashSize * shft / (linesInstance.dashSize + linesInstance.gapSize);
  15181. for (i = 0; i < points.length - 1; i++) {
  15182. points[i + 1].subtractToRef(points[i], curvect);
  15183. nb = Math.floor(curvect.length() / shft);
  15184. curvect.normalize();
  15185. j = 0;
  15186. while (j < nb && p < positions.length) {
  15187. curshft = shft * j;
  15188. positions[p] = points[i].x + curshft * curvect.x;
  15189. positions[p + 1] = points[i].y + curshft * curvect.y;
  15190. positions[p + 2] = points[i].z + curshft * curvect.z;
  15191. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  15192. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  15193. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  15194. p += 6;
  15195. j++;
  15196. }
  15197. }
  15198. while (p < positions.length) {
  15199. positions[p] = points[i].x;
  15200. positions[p + 1] = points[i].y;
  15201. positions[p + 2] = points[i].z;
  15202. p += 3;
  15203. }
  15204. };
  15205. linesInstance.updateMeshPositions(positionFunction, false);
  15206. return linesInstance;
  15207. }
  15208. // dashed lines creation
  15209. var dashedLines = new BABYLON.LinesMesh(name, scene, updatable);
  15210. var vertexData = BABYLON.VertexData.CreateDashedLines(points, dashSize, gapSize, dashNb);
  15211. vertexData.applyToMesh(dashedLines, updatable);
  15212. dashedLines.dashSize = dashSize;
  15213. dashedLines.gapSize = gapSize;
  15214. return dashedLines;
  15215. };
  15216. // Extrusion
  15217. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15218. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15219. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15220. scale = scale || 1;
  15221. rotation = rotation || 0;
  15222. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, extrudedInstance);
  15223. return extruded;
  15224. };
  15225. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15226. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15227. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15228. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, extrudedInstance);
  15229. return extrudedCustom;
  15230. };
  15231. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  15232. // extrusion geometry
  15233. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  15234. var tangents = path3D.getTangents();
  15235. var normals = path3D.getNormals();
  15236. var binormals = path3D.getBinormals();
  15237. var distances = path3D.getDistances();
  15238. var angle = 0;
  15239. var returnScale = function (i, distance) { return scale; };
  15240. var returnRotation = function (i, distance) { return rotation; };
  15241. var rotate = custom ? rotateFunction : returnRotation;
  15242. var scl = custom ? scaleFunction : returnScale;
  15243. var index = 0;
  15244. for (var i = 0; i < curve.length; i++) {
  15245. var shapePath = new Array();
  15246. var angleStep = rotate(i, distances[i]);
  15247. var scaleRatio = scl(i, distances[i]);
  15248. for (var p = 0; p < shape.length; p++) {
  15249. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  15250. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  15251. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  15252. shapePath.push(rotated);
  15253. }
  15254. shapePaths[index] = shapePath;
  15255. angle += angleStep;
  15256. index++;
  15257. }
  15258. // cap
  15259. var capPath = function (shapePath) {
  15260. var pointCap = Array();
  15261. var barycenter = BABYLON.Vector3.Zero();
  15262. var i;
  15263. for (i = 0; i < shapePath.length; i++) {
  15264. barycenter.addInPlace(shapePath[i]);
  15265. }
  15266. barycenter.scaleInPlace(1 / shapePath.length);
  15267. for (i = 0; i < shapePath.length; i++) {
  15268. pointCap.push(barycenter);
  15269. }
  15270. return pointCap;
  15271. };
  15272. switch (cap) {
  15273. case Mesh.NO_CAP:
  15274. break;
  15275. case Mesh.CAP_START:
  15276. shapePaths.unshift(capPath(shapePaths[0]));
  15277. break;
  15278. case Mesh.CAP_END:
  15279. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15280. break;
  15281. case Mesh.CAP_ALL:
  15282. shapePaths.unshift(capPath(shapePaths[0]));
  15283. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15284. break;
  15285. default:
  15286. break;
  15287. }
  15288. return shapePaths;
  15289. };
  15290. if (instance) {
  15291. var path3D = (instance.path3D).update(curve);
  15292. var pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  15293. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  15294. return instance;
  15295. }
  15296. // extruded shape creation
  15297. var path3D = new BABYLON.Path3D(curve);
  15298. var newShapePaths = new Array();
  15299. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15300. var pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  15301. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  15302. extrudedGeneric.pathArray = pathArray;
  15303. extrudedGeneric.path3D = path3D;
  15304. extrudedGeneric.cap = cap;
  15305. return extrudedGeneric;
  15306. };
  15307. // Lathe
  15308. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  15309. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15310. radius = radius || 1;
  15311. tessellation = tessellation || radius * 60;
  15312. var pi2 = Math.PI * 2;
  15313. var Y = BABYLON.Axis.Y;
  15314. var shapeLathe = new Array();
  15315. // first rotatable point
  15316. var i = 0;
  15317. while (shape[i].x === 0) {
  15318. i++;
  15319. }
  15320. var pt = shape[i];
  15321. for (i = 0; i < shape.length; i++) {
  15322. shapeLathe.push(shape[i].subtract(pt));
  15323. }
  15324. // circle path
  15325. var step = pi2 / tessellation;
  15326. var rotated;
  15327. var path = new Array();
  15328. ;
  15329. for (i = 0; i < tessellation; i++) {
  15330. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  15331. path.push(rotated);
  15332. }
  15333. path.push(path[0]);
  15334. // extrusion
  15335. var scaleFunction = function () { return 1; };
  15336. var rotateFunction = function () { return 0; };
  15337. var lathe = Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, true, false, Mesh.NO_CAP, scene, updatable, sideOrientation);
  15338. return lathe;
  15339. };
  15340. // Plane & ground
  15341. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  15342. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15343. var plane = new Mesh(name, scene);
  15344. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  15345. vertexData.applyToMesh(plane, updatable);
  15346. return plane;
  15347. };
  15348. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  15349. var ground = new BABYLON.GroundMesh(name, scene);
  15350. ground._setReady(false);
  15351. ground._subdivisions = subdivisions;
  15352. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  15353. vertexData.applyToMesh(ground, updatable);
  15354. ground._setReady(true);
  15355. return ground;
  15356. };
  15357. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15358. var tiledGround = new Mesh(name, scene);
  15359. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  15360. vertexData.applyToMesh(tiledGround, updatable);
  15361. return tiledGround;
  15362. };
  15363. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15364. var ground = new BABYLON.GroundMesh(name, scene);
  15365. ground._subdivisions = subdivisions;
  15366. ground._setReady(false);
  15367. var onload = function (img) {
  15368. // Getting height map data
  15369. var canvas = document.createElement("canvas");
  15370. var context = canvas.getContext("2d");
  15371. var heightMapWidth = img.width;
  15372. var heightMapHeight = img.height;
  15373. canvas.width = heightMapWidth;
  15374. canvas.height = heightMapHeight;
  15375. context.drawImage(img, 0, 0);
  15376. // Create VertexData from map data
  15377. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15378. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15379. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  15380. vertexData.applyToMesh(ground, updatable);
  15381. ground._setReady(true);
  15382. //execute ready callback, if set
  15383. if (onReady) {
  15384. onReady(ground);
  15385. }
  15386. };
  15387. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15388. return ground;
  15389. };
  15390. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, tubeInstance) {
  15391. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15392. if (tubeInstance === void 0) { tubeInstance = null; }
  15393. // tube geometry
  15394. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap) {
  15395. var tangents = path3D.getTangents();
  15396. var normals = path3D.getNormals();
  15397. var distances = path3D.getDistances();
  15398. var pi2 = Math.PI * 2;
  15399. var step = pi2 / tessellation;
  15400. var returnRadius = function (i, distance) { return radius; };
  15401. var radiusFunctionFinal = radiusFunction || returnRadius;
  15402. var circlePath;
  15403. var rad;
  15404. var normal;
  15405. var rotated;
  15406. var rotationMatrix;
  15407. var index = 0;
  15408. for (var i = 0; i < path.length; i++) {
  15409. rad = radiusFunctionFinal(i, distances[i]); // current radius
  15410. circlePath = Array(); // current circle array
  15411. normal = normals[i]; // current normal
  15412. for (var t = 0; t < tessellation; t++) {
  15413. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], step * t);
  15414. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  15415. circlePath.push(rotated);
  15416. }
  15417. circlePath.push(circlePath[0]);
  15418. circlePaths[index] = circlePath;
  15419. index++;
  15420. }
  15421. // cap
  15422. var capPath = function (nbPoints, pathIndex) {
  15423. var pointCap = Array();
  15424. for (var i = 0; i < nbPoints; i++) {
  15425. pointCap.push(path[pathIndex]);
  15426. }
  15427. return pointCap;
  15428. };
  15429. switch (cap) {
  15430. case Mesh.NO_CAP:
  15431. break;
  15432. case Mesh.CAP_START:
  15433. circlePaths.unshift(capPath(tessellation + 1, 0));
  15434. break;
  15435. case Mesh.CAP_END:
  15436. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  15437. break;
  15438. case Mesh.CAP_ALL:
  15439. circlePaths.unshift(capPath(tessellation + 1, 0));
  15440. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  15441. break;
  15442. default:
  15443. break;
  15444. }
  15445. return circlePaths;
  15446. };
  15447. if (tubeInstance) {
  15448. var path3D = (tubeInstance.path3D).update(path);
  15449. var pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction, tubeInstance.cap);
  15450. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  15451. return tubeInstance;
  15452. }
  15453. // tube creation
  15454. var path3D = new BABYLON.Path3D(path);
  15455. var newPathArray = new Array();
  15456. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15457. var pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap);
  15458. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  15459. tube.pathArray = pathArray;
  15460. tube.path3D = path3D;
  15461. tube.tessellation = tessellation;
  15462. tube.cap = cap;
  15463. return tube;
  15464. };
  15465. // Decals
  15466. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  15467. if (angle === void 0) { angle = 0; }
  15468. var indices = sourceMesh.getIndices();
  15469. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15470. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15471. // Getting correct rotation
  15472. if (!normal) {
  15473. var target = new BABYLON.Vector3(0, 0, 1);
  15474. var camera = sourceMesh.getScene().activeCamera;
  15475. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  15476. normal = camera.globalPosition.subtract(cameraWorldTarget);
  15477. }
  15478. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  15479. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  15480. var pitch = Math.atan2(normal.y, len);
  15481. // Matrix
  15482. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  15483. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  15484. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  15485. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  15486. var vertexData = new BABYLON.VertexData();
  15487. vertexData.indices = [];
  15488. vertexData.positions = [];
  15489. vertexData.normals = [];
  15490. vertexData.uvs = [];
  15491. var currentVertexDataIndex = 0;
  15492. var extractDecalVector3 = function (indexId) {
  15493. var vertexId = indices[indexId];
  15494. var result = new BABYLON.PositionNormalVertex();
  15495. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  15496. // Send vector to decal local world
  15497. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  15498. // Get normal
  15499. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  15500. return result;
  15501. };
  15502. // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  15503. var clip = function (vertices, axis) {
  15504. if (vertices.length === 0) {
  15505. return vertices;
  15506. }
  15507. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  15508. var clipVertices = function (v0, v1) {
  15509. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  15510. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  15511. };
  15512. var result = new Array();
  15513. for (var index = 0; index < vertices.length; index += 3) {
  15514. var v1Out;
  15515. var v2Out;
  15516. var v3Out;
  15517. var total = 0;
  15518. var nV1, nV2, nV3, nV4;
  15519. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  15520. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  15521. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  15522. v1Out = d1 > 0;
  15523. v2Out = d2 > 0;
  15524. v3Out = d3 > 0;
  15525. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  15526. switch (total) {
  15527. case 0:
  15528. result.push(vertices[index]);
  15529. result.push(vertices[index + 1]);
  15530. result.push(vertices[index + 2]);
  15531. break;
  15532. case 1:
  15533. if (v1Out) {
  15534. nV1 = vertices[index + 1];
  15535. nV2 = vertices[index + 2];
  15536. nV3 = clipVertices(vertices[index], nV1);
  15537. nV4 = clipVertices(vertices[index], nV2);
  15538. }
  15539. if (v2Out) {
  15540. nV1 = vertices[index];
  15541. nV2 = vertices[index + 2];
  15542. nV3 = clipVertices(vertices[index + 1], nV1);
  15543. nV4 = clipVertices(vertices[index + 1], nV2);
  15544. result.push(nV3);
  15545. result.push(nV2.clone());
  15546. result.push(nV1.clone());
  15547. result.push(nV2.clone());
  15548. result.push(nV3.clone());
  15549. result.push(nV4);
  15550. break;
  15551. }
  15552. if (v3Out) {
  15553. nV1 = vertices[index];
  15554. nV2 = vertices[index + 1];
  15555. nV3 = clipVertices(vertices[index + 2], nV1);
  15556. nV4 = clipVertices(vertices[index + 2], nV2);
  15557. }
  15558. result.push(nV1.clone());
  15559. result.push(nV2.clone());
  15560. result.push(nV3);
  15561. result.push(nV4);
  15562. result.push(nV3.clone());
  15563. result.push(nV2.clone());
  15564. break;
  15565. case 2:
  15566. if (!v1Out) {
  15567. nV1 = vertices[index].clone();
  15568. nV2 = clipVertices(nV1, vertices[index + 1]);
  15569. nV3 = clipVertices(nV1, vertices[index + 2]);
  15570. result.push(nV1);
  15571. result.push(nV2);
  15572. result.push(nV3);
  15573. }
  15574. if (!v2Out) {
  15575. nV1 = vertices[index + 1].clone();
  15576. nV2 = clipVertices(nV1, vertices[index + 2]);
  15577. nV3 = clipVertices(nV1, vertices[index]);
  15578. result.push(nV1);
  15579. result.push(nV2);
  15580. result.push(nV3);
  15581. }
  15582. if (!v3Out) {
  15583. nV1 = vertices[index + 2].clone();
  15584. nV2 = clipVertices(nV1, vertices[index]);
  15585. nV3 = clipVertices(nV1, vertices[index + 1]);
  15586. result.push(nV1);
  15587. result.push(nV2);
  15588. result.push(nV3);
  15589. }
  15590. break;
  15591. case 3:
  15592. break;
  15593. }
  15594. }
  15595. return result;
  15596. };
  15597. for (var index = 0; index < indices.length; index += 3) {
  15598. var faceVertices = new Array();
  15599. faceVertices.push(extractDecalVector3(index));
  15600. faceVertices.push(extractDecalVector3(index + 1));
  15601. faceVertices.push(extractDecalVector3(index + 2));
  15602. // Clip
  15603. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  15604. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  15605. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  15606. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  15607. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  15608. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  15609. if (faceVertices.length === 0) {
  15610. continue;
  15611. }
  15612. // Add UVs and get back to world
  15613. var localRotationMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle);
  15614. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  15615. var vertex = faceVertices[vIndex];
  15616. vertexData.indices.push(currentVertexDataIndex);
  15617. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  15618. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  15619. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  15620. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  15621. currentVertexDataIndex++;
  15622. }
  15623. }
  15624. // Return mesh
  15625. var decal = new Mesh(name, sourceMesh.getScene());
  15626. vertexData.applyToMesh(decal);
  15627. decal.position = position.clone();
  15628. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  15629. return decal;
  15630. };
  15631. // Tools
  15632. Mesh.MinMax = function (meshes) {
  15633. var minVector = null;
  15634. var maxVector = null;
  15635. for (var i in meshes) {
  15636. var mesh = meshes[i];
  15637. var boundingBox = mesh.getBoundingInfo().boundingBox;
  15638. if (!minVector) {
  15639. minVector = boundingBox.minimumWorld;
  15640. maxVector = boundingBox.maximumWorld;
  15641. continue;
  15642. }
  15643. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  15644. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  15645. }
  15646. return {
  15647. min: minVector,
  15648. max: maxVector
  15649. };
  15650. };
  15651. Mesh.Center = function (meshesOrMinMaxVector) {
  15652. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  15653. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  15654. };
  15655. /**
  15656. * Merge the array of meshes into a single mesh for performance reasons.
  15657. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  15658. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  15659. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  15660. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  15661. */
  15662. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  15663. if (disposeSource === void 0) { disposeSource = true; }
  15664. if (!allow32BitsIndices) {
  15665. var totalVertices = 0;
  15666. // Counting vertices
  15667. for (var index = 0; index < meshes.length; index++) {
  15668. if (meshes[index]) {
  15669. totalVertices += meshes[index].getTotalVertices();
  15670. if (totalVertices > 65536) {
  15671. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  15672. return null;
  15673. }
  15674. }
  15675. }
  15676. }
  15677. // Merge
  15678. var vertexData;
  15679. var otherVertexData;
  15680. var source;
  15681. for (index = 0; index < meshes.length; index++) {
  15682. if (meshes[index]) {
  15683. meshes[index].computeWorldMatrix(true);
  15684. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  15685. otherVertexData.transform(meshes[index].getWorldMatrix());
  15686. if (vertexData) {
  15687. vertexData.merge(otherVertexData);
  15688. }
  15689. else {
  15690. vertexData = otherVertexData;
  15691. source = meshes[index];
  15692. }
  15693. }
  15694. }
  15695. if (!meshSubclass) {
  15696. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  15697. }
  15698. vertexData.applyToMesh(meshSubclass);
  15699. // Setting properties
  15700. meshSubclass.material = source.material;
  15701. meshSubclass.checkCollisions = source.checkCollisions;
  15702. // Cleaning
  15703. if (disposeSource) {
  15704. for (index = 0; index < meshes.length; index++) {
  15705. if (meshes[index]) {
  15706. meshes[index].dispose();
  15707. }
  15708. }
  15709. }
  15710. return meshSubclass;
  15711. };
  15712. // Consts
  15713. Mesh._FRONTSIDE = 0;
  15714. Mesh._BACKSIDE = 1;
  15715. Mesh._DOUBLESIDE = 2;
  15716. Mesh._DEFAULTSIDE = 0;
  15717. Mesh._NO_CAP = 0;
  15718. Mesh._CAP_START = 1;
  15719. Mesh._CAP_END = 2;
  15720. Mesh._CAP_ALL = 3;
  15721. return Mesh;
  15722. })(BABYLON.AbstractMesh);
  15723. BABYLON.Mesh = Mesh;
  15724. })(BABYLON || (BABYLON = {}));
  15725. //# sourceMappingURL=babylon.mesh.js.map
  15726. var BABYLON;
  15727. (function (BABYLON) {
  15728. var SubMesh = (function () {
  15729. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  15730. if (createBoundingBox === void 0) { createBoundingBox = true; }
  15731. this.materialIndex = materialIndex;
  15732. this.verticesStart = verticesStart;
  15733. this.verticesCount = verticesCount;
  15734. this.indexStart = indexStart;
  15735. this.indexCount = indexCount;
  15736. this._renderId = 0;
  15737. this._mesh = mesh;
  15738. this._renderingMesh = renderingMesh || mesh;
  15739. mesh.subMeshes.push(this);
  15740. this._trianglePlanes = [];
  15741. this._id = mesh.subMeshes.length - 1;
  15742. if (createBoundingBox) {
  15743. this.refreshBoundingInfo();
  15744. mesh.computeWorldMatrix(true);
  15745. }
  15746. }
  15747. SubMesh.prototype.getBoundingInfo = function () {
  15748. return this._boundingInfo;
  15749. };
  15750. SubMesh.prototype.getMesh = function () {
  15751. return this._mesh;
  15752. };
  15753. SubMesh.prototype.getRenderingMesh = function () {
  15754. return this._renderingMesh;
  15755. };
  15756. SubMesh.prototype.getMaterial = function () {
  15757. var rootMaterial = this._renderingMesh.material;
  15758. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  15759. var multiMaterial = rootMaterial;
  15760. return multiMaterial.getSubMaterial(this.materialIndex);
  15761. }
  15762. if (!rootMaterial) {
  15763. return this._mesh.getScene().defaultMaterial;
  15764. }
  15765. return rootMaterial;
  15766. };
  15767. // Methods
  15768. SubMesh.prototype.refreshBoundingInfo = function () {
  15769. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15770. if (!data) {
  15771. this._boundingInfo = this._mesh._boundingInfo;
  15772. return;
  15773. }
  15774. var indices = this._renderingMesh.getIndices();
  15775. var extend;
  15776. if (this.indexStart === 0 && this.indexCount === indices.length) {
  15777. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  15778. }
  15779. else {
  15780. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  15781. }
  15782. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15783. };
  15784. SubMesh.prototype._checkCollision = function (collider) {
  15785. return this._boundingInfo._checkCollision(collider);
  15786. };
  15787. SubMesh.prototype.updateBoundingInfo = function (world) {
  15788. if (!this._boundingInfo) {
  15789. this.refreshBoundingInfo();
  15790. }
  15791. this._boundingInfo._update(world);
  15792. };
  15793. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  15794. return this._boundingInfo.isInFrustum(frustumPlanes);
  15795. };
  15796. SubMesh.prototype.render = function () {
  15797. this._renderingMesh.render(this);
  15798. };
  15799. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  15800. if (!this._linesIndexBuffer) {
  15801. var linesIndices = [];
  15802. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15803. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  15804. }
  15805. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  15806. this.linesIndexCount = linesIndices.length;
  15807. }
  15808. return this._linesIndexBuffer;
  15809. };
  15810. SubMesh.prototype.canIntersects = function (ray) {
  15811. return ray.intersectsBox(this._boundingInfo.boundingBox);
  15812. };
  15813. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  15814. var intersectInfo = null;
  15815. // Triangles test
  15816. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15817. var p0 = positions[indices[index]];
  15818. var p1 = positions[indices[index + 1]];
  15819. var p2 = positions[indices[index + 2]];
  15820. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  15821. if (currentIntersectInfo) {
  15822. if (currentIntersectInfo.distance < 0) {
  15823. continue;
  15824. }
  15825. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15826. intersectInfo = currentIntersectInfo;
  15827. intersectInfo.faceId = index / 3;
  15828. if (fastCheck) {
  15829. break;
  15830. }
  15831. }
  15832. }
  15833. }
  15834. return intersectInfo;
  15835. };
  15836. // Clone
  15837. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  15838. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  15839. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  15840. return result;
  15841. };
  15842. // Dispose
  15843. SubMesh.prototype.dispose = function () {
  15844. if (this._linesIndexBuffer) {
  15845. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  15846. this._linesIndexBuffer = null;
  15847. }
  15848. // Remove from mesh
  15849. var index = this._mesh.subMeshes.indexOf(this);
  15850. this._mesh.subMeshes.splice(index, 1);
  15851. };
  15852. // Statics
  15853. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  15854. var minVertexIndex = Number.MAX_VALUE;
  15855. var maxVertexIndex = -Number.MAX_VALUE;
  15856. renderingMesh = renderingMesh || mesh;
  15857. var indices = renderingMesh.getIndices();
  15858. for (var index = startIndex; index < startIndex + indexCount; index++) {
  15859. var vertexIndex = indices[index];
  15860. if (vertexIndex < minVertexIndex)
  15861. minVertexIndex = vertexIndex;
  15862. if (vertexIndex > maxVertexIndex)
  15863. maxVertexIndex = vertexIndex;
  15864. }
  15865. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  15866. };
  15867. return SubMesh;
  15868. })();
  15869. BABYLON.SubMesh = SubMesh;
  15870. })(BABYLON || (BABYLON = {}));
  15871. //# sourceMappingURL=babylon.subMesh.js.map
  15872. var BABYLON;
  15873. (function (BABYLON) {
  15874. var BaseTexture = (function () {
  15875. function BaseTexture(scene) {
  15876. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  15877. this.hasAlpha = false;
  15878. this.getAlphaFromRGB = false;
  15879. this.level = 1;
  15880. this.isCube = false;
  15881. this.isRenderTarget = false;
  15882. this.animations = new Array();
  15883. this.coordinatesIndex = 0;
  15884. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  15885. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  15886. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  15887. this.anisotropicFilteringLevel = 4;
  15888. this._scene = scene;
  15889. this._scene.textures.push(this);
  15890. }
  15891. BaseTexture.prototype.getScene = function () {
  15892. return this._scene;
  15893. };
  15894. BaseTexture.prototype.getTextureMatrix = function () {
  15895. return null;
  15896. };
  15897. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  15898. return null;
  15899. };
  15900. BaseTexture.prototype.getInternalTexture = function () {
  15901. return this._texture;
  15902. };
  15903. BaseTexture.prototype.isReady = function () {
  15904. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15905. return true;
  15906. }
  15907. if (this._texture) {
  15908. return this._texture.isReady;
  15909. }
  15910. return false;
  15911. };
  15912. BaseTexture.prototype.getSize = function () {
  15913. if (this._texture._width) {
  15914. return { width: this._texture._width, height: this._texture._height };
  15915. }
  15916. if (this._texture._size) {
  15917. return { width: this._texture._size, height: this._texture._size };
  15918. }
  15919. return { width: 0, height: 0 };
  15920. };
  15921. BaseTexture.prototype.getBaseSize = function () {
  15922. if (!this.isReady())
  15923. return { width: 0, height: 0 };
  15924. if (this._texture._size) {
  15925. return { width: this._texture._size, height: this._texture._size };
  15926. }
  15927. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  15928. };
  15929. BaseTexture.prototype.scale = function (ratio) {
  15930. };
  15931. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  15932. get: function () {
  15933. return false;
  15934. },
  15935. enumerable: true,
  15936. configurable: true
  15937. });
  15938. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  15939. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  15940. for (var index = 0; index < texturesCache.length; index++) {
  15941. var texturesCacheEntry = texturesCache[index];
  15942. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  15943. texturesCache.splice(index, 1);
  15944. return;
  15945. }
  15946. }
  15947. };
  15948. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  15949. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  15950. for (var index = 0; index < texturesCache.length; index++) {
  15951. var texturesCacheEntry = texturesCache[index];
  15952. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  15953. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  15954. texturesCacheEntry.references++;
  15955. return texturesCacheEntry;
  15956. }
  15957. }
  15958. }
  15959. return null;
  15960. };
  15961. BaseTexture.prototype.delayLoad = function () {
  15962. };
  15963. BaseTexture.prototype.releaseInternalTexture = function () {
  15964. if (!this._texture) {
  15965. return;
  15966. }
  15967. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  15968. this._texture.references--;
  15969. // Final reference ?
  15970. if (this._texture.references === 0) {
  15971. var index = texturesCache.indexOf(this._texture);
  15972. texturesCache.splice(index, 1);
  15973. this._scene.getEngine()._releaseTexture(this._texture);
  15974. delete this._texture;
  15975. }
  15976. };
  15977. BaseTexture.prototype.clone = function () {
  15978. return null;
  15979. };
  15980. BaseTexture.prototype.dispose = function () {
  15981. // Remove from scene
  15982. var index = this._scene.textures.indexOf(this);
  15983. if (index >= 0) {
  15984. this._scene.textures.splice(index, 1);
  15985. }
  15986. if (this._texture === undefined) {
  15987. return;
  15988. }
  15989. this.releaseInternalTexture();
  15990. // Callback
  15991. if (this.onDispose) {
  15992. this.onDispose();
  15993. }
  15994. };
  15995. return BaseTexture;
  15996. })();
  15997. BABYLON.BaseTexture = BaseTexture;
  15998. })(BABYLON || (BABYLON = {}));
  15999. //# sourceMappingURL=babylon.baseTexture.js.map
  16000. var BABYLON;
  16001. (function (BABYLON) {
  16002. var Texture = (function (_super) {
  16003. __extends(Texture, _super);
  16004. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16005. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16006. if (onLoad === void 0) { onLoad = null; }
  16007. if (onError === void 0) { onError = null; }
  16008. if (buffer === void 0) { buffer = null; }
  16009. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16010. _super.call(this, scene);
  16011. this.uOffset = 0;
  16012. this.vOffset = 0;
  16013. this.uScale = 1.0;
  16014. this.vScale = 1.0;
  16015. this.uAng = 0;
  16016. this.vAng = 0;
  16017. this.wAng = 0;
  16018. this.name = url;
  16019. this.url = url;
  16020. this._noMipmap = noMipmap;
  16021. this._invertY = invertY;
  16022. this._samplingMode = samplingMode;
  16023. this._buffer = buffer;
  16024. this._deleteBuffer = deleteBuffer;
  16025. if (!url) {
  16026. return;
  16027. }
  16028. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16029. if (!this._texture) {
  16030. if (!scene.useDelayedTextureLoading) {
  16031. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16032. if (deleteBuffer) {
  16033. delete this._buffer;
  16034. }
  16035. }
  16036. else {
  16037. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16038. }
  16039. }
  16040. else {
  16041. BABYLON.Tools.SetImmediate(function () {
  16042. if (onLoad) {
  16043. onLoad();
  16044. }
  16045. });
  16046. }
  16047. }
  16048. Texture.prototype.delayLoad = function () {
  16049. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16050. return;
  16051. }
  16052. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16053. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16054. if (!this._texture) {
  16055. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16056. if (this._deleteBuffer) {
  16057. delete this._buffer;
  16058. }
  16059. }
  16060. };
  16061. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16062. if (!this._texture) {
  16063. return;
  16064. }
  16065. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16066. };
  16067. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16068. x -= this.uOffset + 0.5;
  16069. y -= this.vOffset + 0.5;
  16070. z -= 0.5;
  16071. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16072. t.x *= this.uScale;
  16073. t.y *= this.vScale;
  16074. t.x += 0.5;
  16075. t.y += 0.5;
  16076. t.z += 0.5;
  16077. };
  16078. Texture.prototype.getTextureMatrix = function () {
  16079. if (this.uOffset === this._cachedUOffset &&
  16080. this.vOffset === this._cachedVOffset &&
  16081. this.uScale === this._cachedUScale &&
  16082. this.vScale === this._cachedVScale &&
  16083. this.uAng === this._cachedUAng &&
  16084. this.vAng === this._cachedVAng &&
  16085. this.wAng === this._cachedWAng) {
  16086. return this._cachedTextureMatrix;
  16087. }
  16088. this._cachedUOffset = this.uOffset;
  16089. this._cachedVOffset = this.vOffset;
  16090. this._cachedUScale = this.uScale;
  16091. this._cachedVScale = this.vScale;
  16092. this._cachedUAng = this.uAng;
  16093. this._cachedVAng = this.vAng;
  16094. this._cachedWAng = this.wAng;
  16095. if (!this._cachedTextureMatrix) {
  16096. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16097. this._rowGenerationMatrix = new BABYLON.Matrix();
  16098. this._t0 = BABYLON.Vector3.Zero();
  16099. this._t1 = BABYLON.Vector3.Zero();
  16100. this._t2 = BABYLON.Vector3.Zero();
  16101. }
  16102. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16103. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16104. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16105. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16106. this._t1.subtractInPlace(this._t0);
  16107. this._t2.subtractInPlace(this._t0);
  16108. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16109. this._cachedTextureMatrix.m[0] = this._t1.x;
  16110. this._cachedTextureMatrix.m[1] = this._t1.y;
  16111. this._cachedTextureMatrix.m[2] = this._t1.z;
  16112. this._cachedTextureMatrix.m[4] = this._t2.x;
  16113. this._cachedTextureMatrix.m[5] = this._t2.y;
  16114. this._cachedTextureMatrix.m[6] = this._t2.z;
  16115. this._cachedTextureMatrix.m[8] = this._t0.x;
  16116. this._cachedTextureMatrix.m[9] = this._t0.y;
  16117. this._cachedTextureMatrix.m[10] = this._t0.z;
  16118. return this._cachedTextureMatrix;
  16119. };
  16120. Texture.prototype.getReflectionTextureMatrix = function () {
  16121. if (this.uOffset === this._cachedUOffset &&
  16122. this.vOffset === this._cachedVOffset &&
  16123. this.uScale === this._cachedUScale &&
  16124. this.vScale === this._cachedVScale &&
  16125. this.coordinatesMode === this._cachedCoordinatesMode) {
  16126. return this._cachedTextureMatrix;
  16127. }
  16128. if (!this._cachedTextureMatrix) {
  16129. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16130. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  16131. }
  16132. this._cachedCoordinatesMode = this.coordinatesMode;
  16133. switch (this.coordinatesMode) {
  16134. case Texture.SPHERICAL_MODE:
  16135. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16136. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  16137. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  16138. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  16139. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  16140. break;
  16141. case Texture.PLANAR_MODE:
  16142. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16143. this._cachedTextureMatrix[0] = this.uScale;
  16144. this._cachedTextureMatrix[5] = this.vScale;
  16145. this._cachedTextureMatrix[12] = this.uOffset;
  16146. this._cachedTextureMatrix[13] = this.vOffset;
  16147. break;
  16148. case Texture.PROJECTION_MODE:
  16149. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  16150. this._projectionModeMatrix.m[0] = 0.5;
  16151. this._projectionModeMatrix.m[5] = -0.5;
  16152. this._projectionModeMatrix.m[10] = 0.0;
  16153. this._projectionModeMatrix.m[12] = 0.5;
  16154. this._projectionModeMatrix.m[13] = 0.5;
  16155. this._projectionModeMatrix.m[14] = 1.0;
  16156. this._projectionModeMatrix.m[15] = 1.0;
  16157. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  16158. break;
  16159. default:
  16160. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16161. break;
  16162. }
  16163. return this._cachedTextureMatrix;
  16164. };
  16165. Texture.prototype.clone = function () {
  16166. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  16167. // Base texture
  16168. newTexture.hasAlpha = this.hasAlpha;
  16169. newTexture.level = this.level;
  16170. newTexture.wrapU = this.wrapU;
  16171. newTexture.wrapV = this.wrapV;
  16172. newTexture.coordinatesIndex = this.coordinatesIndex;
  16173. newTexture.coordinatesMode = this.coordinatesMode;
  16174. // Texture
  16175. newTexture.uOffset = this.uOffset;
  16176. newTexture.vOffset = this.vOffset;
  16177. newTexture.uScale = this.uScale;
  16178. newTexture.vScale = this.vScale;
  16179. newTexture.uAng = this.uAng;
  16180. newTexture.vAng = this.vAng;
  16181. newTexture.wAng = this.wAng;
  16182. return newTexture;
  16183. };
  16184. // Statics
  16185. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  16186. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16187. if (onLoad === void 0) { onLoad = null; }
  16188. if (onError === void 0) { onError = null; }
  16189. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  16190. };
  16191. // Constants
  16192. Texture.NEAREST_SAMPLINGMODE = 1;
  16193. Texture.BILINEAR_SAMPLINGMODE = 2;
  16194. Texture.TRILINEAR_SAMPLINGMODE = 3;
  16195. Texture.EXPLICIT_MODE = 0;
  16196. Texture.SPHERICAL_MODE = 1;
  16197. Texture.PLANAR_MODE = 2;
  16198. Texture.CUBIC_MODE = 3;
  16199. Texture.PROJECTION_MODE = 4;
  16200. Texture.SKYBOX_MODE = 5;
  16201. Texture.CLAMP_ADDRESSMODE = 0;
  16202. Texture.WRAP_ADDRESSMODE = 1;
  16203. Texture.MIRROR_ADDRESSMODE = 2;
  16204. return Texture;
  16205. })(BABYLON.BaseTexture);
  16206. BABYLON.Texture = Texture;
  16207. })(BABYLON || (BABYLON = {}));
  16208. //# sourceMappingURL=babylon.texture.js.map
  16209. var BABYLON;
  16210. (function (BABYLON) {
  16211. var CubeTexture = (function (_super) {
  16212. __extends(CubeTexture, _super);
  16213. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  16214. _super.call(this, scene);
  16215. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  16216. this.name = rootUrl;
  16217. this.url = rootUrl;
  16218. this._noMipmap = noMipmap;
  16219. this.hasAlpha = false;
  16220. this._texture = this._getFromCache(rootUrl, noMipmap);
  16221. if (!extensions) {
  16222. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  16223. }
  16224. this._extensions = extensions;
  16225. if (!this._texture) {
  16226. if (!scene.useDelayedTextureLoading) {
  16227. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  16228. }
  16229. else {
  16230. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16231. }
  16232. }
  16233. this.isCube = true;
  16234. this._textureMatrix = BABYLON.Matrix.Identity();
  16235. }
  16236. CubeTexture.prototype.clone = function () {
  16237. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  16238. // Base texture
  16239. newTexture.level = this.level;
  16240. newTexture.wrapU = this.wrapU;
  16241. newTexture.wrapV = this.wrapV;
  16242. newTexture.coordinatesIndex = this.coordinatesIndex;
  16243. newTexture.coordinatesMode = this.coordinatesMode;
  16244. return newTexture;
  16245. };
  16246. // Methods
  16247. CubeTexture.prototype.delayLoad = function () {
  16248. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16249. return;
  16250. }
  16251. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16252. this._texture = this._getFromCache(this.url, this._noMipmap);
  16253. if (!this._texture) {
  16254. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  16255. }
  16256. };
  16257. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  16258. return this._textureMatrix;
  16259. };
  16260. return CubeTexture;
  16261. })(BABYLON.BaseTexture);
  16262. BABYLON.CubeTexture = CubeTexture;
  16263. })(BABYLON || (BABYLON = {}));
  16264. //# sourceMappingURL=babylon.cubeTexture.js.map
  16265. var BABYLON;
  16266. (function (BABYLON) {
  16267. var RenderTargetTexture = (function (_super) {
  16268. __extends(RenderTargetTexture, _super);
  16269. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  16270. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  16271. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  16272. _super.call(this, null, scene, !generateMipMaps);
  16273. this.renderList = new Array();
  16274. this.renderParticles = true;
  16275. this.renderSprites = false;
  16276. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  16277. this._currentRefreshId = -1;
  16278. this._refreshRate = 1;
  16279. this.name = name;
  16280. this.isRenderTarget = true;
  16281. this._size = size;
  16282. this._generateMipMaps = generateMipMaps;
  16283. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  16284. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  16285. // Rendering groups
  16286. this._renderingManager = new BABYLON.RenderingManager(scene);
  16287. }
  16288. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  16289. this._currentRefreshId = -1;
  16290. };
  16291. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  16292. get: function () {
  16293. return this._refreshRate;
  16294. },
  16295. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16296. set: function (value) {
  16297. this._refreshRate = value;
  16298. this.resetRefreshCounter();
  16299. },
  16300. enumerable: true,
  16301. configurable: true
  16302. });
  16303. RenderTargetTexture.prototype._shouldRender = function () {
  16304. if (this._currentRefreshId === -1) {
  16305. this._currentRefreshId = 1;
  16306. return true;
  16307. }
  16308. if (this.refreshRate === this._currentRefreshId) {
  16309. this._currentRefreshId = 1;
  16310. return true;
  16311. }
  16312. this._currentRefreshId++;
  16313. return false;
  16314. };
  16315. RenderTargetTexture.prototype.isReady = function () {
  16316. if (!this.getScene().renderTargetsEnabled) {
  16317. return false;
  16318. }
  16319. return _super.prototype.isReady.call(this);
  16320. };
  16321. RenderTargetTexture.prototype.getRenderSize = function () {
  16322. return this._size;
  16323. };
  16324. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  16325. get: function () {
  16326. return true;
  16327. },
  16328. enumerable: true,
  16329. configurable: true
  16330. });
  16331. RenderTargetTexture.prototype.scale = function (ratio) {
  16332. var newSize = this._size * ratio;
  16333. this.resize(newSize, this._generateMipMaps);
  16334. };
  16335. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  16336. this.releaseInternalTexture();
  16337. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16338. };
  16339. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  16340. var scene = this.getScene();
  16341. var engine = scene.getEngine();
  16342. if (this._waitingRenderList) {
  16343. this.renderList = [];
  16344. for (var index = 0; index < this._waitingRenderList.length; index++) {
  16345. var id = this._waitingRenderList[index];
  16346. this.renderList.push(scene.getMeshByID(id));
  16347. }
  16348. delete this._waitingRenderList;
  16349. }
  16350. if (this.renderList && this.renderList.length === 0) {
  16351. return;
  16352. }
  16353. // Bind
  16354. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  16355. engine.bindFramebuffer(this._texture);
  16356. }
  16357. this._renderingManager.reset();
  16358. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  16359. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  16360. var mesh = currentRenderList[meshIndex];
  16361. if (mesh) {
  16362. if (!mesh.isReady()) {
  16363. // Reset _currentRefreshId
  16364. this.resetRefreshCounter();
  16365. continue;
  16366. }
  16367. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  16368. mesh._activate(scene.getRenderId());
  16369. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  16370. var subMesh = mesh.subMeshes[subIndex];
  16371. scene._activeIndices += subMesh.indexCount;
  16372. this._renderingManager.dispatch(subMesh);
  16373. }
  16374. }
  16375. }
  16376. }
  16377. if (this.onBeforeRender) {
  16378. this.onBeforeRender();
  16379. }
  16380. // Clear
  16381. if (this.onClear) {
  16382. this.onClear(engine);
  16383. }
  16384. else {
  16385. engine.clear(scene.clearColor, true, true);
  16386. }
  16387. if (!this._doNotChangeAspectRatio) {
  16388. scene.updateTransformMatrix(true);
  16389. }
  16390. // Render
  16391. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  16392. if (useCameraPostProcess) {
  16393. scene.postProcessManager._finalizeFrame(false, this._texture);
  16394. }
  16395. if (!this._doNotChangeAspectRatio) {
  16396. scene.updateTransformMatrix(true);
  16397. }
  16398. if (this.onAfterRender) {
  16399. this.onAfterRender();
  16400. }
  16401. // Dump ?
  16402. if (dumpForDebug) {
  16403. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  16404. }
  16405. // Unbind
  16406. engine.unBindFramebuffer(this._texture);
  16407. if (this.onAfterUnbind) {
  16408. this.onAfterUnbind();
  16409. }
  16410. };
  16411. RenderTargetTexture.prototype.clone = function () {
  16412. var textureSize = this.getSize();
  16413. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16414. // Base texture
  16415. newTexture.hasAlpha = this.hasAlpha;
  16416. newTexture.level = this.level;
  16417. // RenderTarget Texture
  16418. newTexture.coordinatesMode = this.coordinatesMode;
  16419. newTexture.renderList = this.renderList.slice(0);
  16420. return newTexture;
  16421. };
  16422. return RenderTargetTexture;
  16423. })(BABYLON.Texture);
  16424. BABYLON.RenderTargetTexture = RenderTargetTexture;
  16425. })(BABYLON || (BABYLON = {}));
  16426. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  16427. var BABYLON;
  16428. (function (BABYLON) {
  16429. var ProceduralTexture = (function (_super) {
  16430. __extends(ProceduralTexture, _super);
  16431. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  16432. if (generateMipMaps === void 0) { generateMipMaps = true; }
  16433. _super.call(this, null, scene, !generateMipMaps);
  16434. this._currentRefreshId = -1;
  16435. this._refreshRate = 1;
  16436. this._vertexDeclaration = [2];
  16437. this._vertexStrideSize = 2 * 4;
  16438. this._uniforms = new Array();
  16439. this._samplers = new Array();
  16440. this._textures = new Array();
  16441. this._floats = new Array();
  16442. this._floatsArrays = {};
  16443. this._colors3 = new Array();
  16444. this._colors4 = new Array();
  16445. this._vectors2 = new Array();
  16446. this._vectors3 = new Array();
  16447. this._matrices = new Array();
  16448. this._fallbackTextureUsed = false;
  16449. scene._proceduralTextures.push(this);
  16450. this.name = name;
  16451. this.isRenderTarget = true;
  16452. this._size = size;
  16453. this._generateMipMaps = generateMipMaps;
  16454. this.setFragment(fragment);
  16455. this._fallbackTexture = fallbackTexture;
  16456. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  16457. // VBO
  16458. var vertices = [];
  16459. vertices.push(1, 1);
  16460. vertices.push(-1, 1);
  16461. vertices.push(-1, -1);
  16462. vertices.push(1, -1);
  16463. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16464. // Indices
  16465. var indices = [];
  16466. indices.push(0);
  16467. indices.push(1);
  16468. indices.push(2);
  16469. indices.push(0);
  16470. indices.push(2);
  16471. indices.push(3);
  16472. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16473. }
  16474. ProceduralTexture.prototype.reset = function () {
  16475. if (this._effect === undefined) {
  16476. return;
  16477. }
  16478. var engine = this.getScene().getEngine();
  16479. engine._releaseEffect(this._effect);
  16480. };
  16481. ProceduralTexture.prototype.isReady = function () {
  16482. var _this = this;
  16483. var engine = this.getScene().getEngine();
  16484. var shaders;
  16485. if (!this._fragment) {
  16486. return false;
  16487. }
  16488. if (this._fallbackTextureUsed) {
  16489. return true;
  16490. }
  16491. if (this._fragment.fragmentElement !== undefined) {
  16492. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  16493. }
  16494. else {
  16495. shaders = { vertex: "procedural", fragment: this._fragment };
  16496. }
  16497. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  16498. _this.releaseInternalTexture();
  16499. if (_this._fallbackTexture) {
  16500. _this._texture = _this._fallbackTexture._texture;
  16501. _this._texture.references++;
  16502. }
  16503. _this._fallbackTextureUsed = true;
  16504. });
  16505. return this._effect.isReady();
  16506. };
  16507. ProceduralTexture.prototype.resetRefreshCounter = function () {
  16508. this._currentRefreshId = -1;
  16509. };
  16510. ProceduralTexture.prototype.setFragment = function (fragment) {
  16511. this._fragment = fragment;
  16512. };
  16513. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  16514. get: function () {
  16515. return this._refreshRate;
  16516. },
  16517. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16518. set: function (value) {
  16519. this._refreshRate = value;
  16520. this.resetRefreshCounter();
  16521. },
  16522. enumerable: true,
  16523. configurable: true
  16524. });
  16525. ProceduralTexture.prototype._shouldRender = function () {
  16526. if (!this.isReady() || !this._texture) {
  16527. return false;
  16528. }
  16529. if (this._fallbackTextureUsed) {
  16530. return false;
  16531. }
  16532. if (this._currentRefreshId === -1) {
  16533. this._currentRefreshId = 1;
  16534. return true;
  16535. }
  16536. if (this.refreshRate === this._currentRefreshId) {
  16537. this._currentRefreshId = 1;
  16538. return true;
  16539. }
  16540. this._currentRefreshId++;
  16541. return false;
  16542. };
  16543. ProceduralTexture.prototype.getRenderSize = function () {
  16544. return this._size;
  16545. };
  16546. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  16547. if (this._fallbackTextureUsed) {
  16548. return;
  16549. }
  16550. this.releaseInternalTexture();
  16551. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16552. };
  16553. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  16554. if (this._uniforms.indexOf(uniformName) === -1) {
  16555. this._uniforms.push(uniformName);
  16556. }
  16557. };
  16558. ProceduralTexture.prototype.setTexture = function (name, texture) {
  16559. if (this._samplers.indexOf(name) === -1) {
  16560. this._samplers.push(name);
  16561. }
  16562. this._textures[name] = texture;
  16563. return this;
  16564. };
  16565. ProceduralTexture.prototype.setFloat = function (name, value) {
  16566. this._checkUniform(name);
  16567. this._floats[name] = value;
  16568. return this;
  16569. };
  16570. ProceduralTexture.prototype.setFloats = function (name, value) {
  16571. this._checkUniform(name);
  16572. this._floatsArrays[name] = value;
  16573. return this;
  16574. };
  16575. ProceduralTexture.prototype.setColor3 = function (name, value) {
  16576. this._checkUniform(name);
  16577. this._colors3[name] = value;
  16578. return this;
  16579. };
  16580. ProceduralTexture.prototype.setColor4 = function (name, value) {
  16581. this._checkUniform(name);
  16582. this._colors4[name] = value;
  16583. return this;
  16584. };
  16585. ProceduralTexture.prototype.setVector2 = function (name, value) {
  16586. this._checkUniform(name);
  16587. this._vectors2[name] = value;
  16588. return this;
  16589. };
  16590. ProceduralTexture.prototype.setVector3 = function (name, value) {
  16591. this._checkUniform(name);
  16592. this._vectors3[name] = value;
  16593. return this;
  16594. };
  16595. ProceduralTexture.prototype.setMatrix = function (name, value) {
  16596. this._checkUniform(name);
  16597. this._matrices[name] = value;
  16598. return this;
  16599. };
  16600. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  16601. var scene = this.getScene();
  16602. var engine = scene.getEngine();
  16603. engine.bindFramebuffer(this._texture);
  16604. // Clear
  16605. engine.clear(scene.clearColor, true, true);
  16606. // Render
  16607. engine.enableEffect(this._effect);
  16608. engine.setState(false);
  16609. // Texture
  16610. for (var name in this._textures) {
  16611. this._effect.setTexture(name, this._textures[name]);
  16612. }
  16613. // Float
  16614. for (name in this._floats) {
  16615. this._effect.setFloat(name, this._floats[name]);
  16616. }
  16617. // Floats
  16618. for (name in this._floatsArrays) {
  16619. this._effect.setArray(name, this._floatsArrays[name]);
  16620. }
  16621. // Color3
  16622. for (name in this._colors3) {
  16623. this._effect.setColor3(name, this._colors3[name]);
  16624. }
  16625. // Color4
  16626. for (name in this._colors4) {
  16627. var color = this._colors4[name];
  16628. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  16629. }
  16630. // Vector2
  16631. for (name in this._vectors2) {
  16632. this._effect.setVector2(name, this._vectors2[name]);
  16633. }
  16634. // Vector3
  16635. for (name in this._vectors3) {
  16636. this._effect.setVector3(name, this._vectors3[name]);
  16637. }
  16638. // Matrix
  16639. for (name in this._matrices) {
  16640. this._effect.setMatrix(name, this._matrices[name]);
  16641. }
  16642. // VBOs
  16643. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16644. // Draw order
  16645. engine.draw(true, 0, 6);
  16646. // Unbind
  16647. engine.unBindFramebuffer(this._texture);
  16648. };
  16649. ProceduralTexture.prototype.clone = function () {
  16650. var textureSize = this.getSize();
  16651. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  16652. // Base texture
  16653. newTexture.hasAlpha = this.hasAlpha;
  16654. newTexture.level = this.level;
  16655. // RenderTarget Texture
  16656. newTexture.coordinatesMode = this.coordinatesMode;
  16657. return newTexture;
  16658. };
  16659. ProceduralTexture.prototype.dispose = function () {
  16660. var index = this.getScene()._proceduralTextures.indexOf(this);
  16661. if (index >= 0) {
  16662. this.getScene()._proceduralTextures.splice(index, 1);
  16663. }
  16664. _super.prototype.dispose.call(this);
  16665. };
  16666. return ProceduralTexture;
  16667. })(BABYLON.Texture);
  16668. BABYLON.ProceduralTexture = ProceduralTexture;
  16669. })(BABYLON || (BABYLON = {}));
  16670. //# sourceMappingURL=babylon.proceduralTexture.js.map
  16671. var BABYLON;
  16672. (function (BABYLON) {
  16673. var MirrorTexture = (function (_super) {
  16674. __extends(MirrorTexture, _super);
  16675. function MirrorTexture(name, size, scene, generateMipMaps) {
  16676. var _this = this;
  16677. _super.call(this, name, size, scene, generateMipMaps, true);
  16678. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  16679. this._transformMatrix = BABYLON.Matrix.Zero();
  16680. this._mirrorMatrix = BABYLON.Matrix.Zero();
  16681. this.onBeforeRender = function () {
  16682. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  16683. _this._savedViewMatrix = scene.getViewMatrix();
  16684. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  16685. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  16686. scene.clipPlane = _this.mirrorPlane;
  16687. scene.getEngine().cullBackFaces = false;
  16688. };
  16689. this.onAfterRender = function () {
  16690. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  16691. scene.getEngine().cullBackFaces = true;
  16692. delete scene.clipPlane;
  16693. };
  16694. }
  16695. MirrorTexture.prototype.clone = function () {
  16696. var textureSize = this.getSize();
  16697. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16698. // Base texture
  16699. newTexture.hasAlpha = this.hasAlpha;
  16700. newTexture.level = this.level;
  16701. // Mirror Texture
  16702. newTexture.mirrorPlane = this.mirrorPlane.clone();
  16703. newTexture.renderList = this.renderList.slice(0);
  16704. return newTexture;
  16705. };
  16706. return MirrorTexture;
  16707. })(BABYLON.RenderTargetTexture);
  16708. BABYLON.MirrorTexture = MirrorTexture;
  16709. })(BABYLON || (BABYLON = {}));
  16710. //# sourceMappingURL=babylon.mirrorTexture.js.map
  16711. var BABYLON;
  16712. (function (BABYLON) {
  16713. var DynamicTexture = (function (_super) {
  16714. __extends(DynamicTexture, _super);
  16715. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  16716. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16717. _super.call(this, null, scene, !generateMipMaps);
  16718. this.name = name;
  16719. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16720. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16721. this._generateMipMaps = generateMipMaps;
  16722. if (options.getContext) {
  16723. this._canvas = options;
  16724. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  16725. }
  16726. else {
  16727. this._canvas = document.createElement("canvas");
  16728. if (options.width) {
  16729. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  16730. }
  16731. else {
  16732. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  16733. }
  16734. }
  16735. var textureSize = this.getSize();
  16736. this._canvas.width = textureSize.width;
  16737. this._canvas.height = textureSize.height;
  16738. this._context = this._canvas.getContext("2d");
  16739. }
  16740. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  16741. get: function () {
  16742. return true;
  16743. },
  16744. enumerable: true,
  16745. configurable: true
  16746. });
  16747. DynamicTexture.prototype.scale = function (ratio) {
  16748. var textureSize = this.getSize();
  16749. textureSize.width *= ratio;
  16750. textureSize.height *= ratio;
  16751. this._canvas.width = textureSize.width;
  16752. this._canvas.height = textureSize.height;
  16753. this.releaseInternalTexture();
  16754. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  16755. };
  16756. DynamicTexture.prototype.getContext = function () {
  16757. return this._context;
  16758. };
  16759. DynamicTexture.prototype.clear = function () {
  16760. var size = this.getSize();
  16761. this._context.fillRect(0, 0, size.width, size.height);
  16762. };
  16763. DynamicTexture.prototype.update = function (invertY) {
  16764. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  16765. };
  16766. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  16767. if (update === void 0) { update = true; }
  16768. var size = this.getSize();
  16769. if (clearColor) {
  16770. this._context.fillStyle = clearColor;
  16771. this._context.fillRect(0, 0, size.width, size.height);
  16772. }
  16773. this._context.font = font;
  16774. if (x === null) {
  16775. var textSize = this._context.measureText(text);
  16776. x = (size.width - textSize.width) / 2;
  16777. }
  16778. this._context.fillStyle = color;
  16779. this._context.fillText(text, x, y);
  16780. if (update) {
  16781. this.update(invertY);
  16782. }
  16783. };
  16784. DynamicTexture.prototype.clone = function () {
  16785. var textureSize = this.getSize();
  16786. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16787. // Base texture
  16788. newTexture.hasAlpha = this.hasAlpha;
  16789. newTexture.level = this.level;
  16790. // Dynamic Texture
  16791. newTexture.wrapU = this.wrapU;
  16792. newTexture.wrapV = this.wrapV;
  16793. return newTexture;
  16794. };
  16795. return DynamicTexture;
  16796. })(BABYLON.Texture);
  16797. BABYLON.DynamicTexture = DynamicTexture;
  16798. })(BABYLON || (BABYLON = {}));
  16799. //# sourceMappingURL=babylon.dynamicTexture.js.map
  16800. var BABYLON;
  16801. (function (BABYLON) {
  16802. var VideoTexture = (function (_super) {
  16803. __extends(VideoTexture, _super);
  16804. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  16805. var _this = this;
  16806. if (generateMipMaps === void 0) { generateMipMaps = false; }
  16807. if (invertY === void 0) { invertY = false; }
  16808. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16809. _super.call(this, null, scene, !generateMipMaps, invertY);
  16810. this._autoLaunch = true;
  16811. this.name = name;
  16812. this.video = document.createElement("video");
  16813. this.video.autoplay = false;
  16814. this.video.loop = true;
  16815. this.video.addEventListener("canplaythrough", function () {
  16816. if (BABYLON.Tools.IsExponantOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponantOfTwo(_this.video.videoHeight)) {
  16817. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16818. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16819. }
  16820. else {
  16821. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16822. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16823. generateMipMaps = false;
  16824. }
  16825. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  16826. _this._texture.isReady = true;
  16827. });
  16828. urls.forEach(function (url) {
  16829. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  16830. var source = document.createElement("source");
  16831. source.src = url;
  16832. _this.video.appendChild(source);
  16833. });
  16834. this._lastUpdate = BABYLON.Tools.Now;
  16835. }
  16836. VideoTexture.prototype.update = function () {
  16837. if (this._autoLaunch) {
  16838. this._autoLaunch = false;
  16839. this.video.play();
  16840. }
  16841. var now = BABYLON.Tools.Now;
  16842. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  16843. return false;
  16844. }
  16845. this._lastUpdate = now;
  16846. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  16847. return true;
  16848. };
  16849. return VideoTexture;
  16850. })(BABYLON.Texture);
  16851. BABYLON.VideoTexture = VideoTexture;
  16852. })(BABYLON || (BABYLON = {}));
  16853. //# sourceMappingURL=babylon.videoTexture.js.map
  16854. var BABYLON;
  16855. (function (BABYLON) {
  16856. var CustomProceduralTexture = (function (_super) {
  16857. __extends(CustomProceduralTexture, _super);
  16858. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  16859. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  16860. this._animate = true;
  16861. this._time = 0;
  16862. this._texturePath = texturePath;
  16863. //Try to load json
  16864. this.loadJson(texturePath);
  16865. this.refreshRate = 1;
  16866. }
  16867. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  16868. var _this = this;
  16869. var that = this;
  16870. function noConfigFile() {
  16871. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  16872. try {
  16873. that.setFragment(that._texturePath);
  16874. }
  16875. catch (ex) {
  16876. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  16877. }
  16878. }
  16879. var configFileUrl = jsonUrl + "/config.json";
  16880. var xhr = new XMLHttpRequest();
  16881. xhr.open("GET", configFileUrl, true);
  16882. xhr.addEventListener("load", function () {
  16883. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  16884. try {
  16885. _this._config = JSON.parse(xhr.response);
  16886. _this.updateShaderUniforms();
  16887. _this.updateTextures();
  16888. _this.setFragment(_this._texturePath + "/custom");
  16889. _this._animate = _this._config.animate;
  16890. _this.refreshRate = _this._config.refreshrate;
  16891. }
  16892. catch (ex) {
  16893. noConfigFile();
  16894. }
  16895. }
  16896. else {
  16897. noConfigFile();
  16898. }
  16899. }, false);
  16900. xhr.addEventListener("error", function () {
  16901. noConfigFile();
  16902. }, false);
  16903. try {
  16904. xhr.send();
  16905. }
  16906. catch (ex) {
  16907. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  16908. }
  16909. };
  16910. CustomProceduralTexture.prototype.isReady = function () {
  16911. if (!_super.prototype.isReady.call(this)) {
  16912. return false;
  16913. }
  16914. for (var name in this._textures) {
  16915. var texture = this._textures[name];
  16916. if (!texture.isReady()) {
  16917. return false;
  16918. }
  16919. }
  16920. return true;
  16921. };
  16922. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  16923. if (this._animate) {
  16924. this._time += this.getScene().getAnimationRatio() * 0.03;
  16925. this.updateShaderUniforms();
  16926. }
  16927. _super.prototype.render.call(this, useCameraPostProcess);
  16928. };
  16929. CustomProceduralTexture.prototype.updateTextures = function () {
  16930. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  16931. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  16932. }
  16933. };
  16934. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  16935. if (this._config) {
  16936. for (var j = 0; j < this._config.uniforms.length; j++) {
  16937. var uniform = this._config.uniforms[j];
  16938. switch (uniform.type) {
  16939. case "float":
  16940. this.setFloat(uniform.name, uniform.value);
  16941. break;
  16942. case "color3":
  16943. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  16944. break;
  16945. case "color4":
  16946. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  16947. break;
  16948. case "vector2":
  16949. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  16950. break;
  16951. case "vector3":
  16952. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  16953. break;
  16954. }
  16955. }
  16956. }
  16957. this.setFloat("time", this._time);
  16958. };
  16959. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  16960. get: function () {
  16961. return this._animate;
  16962. },
  16963. set: function (value) {
  16964. this._animate = value;
  16965. },
  16966. enumerable: true,
  16967. configurable: true
  16968. });
  16969. return CustomProceduralTexture;
  16970. })(BABYLON.ProceduralTexture);
  16971. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  16972. })(BABYLON || (BABYLON = {}));
  16973. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  16974. var BABYLON;
  16975. (function (BABYLON) {
  16976. var WoodProceduralTexture = (function (_super) {
  16977. __extends(WoodProceduralTexture, _super);
  16978. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  16979. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  16980. this._ampScale = 100.0;
  16981. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  16982. this.updateShaderUniforms();
  16983. this.refreshRate = 0;
  16984. }
  16985. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  16986. this.setFloat("ampScale", this._ampScale);
  16987. this.setColor3("woodColor", this._woodColor);
  16988. };
  16989. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  16990. get: function () {
  16991. return this._ampScale;
  16992. },
  16993. set: function (value) {
  16994. this._ampScale = value;
  16995. this.updateShaderUniforms();
  16996. },
  16997. enumerable: true,
  16998. configurable: true
  16999. });
  17000. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  17001. get: function () {
  17002. return this._woodColor;
  17003. },
  17004. set: function (value) {
  17005. this._woodColor = value;
  17006. this.updateShaderUniforms();
  17007. },
  17008. enumerable: true,
  17009. configurable: true
  17010. });
  17011. return WoodProceduralTexture;
  17012. })(BABYLON.ProceduralTexture);
  17013. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  17014. var FireProceduralTexture = (function (_super) {
  17015. __extends(FireProceduralTexture, _super);
  17016. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17017. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  17018. this._time = 0.0;
  17019. this._speed = new BABYLON.Vector2(0.5, 0.3);
  17020. this._autoGenerateTime = true;
  17021. this._alphaThreshold = 0.5;
  17022. this._fireColors = FireProceduralTexture.RedFireColors;
  17023. this.updateShaderUniforms();
  17024. this.refreshRate = 1;
  17025. }
  17026. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  17027. this.setFloat("time", this._time);
  17028. this.setVector2("speed", this._speed);
  17029. this.setColor3("c1", this._fireColors[0]);
  17030. this.setColor3("c2", this._fireColors[1]);
  17031. this.setColor3("c3", this._fireColors[2]);
  17032. this.setColor3("c4", this._fireColors[3]);
  17033. this.setColor3("c5", this._fireColors[4]);
  17034. this.setColor3("c6", this._fireColors[5]);
  17035. this.setFloat("alphaThreshold", this._alphaThreshold);
  17036. };
  17037. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17038. if (this._autoGenerateTime) {
  17039. this._time += this.getScene().getAnimationRatio() * 0.03;
  17040. this.updateShaderUniforms();
  17041. }
  17042. _super.prototype.render.call(this, useCameraPostProcess);
  17043. };
  17044. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  17045. get: function () {
  17046. return [
  17047. new BABYLON.Color3(0.5, 0.0, 1.0),
  17048. new BABYLON.Color3(0.9, 0.0, 1.0),
  17049. new BABYLON.Color3(0.2, 0.0, 1.0),
  17050. new BABYLON.Color3(1.0, 0.9, 1.0),
  17051. new BABYLON.Color3(0.1, 0.1, 1.0),
  17052. new BABYLON.Color3(0.9, 0.9, 1.0)
  17053. ];
  17054. },
  17055. enumerable: true,
  17056. configurable: true
  17057. });
  17058. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  17059. get: function () {
  17060. return [
  17061. new BABYLON.Color3(0.5, 1.0, 0.0),
  17062. new BABYLON.Color3(0.5, 1.0, 0.0),
  17063. new BABYLON.Color3(0.3, 0.4, 0.0),
  17064. new BABYLON.Color3(0.5, 1.0, 0.0),
  17065. new BABYLON.Color3(0.2, 0.0, 0.0),
  17066. new BABYLON.Color3(0.5, 1.0, 0.0)
  17067. ];
  17068. },
  17069. enumerable: true,
  17070. configurable: true
  17071. });
  17072. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  17073. get: function () {
  17074. return [
  17075. new BABYLON.Color3(0.5, 0.0, 0.1),
  17076. new BABYLON.Color3(0.9, 0.0, 0.0),
  17077. new BABYLON.Color3(0.2, 0.0, 0.0),
  17078. new BABYLON.Color3(1.0, 0.9, 0.0),
  17079. new BABYLON.Color3(0.1, 0.1, 0.1),
  17080. new BABYLON.Color3(0.9, 0.9, 0.9)
  17081. ];
  17082. },
  17083. enumerable: true,
  17084. configurable: true
  17085. });
  17086. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  17087. get: function () {
  17088. return [
  17089. new BABYLON.Color3(0.1, 0.0, 0.5),
  17090. new BABYLON.Color3(0.0, 0.0, 0.5),
  17091. new BABYLON.Color3(0.1, 0.0, 0.2),
  17092. new BABYLON.Color3(0.0, 0.0, 1.0),
  17093. new BABYLON.Color3(0.1, 0.2, 0.3),
  17094. new BABYLON.Color3(0.0, 0.2, 0.9)
  17095. ];
  17096. },
  17097. enumerable: true,
  17098. configurable: true
  17099. });
  17100. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  17101. get: function () {
  17102. return this._fireColors;
  17103. },
  17104. set: function (value) {
  17105. this._fireColors = value;
  17106. this.updateShaderUniforms();
  17107. },
  17108. enumerable: true,
  17109. configurable: true
  17110. });
  17111. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  17112. get: function () {
  17113. return this._time;
  17114. },
  17115. set: function (value) {
  17116. this._time = value;
  17117. this.updateShaderUniforms();
  17118. },
  17119. enumerable: true,
  17120. configurable: true
  17121. });
  17122. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  17123. get: function () {
  17124. return this._speed;
  17125. },
  17126. set: function (value) {
  17127. this._speed = value;
  17128. this.updateShaderUniforms();
  17129. },
  17130. enumerable: true,
  17131. configurable: true
  17132. });
  17133. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  17134. get: function () {
  17135. return this._alphaThreshold;
  17136. },
  17137. set: function (value) {
  17138. this._alphaThreshold = value;
  17139. this.updateShaderUniforms();
  17140. },
  17141. enumerable: true,
  17142. configurable: true
  17143. });
  17144. return FireProceduralTexture;
  17145. })(BABYLON.ProceduralTexture);
  17146. BABYLON.FireProceduralTexture = FireProceduralTexture;
  17147. var CloudProceduralTexture = (function (_super) {
  17148. __extends(CloudProceduralTexture, _super);
  17149. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17150. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  17151. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  17152. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  17153. this.updateShaderUniforms();
  17154. this.refreshRate = 0;
  17155. }
  17156. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  17157. this.setColor3("skyColor", this._skyColor);
  17158. this.setColor3("cloudColor", this._cloudColor);
  17159. };
  17160. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  17161. get: function () {
  17162. return this._skyColor;
  17163. },
  17164. set: function (value) {
  17165. this._skyColor = value;
  17166. this.updateShaderUniforms();
  17167. },
  17168. enumerable: true,
  17169. configurable: true
  17170. });
  17171. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  17172. get: function () {
  17173. return this._cloudColor;
  17174. },
  17175. set: function (value) {
  17176. this._cloudColor = value;
  17177. this.updateShaderUniforms();
  17178. },
  17179. enumerable: true,
  17180. configurable: true
  17181. });
  17182. return CloudProceduralTexture;
  17183. })(BABYLON.ProceduralTexture);
  17184. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  17185. var GrassProceduralTexture = (function (_super) {
  17186. __extends(GrassProceduralTexture, _super);
  17187. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17188. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  17189. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  17190. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  17191. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  17192. this._groundColor = new BABYLON.Color3(1, 1, 1);
  17193. this._grassColors = [
  17194. new BABYLON.Color3(0.29, 0.38, 0.02),
  17195. new BABYLON.Color3(0.36, 0.49, 0.09),
  17196. new BABYLON.Color3(0.51, 0.6, 0.28)
  17197. ];
  17198. this.updateShaderUniforms();
  17199. this.refreshRate = 0;
  17200. }
  17201. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  17202. this.setColor3("herb1Color", this._grassColors[0]);
  17203. this.setColor3("herb2Color", this._grassColors[1]);
  17204. this.setColor3("herb3Color", this._grassColors[2]);
  17205. this.setColor3("groundColor", this._groundColor);
  17206. };
  17207. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  17208. get: function () {
  17209. return this._grassColors;
  17210. },
  17211. set: function (value) {
  17212. this._grassColors = value;
  17213. this.updateShaderUniforms();
  17214. },
  17215. enumerable: true,
  17216. configurable: true
  17217. });
  17218. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  17219. get: function () {
  17220. return this._groundColor;
  17221. },
  17222. set: function (value) {
  17223. this.groundColor = value;
  17224. this.updateShaderUniforms();
  17225. },
  17226. enumerable: true,
  17227. configurable: true
  17228. });
  17229. return GrassProceduralTexture;
  17230. })(BABYLON.ProceduralTexture);
  17231. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  17232. var RoadProceduralTexture = (function (_super) {
  17233. __extends(RoadProceduralTexture, _super);
  17234. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17235. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  17236. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  17237. this.updateShaderUniforms();
  17238. this.refreshRate = 0;
  17239. }
  17240. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  17241. this.setColor3("roadColor", this._roadColor);
  17242. };
  17243. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  17244. get: function () {
  17245. return this._roadColor;
  17246. },
  17247. set: function (value) {
  17248. this._roadColor = value;
  17249. this.updateShaderUniforms();
  17250. },
  17251. enumerable: true,
  17252. configurable: true
  17253. });
  17254. return RoadProceduralTexture;
  17255. })(BABYLON.ProceduralTexture);
  17256. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  17257. var BrickProceduralTexture = (function (_super) {
  17258. __extends(BrickProceduralTexture, _super);
  17259. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17260. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  17261. this._numberOfBricksHeight = 15;
  17262. this._numberOfBricksWidth = 5;
  17263. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17264. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17265. this.updateShaderUniforms();
  17266. this.refreshRate = 0;
  17267. }
  17268. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  17269. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  17270. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  17271. this.setColor3("brickColor", this._brickColor);
  17272. this.setColor3("jointColor", this._jointColor);
  17273. };
  17274. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  17275. get: function () {
  17276. return this._numberOfBricksHeight;
  17277. },
  17278. set: function (value) {
  17279. this._numberOfBricksHeight = value;
  17280. this.updateShaderUniforms();
  17281. },
  17282. enumerable: true,
  17283. configurable: true
  17284. });
  17285. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  17286. get: function () {
  17287. return this._numberOfBricksWidth;
  17288. },
  17289. set: function (value) {
  17290. this._numberOfBricksHeight = value;
  17291. this.updateShaderUniforms();
  17292. },
  17293. enumerable: true,
  17294. configurable: true
  17295. });
  17296. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  17297. get: function () {
  17298. return this._jointColor;
  17299. },
  17300. set: function (value) {
  17301. this._jointColor = value;
  17302. this.updateShaderUniforms();
  17303. },
  17304. enumerable: true,
  17305. configurable: true
  17306. });
  17307. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  17308. get: function () {
  17309. return this._brickColor;
  17310. },
  17311. set: function (value) {
  17312. this._brickColor = value;
  17313. this.updateShaderUniforms();
  17314. },
  17315. enumerable: true,
  17316. configurable: true
  17317. });
  17318. return BrickProceduralTexture;
  17319. })(BABYLON.ProceduralTexture);
  17320. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  17321. var MarbleProceduralTexture = (function (_super) {
  17322. __extends(MarbleProceduralTexture, _super);
  17323. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17324. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  17325. this._numberOfTilesHeight = 3;
  17326. this._numberOfTilesWidth = 3;
  17327. this._amplitude = 9.0;
  17328. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17329. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17330. this.updateShaderUniforms();
  17331. this.refreshRate = 0;
  17332. }
  17333. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  17334. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  17335. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  17336. this.setFloat("amplitude", this._amplitude);
  17337. this.setColor3("marbleColor", this._marbleColor);
  17338. this.setColor3("jointColor", this._jointColor);
  17339. };
  17340. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  17341. get: function () {
  17342. return this._numberOfTilesHeight;
  17343. },
  17344. set: function (value) {
  17345. this._numberOfTilesHeight = value;
  17346. this.updateShaderUniforms();
  17347. },
  17348. enumerable: true,
  17349. configurable: true
  17350. });
  17351. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  17352. get: function () {
  17353. return this._numberOfTilesWidth;
  17354. },
  17355. set: function (value) {
  17356. this._numberOfTilesWidth = value;
  17357. this.updateShaderUniforms();
  17358. },
  17359. enumerable: true,
  17360. configurable: true
  17361. });
  17362. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  17363. get: function () {
  17364. return this._jointColor;
  17365. },
  17366. set: function (value) {
  17367. this._jointColor = value;
  17368. this.updateShaderUniforms();
  17369. },
  17370. enumerable: true,
  17371. configurable: true
  17372. });
  17373. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  17374. get: function () {
  17375. return this._marbleColor;
  17376. },
  17377. set: function (value) {
  17378. this._marbleColor = value;
  17379. this.updateShaderUniforms();
  17380. },
  17381. enumerable: true,
  17382. configurable: true
  17383. });
  17384. return MarbleProceduralTexture;
  17385. })(BABYLON.ProceduralTexture);
  17386. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  17387. })(BABYLON || (BABYLON = {}));
  17388. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  17389. var BABYLON;
  17390. (function (BABYLON) {
  17391. var EffectFallbacks = (function () {
  17392. function EffectFallbacks() {
  17393. this._defines = {};
  17394. this._currentRank = 32;
  17395. this._maxRank = -1;
  17396. }
  17397. EffectFallbacks.prototype.addFallback = function (rank, define) {
  17398. if (!this._defines[rank]) {
  17399. if (rank < this._currentRank) {
  17400. this._currentRank = rank;
  17401. }
  17402. if (rank > this._maxRank) {
  17403. this._maxRank = rank;
  17404. }
  17405. this._defines[rank] = new Array();
  17406. }
  17407. this._defines[rank].push(define);
  17408. };
  17409. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  17410. get: function () {
  17411. return this._currentRank <= this._maxRank;
  17412. },
  17413. enumerable: true,
  17414. configurable: true
  17415. });
  17416. EffectFallbacks.prototype.reduce = function (currentDefines) {
  17417. var currentFallbacks = this._defines[this._currentRank];
  17418. for (var index = 0; index < currentFallbacks.length; index++) {
  17419. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  17420. }
  17421. this._currentRank++;
  17422. return currentDefines;
  17423. };
  17424. return EffectFallbacks;
  17425. })();
  17426. BABYLON.EffectFallbacks = EffectFallbacks;
  17427. var Effect = (function () {
  17428. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  17429. var _this = this;
  17430. this._isReady = false;
  17431. this._compilationError = "";
  17432. this._valueCache = [];
  17433. this._engine = engine;
  17434. this.name = baseName;
  17435. this.defines = defines;
  17436. this._uniformsNames = uniformsNames.concat(samplers);
  17437. this._samplers = samplers;
  17438. this._attributesNames = attributesNames;
  17439. this.onError = onError;
  17440. this.onCompiled = onCompiled;
  17441. var vertexSource;
  17442. var fragmentSource;
  17443. if (baseName.vertexElement) {
  17444. vertexSource = document.getElementById(baseName.vertexElement);
  17445. if (!vertexSource) {
  17446. vertexSource = baseName.vertexElement;
  17447. }
  17448. }
  17449. else {
  17450. vertexSource = baseName.vertex || baseName;
  17451. }
  17452. if (baseName.fragmentElement) {
  17453. fragmentSource = document.getElementById(baseName.fragmentElement);
  17454. if (!fragmentSource) {
  17455. fragmentSource = baseName.fragmentElement;
  17456. }
  17457. }
  17458. else {
  17459. fragmentSource = baseName.fragment || baseName;
  17460. }
  17461. this._loadVertexShader(vertexSource, function (vertexCode) {
  17462. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  17463. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  17464. });
  17465. });
  17466. }
  17467. // Properties
  17468. Effect.prototype.isReady = function () {
  17469. return this._isReady;
  17470. };
  17471. Effect.prototype.getProgram = function () {
  17472. return this._program;
  17473. };
  17474. Effect.prototype.getAttributesNames = function () {
  17475. return this._attributesNames;
  17476. };
  17477. Effect.prototype.getAttributeLocation = function (index) {
  17478. return this._attributes[index];
  17479. };
  17480. Effect.prototype.getAttributeLocationByName = function (name) {
  17481. var index = this._attributesNames.indexOf(name);
  17482. return this._attributes[index];
  17483. };
  17484. Effect.prototype.getAttributesCount = function () {
  17485. return this._attributes.length;
  17486. };
  17487. Effect.prototype.getUniformIndex = function (uniformName) {
  17488. return this._uniformsNames.indexOf(uniformName);
  17489. };
  17490. Effect.prototype.getUniform = function (uniformName) {
  17491. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  17492. };
  17493. Effect.prototype.getSamplers = function () {
  17494. return this._samplers;
  17495. };
  17496. Effect.prototype.getCompilationError = function () {
  17497. return this._compilationError;
  17498. };
  17499. // Methods
  17500. Effect.prototype._loadVertexShader = function (vertex, callback) {
  17501. // DOM element ?
  17502. if (vertex instanceof HTMLElement) {
  17503. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  17504. callback(vertexCode);
  17505. return;
  17506. }
  17507. // Is in local store ?
  17508. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  17509. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  17510. return;
  17511. }
  17512. var vertexShaderUrl;
  17513. if (vertex[0] === "." || vertex[0] === "/") {
  17514. vertexShaderUrl = vertex;
  17515. }
  17516. else {
  17517. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  17518. }
  17519. // Vertex shader
  17520. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  17521. };
  17522. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  17523. // DOM element ?
  17524. if (fragment instanceof HTMLElement) {
  17525. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  17526. callback(fragmentCode);
  17527. return;
  17528. }
  17529. // Is in local store ?
  17530. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  17531. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  17532. return;
  17533. }
  17534. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  17535. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  17536. return;
  17537. }
  17538. var fragmentShaderUrl;
  17539. if (fragment[0] === "." || fragment[0] === "/") {
  17540. fragmentShaderUrl = fragment;
  17541. }
  17542. else {
  17543. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  17544. }
  17545. // Fragment shader
  17546. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  17547. };
  17548. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  17549. try {
  17550. var engine = this._engine;
  17551. if (!engine.getCaps().highPrecisionShaderSupported) {
  17552. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17553. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17554. }
  17555. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  17556. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  17557. this._attributes = engine.getAttributes(this._program, attributesNames);
  17558. for (var index = 0; index < this._samplers.length; index++) {
  17559. var sampler = this.getUniform(this._samplers[index]);
  17560. if (sampler == null) {
  17561. this._samplers.splice(index, 1);
  17562. index--;
  17563. }
  17564. }
  17565. engine.bindSamplers(this);
  17566. this._isReady = true;
  17567. if (this.onCompiled) {
  17568. this.onCompiled(this);
  17569. }
  17570. }
  17571. catch (e) {
  17572. // Is it a problem with precision?
  17573. if (e.message.indexOf("highp") !== -1) {
  17574. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17575. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17576. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17577. return;
  17578. }
  17579. // Let's go through fallbacks then
  17580. if (fallbacks && fallbacks.isMoreFallbacks) {
  17581. defines = fallbacks.reduce(defines);
  17582. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17583. }
  17584. else {
  17585. BABYLON.Tools.Error("Unable to compile effect: ");
  17586. if (this.name.vertexElement) {
  17587. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  17588. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  17589. }
  17590. else if (this.name.vertex) {
  17591. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  17592. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  17593. }
  17594. else {
  17595. BABYLON.Tools.Error("Vertex shader:" + this.name);
  17596. BABYLON.Tools.Error("Fragment shader:" + this.name);
  17597. }
  17598. BABYLON.Tools.Error("Defines: " + defines);
  17599. BABYLON.Tools.Error("Error: " + e.message);
  17600. this._compilationError = e.message;
  17601. if (this.onError) {
  17602. this.onError(this, this._compilationError);
  17603. }
  17604. }
  17605. }
  17606. };
  17607. Effect.prototype._bindTexture = function (channel, texture) {
  17608. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  17609. };
  17610. Effect.prototype.setTexture = function (channel, texture) {
  17611. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  17612. };
  17613. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17614. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  17615. };
  17616. //public _cacheMatrix(uniformName, matrix) {
  17617. // if (!this._valueCache[uniformName]) {
  17618. // this._valueCache[uniformName] = new BABYLON.Matrix();
  17619. // }
  17620. // for (var index = 0; index < 16; index++) {
  17621. // this._valueCache[uniformName].m[index] = matrix.m[index];
  17622. // }
  17623. //};
  17624. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  17625. if (!this._valueCache[uniformName]) {
  17626. this._valueCache[uniformName] = [x, y];
  17627. return;
  17628. }
  17629. this._valueCache[uniformName][0] = x;
  17630. this._valueCache[uniformName][1] = y;
  17631. };
  17632. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  17633. if (!this._valueCache[uniformName]) {
  17634. this._valueCache[uniformName] = [x, y, z];
  17635. return;
  17636. }
  17637. this._valueCache[uniformName][0] = x;
  17638. this._valueCache[uniformName][1] = y;
  17639. this._valueCache[uniformName][2] = z;
  17640. };
  17641. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  17642. if (!this._valueCache[uniformName]) {
  17643. this._valueCache[uniformName] = [x, y, z, w];
  17644. return;
  17645. }
  17646. this._valueCache[uniformName][0] = x;
  17647. this._valueCache[uniformName][1] = y;
  17648. this._valueCache[uniformName][2] = z;
  17649. this._valueCache[uniformName][3] = w;
  17650. };
  17651. Effect.prototype.setArray = function (uniformName, array) {
  17652. this._engine.setArray(this.getUniform(uniformName), array);
  17653. return this;
  17654. };
  17655. Effect.prototype.setArray2 = function (uniformName, array) {
  17656. this._engine.setArray2(this.getUniform(uniformName), array);
  17657. return this;
  17658. };
  17659. Effect.prototype.setArray3 = function (uniformName, array) {
  17660. this._engine.setArray3(this.getUniform(uniformName), array);
  17661. return this;
  17662. };
  17663. Effect.prototype.setArray4 = function (uniformName, array) {
  17664. this._engine.setArray4(this.getUniform(uniformName), array);
  17665. return this;
  17666. };
  17667. Effect.prototype.setMatrices = function (uniformName, matrices) {
  17668. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  17669. return this;
  17670. };
  17671. Effect.prototype.setMatrix = function (uniformName, matrix) {
  17672. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  17673. // return;
  17674. //this._cacheMatrix(uniformName, matrix);
  17675. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  17676. return this;
  17677. };
  17678. Effect.prototype.setFloat = function (uniformName, value) {
  17679. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  17680. return this;
  17681. this._valueCache[uniformName] = value;
  17682. this._engine.setFloat(this.getUniform(uniformName), value);
  17683. return this;
  17684. };
  17685. Effect.prototype.setBool = function (uniformName, bool) {
  17686. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  17687. return this;
  17688. this._valueCache[uniformName] = bool;
  17689. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  17690. return this;
  17691. };
  17692. Effect.prototype.setVector2 = function (uniformName, vector2) {
  17693. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  17694. return this;
  17695. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  17696. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  17697. return this;
  17698. };
  17699. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  17700. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  17701. return this;
  17702. this._cacheFloat2(uniformName, x, y);
  17703. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  17704. return this;
  17705. };
  17706. Effect.prototype.setVector3 = function (uniformName, vector3) {
  17707. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  17708. return this;
  17709. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  17710. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  17711. return this;
  17712. };
  17713. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  17714. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  17715. return this;
  17716. this._cacheFloat3(uniformName, x, y, z);
  17717. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  17718. return this;
  17719. };
  17720. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  17721. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  17722. return this;
  17723. this._cacheFloat4(uniformName, x, y, z, w);
  17724. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  17725. return this;
  17726. };
  17727. Effect.prototype.setColor3 = function (uniformName, color3) {
  17728. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  17729. return this;
  17730. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  17731. this._engine.setColor3(this.getUniform(uniformName), color3);
  17732. return this;
  17733. };
  17734. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  17735. 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)
  17736. return this;
  17737. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  17738. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  17739. return this;
  17740. };
  17741. // Statics
  17742. Effect.ShadersStore = {};
  17743. return Effect;
  17744. })();
  17745. BABYLON.Effect = Effect;
  17746. })(BABYLON || (BABYLON = {}));
  17747. //# sourceMappingURL=babylon.effect.js.map
  17748. var BABYLON;
  17749. (function (BABYLON) {
  17750. var Material = (function () {
  17751. function Material(name, scene, doNotAdd) {
  17752. this.name = name;
  17753. this.checkReadyOnEveryCall = true;
  17754. this.checkReadyOnlyOnce = false;
  17755. this.state = "";
  17756. this.alpha = 1.0;
  17757. this.backFaceCulling = true;
  17758. this._wasPreviouslyReady = false;
  17759. this._fillMode = Material.TriangleFillMode;
  17760. this.pointSize = 1.0;
  17761. this.zOffset = 0;
  17762. this.id = name;
  17763. this._scene = scene;
  17764. if (!doNotAdd) {
  17765. scene.materials.push(this);
  17766. }
  17767. }
  17768. Object.defineProperty(Material, "TriangleFillMode", {
  17769. get: function () {
  17770. return Material._TriangleFillMode;
  17771. },
  17772. enumerable: true,
  17773. configurable: true
  17774. });
  17775. Object.defineProperty(Material, "WireFrameFillMode", {
  17776. get: function () {
  17777. return Material._WireFrameFillMode;
  17778. },
  17779. enumerable: true,
  17780. configurable: true
  17781. });
  17782. Object.defineProperty(Material, "PointFillMode", {
  17783. get: function () {
  17784. return Material._PointFillMode;
  17785. },
  17786. enumerable: true,
  17787. configurable: true
  17788. });
  17789. Object.defineProperty(Material.prototype, "wireframe", {
  17790. get: function () {
  17791. return this._fillMode === Material.WireFrameFillMode;
  17792. },
  17793. set: function (value) {
  17794. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  17795. },
  17796. enumerable: true,
  17797. configurable: true
  17798. });
  17799. Object.defineProperty(Material.prototype, "pointsCloud", {
  17800. get: function () {
  17801. return this._fillMode === Material.PointFillMode;
  17802. },
  17803. set: function (value) {
  17804. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  17805. },
  17806. enumerable: true,
  17807. configurable: true
  17808. });
  17809. Object.defineProperty(Material.prototype, "fillMode", {
  17810. get: function () {
  17811. return this._fillMode;
  17812. },
  17813. set: function (value) {
  17814. this._fillMode = value;
  17815. },
  17816. enumerable: true,
  17817. configurable: true
  17818. });
  17819. Material.prototype.isReady = function (mesh, useInstances) {
  17820. return true;
  17821. };
  17822. Material.prototype.getEffect = function () {
  17823. return this._effect;
  17824. };
  17825. Material.prototype.getScene = function () {
  17826. return this._scene;
  17827. };
  17828. Material.prototype.needAlphaBlending = function () {
  17829. return (this.alpha < 1.0);
  17830. };
  17831. Material.prototype.needAlphaTesting = function () {
  17832. return false;
  17833. };
  17834. Material.prototype.getAlphaTestTexture = function () {
  17835. return null;
  17836. };
  17837. Material.prototype.trackCreation = function (onCompiled, onError) {
  17838. };
  17839. Material.prototype._preBind = function () {
  17840. var engine = this._scene.getEngine();
  17841. engine.enableEffect(this._effect);
  17842. engine.setState(this.backFaceCulling, this.zOffset);
  17843. };
  17844. Material.prototype.bind = function (world, mesh) {
  17845. this._scene._cachedMaterial = this;
  17846. if (this.onBind) {
  17847. this.onBind(this, mesh);
  17848. }
  17849. };
  17850. Material.prototype.bindOnlyWorldMatrix = function (world) {
  17851. };
  17852. Material.prototype.unbind = function () {
  17853. };
  17854. Material.prototype.dispose = function (forceDisposeEffect) {
  17855. // Remove from scene
  17856. var index = this._scene.materials.indexOf(this);
  17857. this._scene.materials.splice(index, 1);
  17858. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  17859. if (forceDisposeEffect && this._effect) {
  17860. this._scene.getEngine()._releaseEffect(this._effect);
  17861. this._effect = null;
  17862. }
  17863. // Callback
  17864. if (this.onDispose) {
  17865. this.onDispose();
  17866. }
  17867. };
  17868. Material._TriangleFillMode = 0;
  17869. Material._WireFrameFillMode = 1;
  17870. Material._PointFillMode = 2;
  17871. return Material;
  17872. })();
  17873. BABYLON.Material = Material;
  17874. })(BABYLON || (BABYLON = {}));
  17875. //# sourceMappingURL=babylon.material.js.map
  17876. var BABYLON;
  17877. (function (BABYLON) {
  17878. var maxSimultaneousLights = 4;
  17879. var FresnelParameters = (function () {
  17880. function FresnelParameters() {
  17881. this.isEnabled = true;
  17882. this.leftColor = BABYLON.Color3.White();
  17883. this.rightColor = BABYLON.Color3.Black();
  17884. this.bias = 0;
  17885. this.power = 1;
  17886. }
  17887. return FresnelParameters;
  17888. })();
  17889. BABYLON.FresnelParameters = FresnelParameters;
  17890. var StandardMaterial = (function (_super) {
  17891. __extends(StandardMaterial, _super);
  17892. function StandardMaterial(name, scene) {
  17893. var _this = this;
  17894. _super.call(this, name, scene);
  17895. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  17896. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  17897. this.specularColor = new BABYLON.Color3(1, 1, 1);
  17898. this.specularPower = 64;
  17899. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  17900. this.useAlphaFromDiffuseTexture = false;
  17901. this.useSpecularOverAlpha = true;
  17902. this.fogEnabled = true;
  17903. this._cachedDefines = null;
  17904. this._renderTargets = new BABYLON.SmartArray(16);
  17905. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  17906. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  17907. this._scaledDiffuse = new BABYLON.Color3();
  17908. this._scaledSpecular = new BABYLON.Color3();
  17909. this.getRenderTargetTextures = function () {
  17910. _this._renderTargets.reset();
  17911. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  17912. _this._renderTargets.push(_this.reflectionTexture);
  17913. }
  17914. return _this._renderTargets;
  17915. };
  17916. }
  17917. StandardMaterial.prototype.needAlphaBlending = function () {
  17918. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  17919. };
  17920. StandardMaterial.prototype.needAlphaTesting = function () {
  17921. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  17922. };
  17923. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  17924. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  17925. };
  17926. StandardMaterial.prototype.getAlphaTestTexture = function () {
  17927. return this.diffuseTexture;
  17928. };
  17929. // Methods
  17930. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  17931. if (this.checkReadyOnlyOnce) {
  17932. if (this._wasPreviouslyReady) {
  17933. return true;
  17934. }
  17935. }
  17936. var scene = this.getScene();
  17937. if (!this.checkReadyOnEveryCall) {
  17938. if (this._renderId === scene.getRenderId()) {
  17939. return true;
  17940. }
  17941. }
  17942. var engine = scene.getEngine();
  17943. var defines = [];
  17944. var fallbacks = new BABYLON.EffectFallbacks();
  17945. var needNormals = false;
  17946. var needUVs = false;
  17947. // Textures
  17948. if (scene.texturesEnabled) {
  17949. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  17950. if (!this.diffuseTexture.isReady()) {
  17951. return false;
  17952. }
  17953. else {
  17954. needUVs = true;
  17955. defines.push("#define DIFFUSE");
  17956. }
  17957. }
  17958. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  17959. if (!this.ambientTexture.isReady()) {
  17960. return false;
  17961. }
  17962. else {
  17963. needUVs = true;
  17964. defines.push("#define AMBIENT");
  17965. }
  17966. }
  17967. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  17968. if (!this.opacityTexture.isReady()) {
  17969. return false;
  17970. }
  17971. else {
  17972. needUVs = true;
  17973. defines.push("#define OPACITY");
  17974. if (this.opacityTexture.getAlphaFromRGB) {
  17975. defines.push("#define OPACITYRGB");
  17976. }
  17977. }
  17978. }
  17979. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  17980. if (!this.reflectionTexture.isReady()) {
  17981. return false;
  17982. }
  17983. else {
  17984. needNormals = true;
  17985. needUVs = true;
  17986. defines.push("#define REFLECTION");
  17987. fallbacks.addFallback(0, "REFLECTION");
  17988. }
  17989. }
  17990. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  17991. if (!this.emissiveTexture.isReady()) {
  17992. return false;
  17993. }
  17994. else {
  17995. needUVs = true;
  17996. defines.push("#define EMISSIVE");
  17997. }
  17998. }
  17999. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18000. if (!this.specularTexture.isReady()) {
  18001. return false;
  18002. }
  18003. else {
  18004. needUVs = true;
  18005. defines.push("#define SPECULAR");
  18006. fallbacks.addFallback(0, "SPECULAR");
  18007. }
  18008. }
  18009. }
  18010. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  18011. if (!this.bumpTexture.isReady()) {
  18012. return false;
  18013. }
  18014. else {
  18015. needUVs = true;
  18016. defines.push("#define BUMP");
  18017. fallbacks.addFallback(0, "BUMP");
  18018. }
  18019. }
  18020. // Effect
  18021. if (this.useSpecularOverAlpha) {
  18022. defines.push("#define SPECULAROVERALPHA");
  18023. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  18024. }
  18025. if (scene.clipPlane) {
  18026. defines.push("#define CLIPPLANE");
  18027. }
  18028. if (engine.getAlphaTesting()) {
  18029. defines.push("#define ALPHATEST");
  18030. }
  18031. if (this._shouldUseAlphaFromDiffuseTexture()) {
  18032. defines.push("#define ALPHAFROMDIFFUSE");
  18033. }
  18034. // Point size
  18035. if (this.pointsCloud || scene.forcePointsCloud) {
  18036. defines.push("#define POINTSIZE");
  18037. }
  18038. // Fog
  18039. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18040. defines.push("#define FOG");
  18041. fallbacks.addFallback(1, "FOG");
  18042. }
  18043. var shadowsActivated = false;
  18044. var lightIndex = 0;
  18045. if (scene.lightsEnabled) {
  18046. for (var index = 0; index < scene.lights.length; index++) {
  18047. var light = scene.lights[index];
  18048. if (!light.isEnabled()) {
  18049. continue;
  18050. }
  18051. // Excluded check
  18052. if (light._excludedMeshesIds.length > 0) {
  18053. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18054. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18055. if (excludedMesh) {
  18056. light.excludedMeshes.push(excludedMesh);
  18057. }
  18058. }
  18059. light._excludedMeshesIds = [];
  18060. }
  18061. // Included check
  18062. if (light._includedOnlyMeshesIds.length > 0) {
  18063. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18064. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18065. if (includedOnlyMesh) {
  18066. light.includedOnlyMeshes.push(includedOnlyMesh);
  18067. }
  18068. }
  18069. light._includedOnlyMeshesIds = [];
  18070. }
  18071. if (!light.canAffectMesh(mesh)) {
  18072. continue;
  18073. }
  18074. needNormals = true;
  18075. defines.push("#define LIGHT" + lightIndex);
  18076. if (lightIndex > 0) {
  18077. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  18078. }
  18079. var type;
  18080. if (light instanceof BABYLON.SpotLight) {
  18081. type = "#define SPOTLIGHT" + lightIndex;
  18082. }
  18083. else if (light instanceof BABYLON.HemisphericLight) {
  18084. type = "#define HEMILIGHT" + lightIndex;
  18085. }
  18086. else {
  18087. type = "#define POINTDIRLIGHT" + lightIndex;
  18088. }
  18089. defines.push(type);
  18090. if (lightIndex > 0) {
  18091. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  18092. }
  18093. // Shadows
  18094. if (scene.shadowsEnabled) {
  18095. var shadowGenerator = light.getShadowGenerator();
  18096. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18097. defines.push("#define SHADOW" + lightIndex);
  18098. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  18099. if (!shadowsActivated) {
  18100. defines.push("#define SHADOWS");
  18101. shadowsActivated = true;
  18102. }
  18103. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18104. defines.push("#define SHADOWVSM" + lightIndex);
  18105. if (lightIndex > 0) {
  18106. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  18107. }
  18108. }
  18109. if (shadowGenerator.usePoissonSampling) {
  18110. defines.push("#define SHADOWPCF" + lightIndex);
  18111. if (lightIndex > 0) {
  18112. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  18113. }
  18114. }
  18115. }
  18116. }
  18117. lightIndex++;
  18118. if (lightIndex === maxSimultaneousLights)
  18119. break;
  18120. }
  18121. }
  18122. if (StandardMaterial.FresnelEnabled) {
  18123. // Fresnel
  18124. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  18125. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  18126. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  18127. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18128. var fresnelRank = 1;
  18129. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18130. defines.push("#define DIFFUSEFRESNEL");
  18131. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  18132. fresnelRank++;
  18133. }
  18134. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18135. defines.push("#define OPACITYFRESNEL");
  18136. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  18137. fresnelRank++;
  18138. }
  18139. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18140. defines.push("#define REFLECTIONFRESNEL");
  18141. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  18142. fresnelRank++;
  18143. }
  18144. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18145. defines.push("#define EMISSIVEFRESNEL");
  18146. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  18147. fresnelRank++;
  18148. }
  18149. needNormals = true;
  18150. defines.push("#define FRESNEL");
  18151. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  18152. }
  18153. }
  18154. // Attribs
  18155. var attribs = [BABYLON.VertexBuffer.PositionKind];
  18156. if (mesh) {
  18157. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18158. attribs.push(BABYLON.VertexBuffer.NormalKind);
  18159. defines.push("#define NORMAL");
  18160. }
  18161. if (needUVs) {
  18162. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18163. attribs.push(BABYLON.VertexBuffer.UVKind);
  18164. defines.push("#define UV1");
  18165. }
  18166. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18167. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  18168. defines.push("#define UV2");
  18169. }
  18170. }
  18171. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18172. attribs.push(BABYLON.VertexBuffer.ColorKind);
  18173. defines.push("#define VERTEXCOLOR");
  18174. if (mesh.hasVertexAlpha) {
  18175. defines.push("#define VERTEXALPHA");
  18176. }
  18177. }
  18178. if (mesh.useBones) {
  18179. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18180. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18181. defines.push("#define BONES");
  18182. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  18183. defines.push("#define BONES4");
  18184. fallbacks.addFallback(0, "BONES4");
  18185. }
  18186. // Instances
  18187. if (useInstances) {
  18188. defines.push("#define INSTANCES");
  18189. attribs.push("world0");
  18190. attribs.push("world1");
  18191. attribs.push("world2");
  18192. attribs.push("world3");
  18193. }
  18194. }
  18195. // Get correct effect
  18196. var join = defines.join("\n");
  18197. if (this._cachedDefines !== join) {
  18198. this._cachedDefines = join;
  18199. scene.resetCachedMaterial();
  18200. // Legacy browser patch
  18201. var shaderName = "default";
  18202. if (!scene.getEngine().getCaps().standardDerivatives) {
  18203. shaderName = "legacydefault";
  18204. }
  18205. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  18206. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  18207. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  18208. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  18209. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  18210. "vFogInfos", "vFogColor", "pointSize",
  18211. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  18212. "mBones",
  18213. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  18214. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  18215. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  18216. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  18217. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  18218. ], join, fallbacks, this.onCompiled, this.onError);
  18219. }
  18220. if (!this._effect.isReady()) {
  18221. return false;
  18222. }
  18223. this._renderId = scene.getRenderId();
  18224. this._wasPreviouslyReady = true;
  18225. return true;
  18226. };
  18227. StandardMaterial.prototype.unbind = function () {
  18228. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  18229. this._effect.setTexture("reflection2DSampler", null);
  18230. }
  18231. };
  18232. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  18233. this._effect.setMatrix("world", world);
  18234. };
  18235. StandardMaterial.prototype.bind = function (world, mesh) {
  18236. var scene = this.getScene();
  18237. // Matrices
  18238. this.bindOnlyWorldMatrix(world);
  18239. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  18240. // Bones
  18241. if (mesh && mesh.useBones) {
  18242. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  18243. }
  18244. if (scene.getCachedMaterial() !== this) {
  18245. if (StandardMaterial.FresnelEnabled) {
  18246. // Fresnel
  18247. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18248. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  18249. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  18250. }
  18251. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18252. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  18253. }
  18254. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18255. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  18256. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  18257. }
  18258. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18259. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  18260. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  18261. }
  18262. }
  18263. // Textures
  18264. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18265. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  18266. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  18267. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  18268. }
  18269. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18270. this._effect.setTexture("ambientSampler", this.ambientTexture);
  18271. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  18272. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  18273. }
  18274. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18275. this._effect.setTexture("opacitySampler", this.opacityTexture);
  18276. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  18277. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  18278. }
  18279. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18280. if (this.reflectionTexture.isCube) {
  18281. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  18282. }
  18283. else {
  18284. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  18285. }
  18286. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  18287. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  18288. }
  18289. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18290. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  18291. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  18292. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  18293. }
  18294. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18295. this._effect.setTexture("specularSampler", this.specularTexture);
  18296. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  18297. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  18298. }
  18299. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  18300. this._effect.setTexture("bumpSampler", this.bumpTexture);
  18301. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  18302. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  18303. }
  18304. // Clip plane
  18305. if (scene.clipPlane) {
  18306. var clipPlane = scene.clipPlane;
  18307. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  18308. }
  18309. // Point size
  18310. if (this.pointsCloud) {
  18311. this._effect.setFloat("pointSize", this.pointSize);
  18312. }
  18313. // Colors
  18314. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  18315. // Scaling down color according to emissive
  18316. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  18317. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  18318. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  18319. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  18320. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  18321. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  18322. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  18323. }
  18324. // Scaling down color according to emissive
  18325. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  18326. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  18327. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  18328. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  18329. if (scene.lightsEnabled) {
  18330. var lightIndex = 0;
  18331. for (var index = 0; index < scene.lights.length; index++) {
  18332. var light = scene.lights[index];
  18333. if (!light.isEnabled()) {
  18334. continue;
  18335. }
  18336. if (!light.canAffectMesh(mesh)) {
  18337. continue;
  18338. }
  18339. if (light instanceof BABYLON.PointLight) {
  18340. // Point Light
  18341. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  18342. }
  18343. else if (light instanceof BABYLON.DirectionalLight) {
  18344. // Directional Light
  18345. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  18346. }
  18347. else if (light instanceof BABYLON.SpotLight) {
  18348. // Spot Light
  18349. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  18350. }
  18351. else if (light instanceof BABYLON.HemisphericLight) {
  18352. // Hemispheric Light
  18353. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  18354. }
  18355. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  18356. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  18357. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  18358. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  18359. // Shadows
  18360. if (scene.shadowsEnabled) {
  18361. var shadowGenerator = light.getShadowGenerator();
  18362. if (mesh.receiveShadows && shadowGenerator) {
  18363. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  18364. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  18365. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  18366. }
  18367. }
  18368. lightIndex++;
  18369. if (lightIndex === maxSimultaneousLights)
  18370. break;
  18371. }
  18372. }
  18373. // View
  18374. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  18375. this._effect.setMatrix("view", scene.getViewMatrix());
  18376. }
  18377. // Fog
  18378. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  18379. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  18380. this._effect.setColor3("vFogColor", scene.fogColor);
  18381. }
  18382. _super.prototype.bind.call(this, world, mesh);
  18383. };
  18384. StandardMaterial.prototype.getAnimatables = function () {
  18385. var results = [];
  18386. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  18387. results.push(this.diffuseTexture);
  18388. }
  18389. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  18390. results.push(this.ambientTexture);
  18391. }
  18392. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  18393. results.push(this.opacityTexture);
  18394. }
  18395. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  18396. results.push(this.reflectionTexture);
  18397. }
  18398. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  18399. results.push(this.emissiveTexture);
  18400. }
  18401. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  18402. results.push(this.specularTexture);
  18403. }
  18404. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  18405. results.push(this.bumpTexture);
  18406. }
  18407. return results;
  18408. };
  18409. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  18410. if (this.diffuseTexture) {
  18411. this.diffuseTexture.dispose();
  18412. }
  18413. if (this.ambientTexture) {
  18414. this.ambientTexture.dispose();
  18415. }
  18416. if (this.opacityTexture) {
  18417. this.opacityTexture.dispose();
  18418. }
  18419. if (this.reflectionTexture) {
  18420. this.reflectionTexture.dispose();
  18421. }
  18422. if (this.emissiveTexture) {
  18423. this.emissiveTexture.dispose();
  18424. }
  18425. if (this.specularTexture) {
  18426. this.specularTexture.dispose();
  18427. }
  18428. if (this.bumpTexture) {
  18429. this.bumpTexture.dispose();
  18430. }
  18431. _super.prototype.dispose.call(this, forceDisposeEffect);
  18432. };
  18433. StandardMaterial.prototype.clone = function (name) {
  18434. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  18435. // Base material
  18436. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  18437. newStandardMaterial.alpha = this.alpha;
  18438. newStandardMaterial.fillMode = this.fillMode;
  18439. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  18440. // Standard material
  18441. if (this.diffuseTexture && this.diffuseTexture.clone) {
  18442. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  18443. }
  18444. if (this.ambientTexture && this.ambientTexture.clone) {
  18445. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  18446. }
  18447. if (this.opacityTexture && this.opacityTexture.clone) {
  18448. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  18449. }
  18450. if (this.reflectionTexture && this.reflectionTexture.clone) {
  18451. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  18452. }
  18453. if (this.emissiveTexture && this.emissiveTexture.clone) {
  18454. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  18455. }
  18456. if (this.specularTexture && this.specularTexture.clone) {
  18457. newStandardMaterial.specularTexture = this.specularTexture.clone();
  18458. }
  18459. if (this.bumpTexture && this.bumpTexture.clone) {
  18460. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  18461. }
  18462. newStandardMaterial.ambientColor = this.ambientColor.clone();
  18463. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  18464. newStandardMaterial.specularColor = this.specularColor.clone();
  18465. newStandardMaterial.specularPower = this.specularPower;
  18466. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  18467. return newStandardMaterial;
  18468. };
  18469. // Statics
  18470. // Flags used to enable or disable a type of texture for all Standard Materials
  18471. StandardMaterial.DiffuseTextureEnabled = true;
  18472. StandardMaterial.AmbientTextureEnabled = true;
  18473. StandardMaterial.OpacityTextureEnabled = true;
  18474. StandardMaterial.ReflectionTextureEnabled = true;
  18475. StandardMaterial.EmissiveTextureEnabled = true;
  18476. StandardMaterial.SpecularTextureEnabled = true;
  18477. StandardMaterial.BumpTextureEnabled = true;
  18478. StandardMaterial.FresnelEnabled = true;
  18479. return StandardMaterial;
  18480. })(BABYLON.Material);
  18481. BABYLON.StandardMaterial = StandardMaterial;
  18482. })(BABYLON || (BABYLON = {}));
  18483. //# sourceMappingURL=babylon.standardMaterial.js.map
  18484. var BABYLON;
  18485. (function (BABYLON) {
  18486. var MultiMaterial = (function (_super) {
  18487. __extends(MultiMaterial, _super);
  18488. function MultiMaterial(name, scene) {
  18489. _super.call(this, name, scene, true);
  18490. this.subMaterials = new Array();
  18491. scene.multiMaterials.push(this);
  18492. }
  18493. // Properties
  18494. MultiMaterial.prototype.getSubMaterial = function (index) {
  18495. if (index < 0 || index >= this.subMaterials.length) {
  18496. return this.getScene().defaultMaterial;
  18497. }
  18498. return this.subMaterials[index];
  18499. };
  18500. // Methods
  18501. MultiMaterial.prototype.isReady = function (mesh) {
  18502. for (var index = 0; index < this.subMaterials.length; index++) {
  18503. var subMaterial = this.subMaterials[index];
  18504. if (subMaterial) {
  18505. if (!this.subMaterials[index].isReady(mesh)) {
  18506. return false;
  18507. }
  18508. }
  18509. }
  18510. return true;
  18511. };
  18512. MultiMaterial.prototype.clone = function (name) {
  18513. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  18514. for (var index = 0; index < this.subMaterials.length; index++) {
  18515. var subMaterial = this.subMaterials[index];
  18516. newMultiMaterial.subMaterials.push(subMaterial);
  18517. }
  18518. return newMultiMaterial;
  18519. };
  18520. return MultiMaterial;
  18521. })(BABYLON.Material);
  18522. BABYLON.MultiMaterial = MultiMaterial;
  18523. })(BABYLON || (BABYLON = {}));
  18524. //# sourceMappingURL=babylon.multiMaterial.js.map
  18525. var BABYLON;
  18526. (function (BABYLON) {
  18527. var SceneLoader = (function () {
  18528. function SceneLoader() {
  18529. }
  18530. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  18531. get: function () {
  18532. return SceneLoader._ForceFullSceneLoadingForIncremental;
  18533. },
  18534. set: function (value) {
  18535. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  18536. },
  18537. enumerable: true,
  18538. configurable: true
  18539. });
  18540. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  18541. get: function () {
  18542. return SceneLoader._ShowLoadingScreen;
  18543. },
  18544. set: function (value) {
  18545. SceneLoader._ShowLoadingScreen = value;
  18546. },
  18547. enumerable: true,
  18548. configurable: true
  18549. });
  18550. SceneLoader._getPluginForFilename = function (sceneFilename) {
  18551. var dotPosition = sceneFilename.lastIndexOf(".");
  18552. var queryStringPosition = sceneFilename.indexOf("?");
  18553. if (queryStringPosition === -1) {
  18554. queryStringPosition = sceneFilename.length;
  18555. }
  18556. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  18557. for (var index = 0; index < this._registeredPlugins.length; index++) {
  18558. var plugin = this._registeredPlugins[index];
  18559. if (plugin.extensions.indexOf(extension) !== -1) {
  18560. return plugin;
  18561. }
  18562. }
  18563. return this._registeredPlugins[this._registeredPlugins.length - 1];
  18564. };
  18565. // Public functions
  18566. SceneLoader.RegisterPlugin = function (plugin) {
  18567. plugin.extensions = plugin.extensions.toLowerCase();
  18568. SceneLoader._registeredPlugins.push(plugin);
  18569. };
  18570. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18571. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18572. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18573. return;
  18574. }
  18575. var loadingToken = {};
  18576. scene._addPendingData(loadingToken);
  18577. var manifestChecked = function (success) {
  18578. scene.database = database;
  18579. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  18580. var importMeshFromData = function (data) {
  18581. var meshes = [];
  18582. var particleSystems = [];
  18583. var skeletons = [];
  18584. try {
  18585. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  18586. if (onerror) {
  18587. onerror(scene, 'unable to load the scene');
  18588. }
  18589. scene._removePendingData(loadingToken);
  18590. return;
  18591. }
  18592. }
  18593. catch (e) {
  18594. if (onerror) {
  18595. onerror(scene, e);
  18596. }
  18597. scene._removePendingData(loadingToken);
  18598. return;
  18599. }
  18600. if (onsuccess) {
  18601. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  18602. onsuccess(meshes, particleSystems, skeletons);
  18603. scene._removePendingData(loadingToken);
  18604. }
  18605. };
  18606. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18607. // Direct load
  18608. importMeshFromData(sceneFilename.substr(5));
  18609. return;
  18610. }
  18611. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  18612. importMeshFromData(data);
  18613. }, progressCallBack, database);
  18614. };
  18615. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18616. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18617. };
  18618. /**
  18619. * Load a scene
  18620. * @param rootUrl a string that defines the root url for scene and resources
  18621. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18622. * @param engine is the instance of BABYLON.Engine to use to create the scene
  18623. */
  18624. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  18625. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  18626. };
  18627. /**
  18628. * Append a scene
  18629. * @param rootUrl a string that defines the root url for scene and resources
  18630. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18631. * @param scene is the instance of BABYLON.Scene to append to
  18632. */
  18633. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18634. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18635. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18636. return;
  18637. }
  18638. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  18639. var database;
  18640. var loadingToken = {};
  18641. scene._addPendingData(loadingToken);
  18642. if (SceneLoader.ShowLoadingScreen) {
  18643. scene.getEngine().displayLoadingUI();
  18644. }
  18645. var loadSceneFromData = function (data) {
  18646. scene.database = database;
  18647. if (!plugin.load(scene, data, rootUrl)) {
  18648. if (onerror) {
  18649. onerror(scene);
  18650. }
  18651. scene._removePendingData(loadingToken);
  18652. scene.getEngine().hideLoadingUI();
  18653. return;
  18654. }
  18655. if (onsuccess) {
  18656. onsuccess(scene);
  18657. }
  18658. scene._removePendingData(loadingToken);
  18659. if (SceneLoader.ShowLoadingScreen) {
  18660. scene.executeWhenReady(function () {
  18661. scene.getEngine().hideLoadingUI();
  18662. });
  18663. }
  18664. };
  18665. var manifestChecked = function (success) {
  18666. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  18667. };
  18668. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18669. // Direct load
  18670. loadSceneFromData(sceneFilename.substr(5));
  18671. return;
  18672. }
  18673. if (rootUrl.indexOf("file:") === -1) {
  18674. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18675. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18676. }
  18677. else {
  18678. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  18679. }
  18680. };
  18681. // Flags
  18682. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  18683. SceneLoader._ShowLoadingScreen = true;
  18684. // Members
  18685. SceneLoader._registeredPlugins = new Array();
  18686. return SceneLoader;
  18687. })();
  18688. BABYLON.SceneLoader = SceneLoader;
  18689. ;
  18690. })(BABYLON || (BABYLON = {}));
  18691. //# sourceMappingURL=babylon.sceneLoader.js.map
  18692. var BABYLON;
  18693. (function (BABYLON) {
  18694. var Internals;
  18695. (function (Internals) {
  18696. var checkColors4 = function (colors, count) {
  18697. // Check if color3 was used
  18698. if (colors.length === count * 3) {
  18699. var colors4 = [];
  18700. for (var index = 0; index < colors.length; index += 3) {
  18701. var newIndex = (index / 3) * 4;
  18702. colors4[newIndex] = colors[index];
  18703. colors4[newIndex + 1] = colors[index + 1];
  18704. colors4[newIndex + 2] = colors[index + 2];
  18705. colors4[newIndex + 3] = 1.0;
  18706. }
  18707. return colors4;
  18708. }
  18709. return colors;
  18710. };
  18711. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  18712. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  18713. texture.name = parsedTexture.name;
  18714. texture.hasAlpha = parsedTexture.hasAlpha;
  18715. texture.level = parsedTexture.level;
  18716. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18717. return texture;
  18718. };
  18719. var loadTexture = function (rootUrl, parsedTexture, scene) {
  18720. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18721. return null;
  18722. }
  18723. if (parsedTexture.isCube) {
  18724. return loadCubeTexture(rootUrl, parsedTexture, scene);
  18725. }
  18726. var texture;
  18727. if (parsedTexture.mirrorPlane) {
  18728. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18729. texture._waitingRenderList = parsedTexture.renderList;
  18730. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18731. }
  18732. else if (parsedTexture.isRenderTarget) {
  18733. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18734. texture._waitingRenderList = parsedTexture.renderList;
  18735. }
  18736. else {
  18737. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  18738. }
  18739. texture.name = parsedTexture.name;
  18740. texture.hasAlpha = parsedTexture.hasAlpha;
  18741. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  18742. texture.level = parsedTexture.level;
  18743. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  18744. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18745. texture.uOffset = parsedTexture.uOffset;
  18746. texture.vOffset = parsedTexture.vOffset;
  18747. texture.uScale = parsedTexture.uScale;
  18748. texture.vScale = parsedTexture.vScale;
  18749. texture.uAng = parsedTexture.uAng;
  18750. texture.vAng = parsedTexture.vAng;
  18751. texture.wAng = parsedTexture.wAng;
  18752. texture.wrapU = parsedTexture.wrapU;
  18753. texture.wrapV = parsedTexture.wrapV;
  18754. // Animations
  18755. if (parsedTexture.animations) {
  18756. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18757. var parsedAnimation = parsedTexture.animations[animationIndex];
  18758. texture.animations.push(parseAnimation(parsedAnimation));
  18759. }
  18760. }
  18761. return texture;
  18762. };
  18763. var parseSkeleton = function (parsedSkeleton, scene) {
  18764. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  18765. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  18766. var parsedBone = parsedSkeleton.bones[index];
  18767. var parentBone = null;
  18768. if (parsedBone.parentBoneIndex > -1) {
  18769. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  18770. }
  18771. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  18772. if (parsedBone.animation) {
  18773. bone.animations.push(parseAnimation(parsedBone.animation));
  18774. }
  18775. }
  18776. return skeleton;
  18777. };
  18778. var parseFresnelParameters = function (parsedFresnelParameters) {
  18779. var fresnelParameters = new BABYLON.FresnelParameters();
  18780. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18781. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18782. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18783. fresnelParameters.bias = parsedFresnelParameters.bias;
  18784. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18785. return fresnelParameters;
  18786. };
  18787. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  18788. var material;
  18789. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  18790. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  18791. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  18792. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  18793. material.specularPower = parsedMaterial.specularPower;
  18794. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  18795. material.alpha = parsedMaterial.alpha;
  18796. material.id = parsedMaterial.id;
  18797. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  18798. material.backFaceCulling = parsedMaterial.backFaceCulling;
  18799. material.wireframe = parsedMaterial.wireframe;
  18800. if (parsedMaterial.diffuseTexture) {
  18801. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  18802. }
  18803. if (parsedMaterial.diffuseFresnelParameters) {
  18804. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  18805. }
  18806. if (parsedMaterial.ambientTexture) {
  18807. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  18808. }
  18809. if (parsedMaterial.opacityTexture) {
  18810. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  18811. }
  18812. if (parsedMaterial.opacityFresnelParameters) {
  18813. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  18814. }
  18815. if (parsedMaterial.reflectionTexture) {
  18816. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  18817. }
  18818. if (parsedMaterial.reflectionFresnelParameters) {
  18819. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  18820. }
  18821. if (parsedMaterial.emissiveTexture) {
  18822. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  18823. }
  18824. if (parsedMaterial.emissiveFresnelParameters) {
  18825. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  18826. }
  18827. if (parsedMaterial.specularTexture) {
  18828. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  18829. }
  18830. if (parsedMaterial.bumpTexture) {
  18831. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  18832. }
  18833. return material;
  18834. };
  18835. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  18836. for (var index = 0; index < parsedData.materials.length; index++) {
  18837. var parsedMaterial = parsedData.materials[index];
  18838. if (parsedMaterial.id === id) {
  18839. return parseMaterial(parsedMaterial, scene, rootUrl);
  18840. }
  18841. }
  18842. return null;
  18843. };
  18844. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  18845. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18846. multiMaterial.id = parsedMultiMaterial.id;
  18847. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18848. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18849. var subMatId = parsedMultiMaterial.materials[matIndex];
  18850. if (subMatId) {
  18851. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18852. }
  18853. else {
  18854. multiMaterial.subMaterials.push(null);
  18855. }
  18856. }
  18857. return multiMaterial;
  18858. };
  18859. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  18860. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  18861. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  18862. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  18863. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  18864. var parsedFlare = parsedLensFlareSystem.flares[index];
  18865. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  18866. }
  18867. return lensFlareSystem;
  18868. };
  18869. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  18870. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  18871. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  18872. if (parsedParticleSystem.textureName) {
  18873. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  18874. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  18875. }
  18876. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  18877. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  18878. particleSystem.minSize = parsedParticleSystem.minSize;
  18879. particleSystem.maxSize = parsedParticleSystem.maxSize;
  18880. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  18881. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  18882. particleSystem.emitter = emitter;
  18883. particleSystem.emitRate = parsedParticleSystem.emitRate;
  18884. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  18885. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  18886. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  18887. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  18888. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  18889. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  18890. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  18891. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  18892. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  18893. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  18894. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  18895. particleSystem.blendMode = parsedParticleSystem.blendMode;
  18896. particleSystem.start();
  18897. return particleSystem;
  18898. };
  18899. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  18900. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  18901. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  18902. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  18903. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  18904. shadowGenerator.getShadowMap().renderList.push(mesh);
  18905. }
  18906. if (parsedShadowGenerator.usePoissonSampling) {
  18907. shadowGenerator.usePoissonSampling = true;
  18908. }
  18909. else if (parsedShadowGenerator.useVarianceShadowMap) {
  18910. shadowGenerator.useVarianceShadowMap = true;
  18911. }
  18912. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  18913. shadowGenerator.useBlurVarianceShadowMap = true;
  18914. if (parsedShadowGenerator.blurScale) {
  18915. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  18916. }
  18917. if (parsedShadowGenerator.blurBoxOffset) {
  18918. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  18919. }
  18920. }
  18921. if (parsedShadowGenerator.bias !== undefined) {
  18922. shadowGenerator.bias = parsedShadowGenerator.bias;
  18923. }
  18924. return shadowGenerator;
  18925. };
  18926. var parseAnimation = function (parsedAnimation) {
  18927. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  18928. var dataType = parsedAnimation.dataType;
  18929. var keys = [];
  18930. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  18931. var key = parsedAnimation.keys[index];
  18932. var data;
  18933. switch (dataType) {
  18934. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18935. data = key.values[0];
  18936. break;
  18937. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18938. data = BABYLON.Quaternion.FromArray(key.values);
  18939. break;
  18940. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18941. data = BABYLON.Matrix.FromArray(key.values);
  18942. break;
  18943. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18944. default:
  18945. data = BABYLON.Vector3.FromArray(key.values);
  18946. break;
  18947. }
  18948. keys.push({
  18949. frame: key.frame,
  18950. value: data
  18951. });
  18952. }
  18953. animation.setKeys(keys);
  18954. return animation;
  18955. };
  18956. var parseLight = function (parsedLight, scene) {
  18957. var light;
  18958. switch (parsedLight.type) {
  18959. case 0:
  18960. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  18961. break;
  18962. case 1:
  18963. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18964. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  18965. break;
  18966. case 2:
  18967. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  18968. break;
  18969. case 3:
  18970. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18971. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  18972. break;
  18973. }
  18974. light.id = parsedLight.id;
  18975. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  18976. if (parsedLight.intensity !== undefined) {
  18977. light.intensity = parsedLight.intensity;
  18978. }
  18979. if (parsedLight.range) {
  18980. light.range = parsedLight.range;
  18981. }
  18982. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  18983. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  18984. if (parsedLight.excludedMeshesIds) {
  18985. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18986. }
  18987. // Parent
  18988. if (parsedLight.parentId) {
  18989. light._waitingParentId = parsedLight.parentId;
  18990. }
  18991. if (parsedLight.includedOnlyMeshesIds) {
  18992. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18993. }
  18994. // Animations
  18995. if (parsedLight.animations) {
  18996. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18997. var parsedAnimation = parsedLight.animations[animationIndex];
  18998. light.animations.push(parseAnimation(parsedAnimation));
  18999. }
  19000. }
  19001. if (parsedLight.autoAnimate) {
  19002. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19003. }
  19004. };
  19005. var parseCamera = function (parsedCamera, scene) {
  19006. var camera;
  19007. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19008. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19009. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19010. var alpha = parsedCamera.alpha;
  19011. var beta = parsedCamera.beta;
  19012. var radius = parsedCamera.radius;
  19013. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19014. var eye_space = parsedCamera.eye_space;
  19015. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  19016. }
  19017. else {
  19018. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19019. }
  19020. }
  19021. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19022. eye_space = parsedCamera.eye_space;
  19023. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  19024. }
  19025. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19026. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19027. }
  19028. else if (parsedCamera.type === "FollowCamera") {
  19029. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19030. camera.heightOffset = parsedCamera.heightOffset;
  19031. camera.radius = parsedCamera.radius;
  19032. camera.rotationOffset = parsedCamera.rotationOffset;
  19033. if (lockedTargetMesh)
  19034. camera.target = lockedTargetMesh;
  19035. }
  19036. else if (parsedCamera.type === "GamepadCamera") {
  19037. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19038. }
  19039. else if (parsedCamera.type === "TouchCamera") {
  19040. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19041. }
  19042. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19043. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19044. }
  19045. else if (parsedCamera.type === "WebVRFreeCamera") {
  19046. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  19047. }
  19048. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  19049. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  19050. }
  19051. else {
  19052. // Free Camera is the default value
  19053. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19054. }
  19055. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19056. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19057. camera.lockedTarget = lockedTargetMesh;
  19058. }
  19059. camera.id = parsedCamera.id;
  19060. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19061. // Parent
  19062. if (parsedCamera.parentId) {
  19063. camera._waitingParentId = parsedCamera.parentId;
  19064. }
  19065. // Target
  19066. if (parsedCamera.target) {
  19067. if (camera.setTarget) {
  19068. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19069. }
  19070. else {
  19071. //For ArcRotate
  19072. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19073. }
  19074. }
  19075. else {
  19076. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19077. }
  19078. camera.fov = parsedCamera.fov;
  19079. camera.minZ = parsedCamera.minZ;
  19080. camera.maxZ = parsedCamera.maxZ;
  19081. camera.speed = parsedCamera.speed;
  19082. camera.inertia = parsedCamera.inertia;
  19083. camera.checkCollisions = parsedCamera.checkCollisions;
  19084. camera.applyGravity = parsedCamera.applyGravity;
  19085. if (parsedCamera.ellipsoid) {
  19086. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19087. }
  19088. // Animations
  19089. if (parsedCamera.animations) {
  19090. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19091. var parsedAnimation = parsedCamera.animations[animationIndex];
  19092. camera.animations.push(parseAnimation(parsedAnimation));
  19093. }
  19094. }
  19095. if (parsedCamera.autoAnimate) {
  19096. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19097. }
  19098. // Layer Mask
  19099. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19100. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19101. }
  19102. else {
  19103. camera.layerMask = 0xFFFFFFFF;
  19104. }
  19105. return camera;
  19106. };
  19107. var parseGeometry = function (parsedGeometry, scene) {
  19108. var id = parsedGeometry.id;
  19109. return scene.getGeometryByID(id);
  19110. };
  19111. var parseBox = function (parsedBox, scene) {
  19112. if (parseGeometry(parsedBox, scene)) {
  19113. return null; // null since geometry could be something else than a box...
  19114. }
  19115. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19116. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19117. scene.pushGeometry(box, true);
  19118. return box;
  19119. };
  19120. var parseSphere = function (parsedSphere, scene) {
  19121. if (parseGeometry(parsedSphere, scene)) {
  19122. return null; // null since geometry could be something else than a sphere...
  19123. }
  19124. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19125. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19126. scene.pushGeometry(sphere, true);
  19127. return sphere;
  19128. };
  19129. var parseCylinder = function (parsedCylinder, scene) {
  19130. if (parseGeometry(parsedCylinder, scene)) {
  19131. return null; // null since geometry could be something else than a cylinder...
  19132. }
  19133. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19134. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19135. scene.pushGeometry(cylinder, true);
  19136. return cylinder;
  19137. };
  19138. var parseTorus = function (parsedTorus, scene) {
  19139. if (parseGeometry(parsedTorus, scene)) {
  19140. return null; // null since geometry could be something else than a torus...
  19141. }
  19142. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19143. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19144. scene.pushGeometry(torus, true);
  19145. return torus;
  19146. };
  19147. var parseGround = function (parsedGround, scene) {
  19148. if (parseGeometry(parsedGround, scene)) {
  19149. return null; // null since geometry could be something else than a ground...
  19150. }
  19151. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19152. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19153. scene.pushGeometry(ground, true);
  19154. return ground;
  19155. };
  19156. var parsePlane = function (parsedPlane, scene) {
  19157. if (parseGeometry(parsedPlane, scene)) {
  19158. return null; // null since geometry could be something else than a plane...
  19159. }
  19160. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19161. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19162. scene.pushGeometry(plane, true);
  19163. return plane;
  19164. };
  19165. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19166. if (parseGeometry(parsedTorusKnot, scene)) {
  19167. return null; // null since geometry could be something else than a torusKnot...
  19168. }
  19169. 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);
  19170. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19171. scene.pushGeometry(torusKnot, true);
  19172. return torusKnot;
  19173. };
  19174. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19175. if (parseGeometry(parsedVertexData, scene)) {
  19176. return null; // null since geometry could be a primitive
  19177. }
  19178. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19179. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19180. if (parsedVertexData.delayLoadingFile) {
  19181. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19182. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19183. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19184. geometry._delayInfo = [];
  19185. if (parsedVertexData.hasUVs) {
  19186. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19187. }
  19188. if (parsedVertexData.hasUVs2) {
  19189. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19190. }
  19191. if (parsedVertexData.hasColors) {
  19192. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19193. }
  19194. if (parsedVertexData.hasMatricesIndices) {
  19195. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19196. }
  19197. if (parsedVertexData.hasMatricesWeights) {
  19198. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19199. }
  19200. geometry._delayLoadingFunction = importVertexData;
  19201. }
  19202. else {
  19203. importVertexData(parsedVertexData, geometry);
  19204. }
  19205. scene.pushGeometry(geometry, true);
  19206. return geometry;
  19207. };
  19208. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19209. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19210. mesh.id = parsedMesh.id;
  19211. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19212. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19213. if (parsedMesh.rotationQuaternion) {
  19214. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19215. }
  19216. else if (parsedMesh.rotation) {
  19217. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19218. }
  19219. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19220. if (parsedMesh.localMatrix) {
  19221. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19222. }
  19223. else if (parsedMesh.pivotMatrix) {
  19224. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19225. }
  19226. mesh.setEnabled(parsedMesh.isEnabled);
  19227. mesh.isVisible = parsedMesh.isVisible;
  19228. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19229. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19230. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19231. if (parsedMesh.applyFog !== undefined) {
  19232. mesh.applyFog = parsedMesh.applyFog;
  19233. }
  19234. if (parsedMesh.pickable !== undefined) {
  19235. mesh.isPickable = parsedMesh.pickable;
  19236. }
  19237. if (parsedMesh.alphaIndex !== undefined) {
  19238. mesh.alphaIndex = parsedMesh.alphaIndex;
  19239. }
  19240. mesh.receiveShadows = parsedMesh.receiveShadows;
  19241. mesh.billboardMode = parsedMesh.billboardMode;
  19242. if (parsedMesh.visibility !== undefined) {
  19243. mesh.visibility = parsedMesh.visibility;
  19244. }
  19245. mesh.checkCollisions = parsedMesh.checkCollisions;
  19246. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19247. // Parent
  19248. if (parsedMesh.parentId) {
  19249. mesh._waitingParentId = parsedMesh.parentId;
  19250. }
  19251. // Actions
  19252. if (parsedMesh.actions !== undefined) {
  19253. mesh._waitingActions = parsedMesh.actions;
  19254. }
  19255. // Geometry
  19256. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19257. if (parsedMesh.delayLoadingFile) {
  19258. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19259. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19260. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19261. if (parsedMesh._binaryInfo) {
  19262. mesh._binaryInfo = parsedMesh._binaryInfo;
  19263. }
  19264. mesh._delayInfo = [];
  19265. if (parsedMesh.hasUVs) {
  19266. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19267. }
  19268. if (parsedMesh.hasUVs2) {
  19269. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19270. }
  19271. if (parsedMesh.hasColors) {
  19272. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19273. }
  19274. if (parsedMesh.hasMatricesIndices) {
  19275. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19276. }
  19277. if (parsedMesh.hasMatricesWeights) {
  19278. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19279. }
  19280. mesh._delayLoadingFunction = importGeometry;
  19281. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19282. mesh._checkDelayState();
  19283. }
  19284. }
  19285. else {
  19286. importGeometry(parsedMesh, mesh);
  19287. }
  19288. // Material
  19289. if (parsedMesh.materialId) {
  19290. mesh.setMaterialByID(parsedMesh.materialId);
  19291. }
  19292. else {
  19293. mesh.material = null;
  19294. }
  19295. // Skeleton
  19296. if (parsedMesh.skeletonId > -1) {
  19297. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19298. }
  19299. // Physics
  19300. if (parsedMesh.physicsImpostor) {
  19301. if (!scene.isPhysicsEnabled()) {
  19302. scene.enablePhysics();
  19303. }
  19304. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  19305. }
  19306. // Animations
  19307. if (parsedMesh.animations) {
  19308. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19309. var parsedAnimation = parsedMesh.animations[animationIndex];
  19310. mesh.animations.push(parseAnimation(parsedAnimation));
  19311. }
  19312. }
  19313. if (parsedMesh.autoAnimate) {
  19314. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  19315. }
  19316. // Layer Mask
  19317. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19318. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19319. }
  19320. else {
  19321. mesh.layerMask = 0xFFFFFFFF;
  19322. }
  19323. // Instances
  19324. if (parsedMesh.instances) {
  19325. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19326. var parsedInstance = parsedMesh.instances[index];
  19327. var instance = mesh.createInstance(parsedInstance.name);
  19328. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19329. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19330. if (parsedInstance.rotationQuaternion) {
  19331. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19332. }
  19333. else if (parsedInstance.rotation) {
  19334. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19335. }
  19336. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19337. instance.checkCollisions = mesh.checkCollisions;
  19338. if (parsedMesh.animations) {
  19339. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19340. parsedAnimation = parsedMesh.animations[animationIndex];
  19341. instance.animations.push(parseAnimation(parsedAnimation));
  19342. }
  19343. }
  19344. }
  19345. }
  19346. return mesh;
  19347. };
  19348. var parseActions = function (parsedActions, object, scene) {
  19349. var actionManager = new BABYLON.ActionManager(scene);
  19350. if (object === null)
  19351. scene.actionManager = actionManager;
  19352. else
  19353. object.actionManager = actionManager;
  19354. // instanciate a new object
  19355. var instanciate = function (name, params) {
  19356. var newInstance = Object.create(BABYLON[name].prototype);
  19357. newInstance.constructor.apply(newInstance, params);
  19358. return newInstance;
  19359. };
  19360. var parseParameter = function (name, value, target, propertyPath) {
  19361. if (propertyPath === null) {
  19362. // String, boolean or float
  19363. var floatValue = parseFloat(value);
  19364. if (value === "true" || value === "false")
  19365. return value === "true";
  19366. else
  19367. return isNaN(floatValue) ? value : floatValue;
  19368. }
  19369. var effectiveTarget = propertyPath.split(".");
  19370. var values = value.split(",");
  19371. // Get effective Target
  19372. for (var i = 0; i < effectiveTarget.length; i++) {
  19373. target = target[effectiveTarget[i]];
  19374. }
  19375. // Return appropriate value with its type
  19376. if (typeof (target) === "boolean")
  19377. return values[0] === "true";
  19378. if (typeof (target) === "string")
  19379. return values[0];
  19380. // Parameters with multiple values such as Vector3 etc.
  19381. var split = new Array();
  19382. for (var i = 0; i < values.length; i++)
  19383. split.push(parseFloat(values[i]));
  19384. if (target instanceof BABYLON.Vector3)
  19385. return BABYLON.Vector3.FromArray(split);
  19386. if (target instanceof BABYLON.Vector4)
  19387. return BABYLON.Vector4.FromArray(split);
  19388. if (target instanceof BABYLON.Color3)
  19389. return BABYLON.Color3.FromArray(split);
  19390. if (target instanceof BABYLON.Color4)
  19391. return BABYLON.Color4.FromArray(split);
  19392. return parseFloat(values[0]);
  19393. };
  19394. // traverse graph per trigger
  19395. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  19396. if (combineArray === void 0) { combineArray = null; }
  19397. if (parsedAction.detached)
  19398. return;
  19399. var parameters = new Array();
  19400. var target = null;
  19401. var propertyPath = null;
  19402. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  19403. // Parameters
  19404. if (parsedAction.type === 2)
  19405. parameters.push(actionManager);
  19406. else
  19407. parameters.push(trigger);
  19408. if (combine) {
  19409. var actions = new Array();
  19410. for (var j = 0; j < parsedAction.combine.length; j++) {
  19411. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  19412. }
  19413. parameters.push(actions);
  19414. }
  19415. else {
  19416. for (var i = 0; i < parsedAction.properties.length; i++) {
  19417. var value = parsedAction.properties[i].value;
  19418. var name = parsedAction.properties[i].name;
  19419. var targetType = parsedAction.properties[i].targetType;
  19420. if (name === "target")
  19421. if (targetType !== null && targetType === "SceneProperties")
  19422. value = target = scene;
  19423. else
  19424. value = target = scene.getNodeByName(value);
  19425. else if (name === "parent")
  19426. value = scene.getNodeByName(value);
  19427. else if (name === "sound")
  19428. value = scene.getSoundByName(value);
  19429. else if (name !== "propertyPath") {
  19430. if (parsedAction.type === 2 && name === "operator")
  19431. value = BABYLON.ValueCondition[value];
  19432. else
  19433. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  19434. }
  19435. else {
  19436. propertyPath = value;
  19437. }
  19438. parameters.push(value);
  19439. }
  19440. }
  19441. if (combineArray === null) {
  19442. parameters.push(condition);
  19443. }
  19444. else {
  19445. parameters.push(null);
  19446. }
  19447. // If interpolate value action
  19448. if (parsedAction.name === "InterpolateValueAction") {
  19449. var param = parameters[parameters.length - 2];
  19450. parameters[parameters.length - 1] = param;
  19451. parameters[parameters.length - 2] = condition;
  19452. }
  19453. // Action or condition(s) and not CombineAction
  19454. var newAction = instanciate(parsedAction.name, parameters);
  19455. if (combineArray === null) {
  19456. if (newAction instanceof BABYLON.Condition) {
  19457. condition = newAction;
  19458. newAction = action;
  19459. }
  19460. else {
  19461. condition = null;
  19462. if (action)
  19463. action.then(newAction);
  19464. else
  19465. actionManager.registerAction(newAction);
  19466. }
  19467. }
  19468. else {
  19469. combineArray.push(newAction);
  19470. }
  19471. for (var i = 0; i < parsedAction.children.length; i++)
  19472. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  19473. };
  19474. // triggers
  19475. for (var i = 0; i < parsedActions.children.length; i++) {
  19476. var triggerParams;
  19477. var trigger = parsedActions.children[i];
  19478. if (trigger.properties.length > 0) {
  19479. var param = trigger.properties[0].value;
  19480. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  19481. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  19482. }
  19483. else
  19484. triggerParams = BABYLON.ActionManager[trigger.name];
  19485. for (var j = 0; j < trigger.children.length; j++) {
  19486. if (!trigger.detached)
  19487. traverse(trigger.children[j], triggerParams, null, null);
  19488. }
  19489. }
  19490. };
  19491. var parseSound = function (parsedSound, scene, rootUrl) {
  19492. var soundName = parsedSound.name;
  19493. var soundUrl = rootUrl + soundName;
  19494. var options = {
  19495. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  19496. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  19497. rolloffFactor: parsedSound.rolloffFactor,
  19498. refDistance: parsedSound.refDistance,
  19499. distanceModel: parsedSound.distanceModel,
  19500. playbackRate: parsedSound.playbackRate
  19501. };
  19502. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  19503. scene._addPendingData(newSound);
  19504. if (parsedSound.position) {
  19505. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  19506. newSound.setPosition(soundPosition);
  19507. }
  19508. if (parsedSound.isDirectional) {
  19509. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  19510. if (parsedSound.localDirectionToMesh) {
  19511. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  19512. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  19513. }
  19514. }
  19515. if (parsedSound.connectedMeshId) {
  19516. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  19517. if (connectedMesh) {
  19518. newSound.attachToMesh(connectedMesh);
  19519. }
  19520. }
  19521. };
  19522. var isDescendantOf = function (mesh, names, hierarchyIds) {
  19523. names = (names instanceof Array) ? names : [names];
  19524. for (var i in names) {
  19525. if (mesh.name === names[i]) {
  19526. hierarchyIds.push(mesh.id);
  19527. return true;
  19528. }
  19529. }
  19530. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  19531. hierarchyIds.push(mesh.id);
  19532. return true;
  19533. }
  19534. return false;
  19535. };
  19536. var importVertexData = function (parsedVertexData, geometry) {
  19537. var vertexData = new BABYLON.VertexData();
  19538. // positions
  19539. var positions = parsedVertexData.positions;
  19540. if (positions) {
  19541. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  19542. }
  19543. // normals
  19544. var normals = parsedVertexData.normals;
  19545. if (normals) {
  19546. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  19547. }
  19548. // uvs
  19549. var uvs = parsedVertexData.uvs;
  19550. if (uvs) {
  19551. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  19552. }
  19553. // uv2s
  19554. var uv2s = parsedVertexData.uv2s;
  19555. if (uv2s) {
  19556. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  19557. }
  19558. // colors
  19559. var colors = parsedVertexData.colors;
  19560. if (colors) {
  19561. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  19562. }
  19563. // matricesIndices
  19564. var matricesIndices = parsedVertexData.matricesIndices;
  19565. if (matricesIndices) {
  19566. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  19567. }
  19568. // matricesWeights
  19569. var matricesWeights = parsedVertexData.matricesWeights;
  19570. if (matricesWeights) {
  19571. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  19572. }
  19573. // indices
  19574. var indices = parsedVertexData.indices;
  19575. if (indices) {
  19576. vertexData.indices = indices;
  19577. }
  19578. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  19579. };
  19580. var importGeometry = function (parsedGeometry, mesh) {
  19581. var scene = mesh.getScene();
  19582. // Geometry
  19583. var geometryId = parsedGeometry.geometryId;
  19584. if (geometryId) {
  19585. var geometry = scene.getGeometryByID(geometryId);
  19586. if (geometry) {
  19587. geometry.applyToMesh(mesh);
  19588. }
  19589. }
  19590. else if (parsedGeometry instanceof ArrayBuffer) {
  19591. var binaryInfo = mesh._binaryInfo;
  19592. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  19593. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  19594. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  19595. }
  19596. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  19597. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  19598. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  19599. }
  19600. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  19601. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  19602. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  19603. }
  19604. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  19605. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  19606. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  19607. }
  19608. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  19609. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  19610. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  19611. }
  19612. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  19613. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  19614. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  19615. }
  19616. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  19617. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  19618. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  19619. }
  19620. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  19621. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  19622. mesh.setIndices(indicesData);
  19623. }
  19624. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  19625. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  19626. mesh.subMeshes = [];
  19627. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  19628. var materialIndex = subMeshesData[(i * 5) + 0];
  19629. var verticesStart = subMeshesData[(i * 5) + 1];
  19630. var verticesCount = subMeshesData[(i * 5) + 2];
  19631. var indexStart = subMeshesData[(i * 5) + 3];
  19632. var indexCount = subMeshesData[(i * 5) + 4];
  19633. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  19634. }
  19635. }
  19636. }
  19637. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  19638. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  19639. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  19640. if (parsedGeometry.uvs) {
  19641. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  19642. }
  19643. if (parsedGeometry.uvs2) {
  19644. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  19645. }
  19646. if (parsedGeometry.colors) {
  19647. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  19648. }
  19649. if (parsedGeometry.matricesIndices) {
  19650. if (!parsedGeometry.matricesIndices._isExpanded) {
  19651. var floatIndices = [];
  19652. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  19653. var matricesIndex = parsedGeometry.matricesIndices[i];
  19654. floatIndices.push(matricesIndex & 0x000000FF);
  19655. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  19656. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  19657. floatIndices.push(matricesIndex >> 24);
  19658. }
  19659. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  19660. }
  19661. else {
  19662. delete parsedGeometry.matricesIndices._isExpanded;
  19663. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  19664. }
  19665. }
  19666. if (parsedGeometry.matricesWeights) {
  19667. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  19668. }
  19669. mesh.setIndices(parsedGeometry.indices);
  19670. // SubMeshes
  19671. if (parsedGeometry.subMeshes) {
  19672. mesh.subMeshes = [];
  19673. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  19674. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  19675. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  19676. }
  19677. }
  19678. }
  19679. // Flat shading
  19680. if (mesh._shouldGenerateFlatShading) {
  19681. mesh.convertToFlatShadedMesh();
  19682. delete mesh._shouldGenerateFlatShading;
  19683. }
  19684. // Update
  19685. mesh.computeWorldMatrix(true);
  19686. // Octree
  19687. if (scene._selectionOctree) {
  19688. scene._selectionOctree.addMesh(mesh);
  19689. }
  19690. };
  19691. BABYLON.SceneLoader.RegisterPlugin({
  19692. extensions: ".babylon",
  19693. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  19694. var parsedData = JSON.parse(data);
  19695. var loadedSkeletonsIds = [];
  19696. var loadedMaterialsIds = [];
  19697. var hierarchyIds = [];
  19698. for (var index = 0; index < parsedData.meshes.length; index++) {
  19699. var parsedMesh = parsedData.meshes[index];
  19700. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  19701. if (meshesNames instanceof Array) {
  19702. // Remove found mesh name from list.
  19703. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  19704. }
  19705. //Geometry?
  19706. if (parsedMesh.geometryId) {
  19707. //does the file contain geometries?
  19708. if (parsedData.geometries) {
  19709. //find the correct geometry and add it to the scene
  19710. var found = false;
  19711. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  19712. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  19713. return;
  19714. }
  19715. else {
  19716. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  19717. if (parsedGeometryData.id == parsedMesh.geometryId) {
  19718. switch (geometryType) {
  19719. case "boxes":
  19720. parseBox(parsedGeometryData, scene);
  19721. break;
  19722. case "spheres":
  19723. parseSphere(parsedGeometryData, scene);
  19724. break;
  19725. case "cylinders":
  19726. parseCylinder(parsedGeometryData, scene);
  19727. break;
  19728. case "toruses":
  19729. parseTorus(parsedGeometryData, scene);
  19730. break;
  19731. case "grounds":
  19732. parseGround(parsedGeometryData, scene);
  19733. break;
  19734. case "planes":
  19735. parsePlane(parsedGeometryData, scene);
  19736. break;
  19737. case "torusKnots":
  19738. parseTorusKnot(parsedGeometryData, scene);
  19739. break;
  19740. case "vertexData":
  19741. parseVertexData(parsedGeometryData, scene, rootUrl);
  19742. break;
  19743. }
  19744. found = true;
  19745. }
  19746. });
  19747. }
  19748. });
  19749. }
  19750. }
  19751. // Material ?
  19752. if (parsedMesh.materialId) {
  19753. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  19754. if (!materialFound) {
  19755. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  19756. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  19757. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  19758. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19759. var subMatId = parsedMultiMaterial.materials[matIndex];
  19760. loadedMaterialsIds.push(subMatId);
  19761. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  19762. }
  19763. loadedMaterialsIds.push(parsedMultiMaterial.id);
  19764. parseMultiMaterial(parsedMultiMaterial, scene);
  19765. materialFound = true;
  19766. break;
  19767. }
  19768. }
  19769. }
  19770. if (!materialFound) {
  19771. loadedMaterialsIds.push(parsedMesh.materialId);
  19772. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  19773. }
  19774. }
  19775. // Skeleton ?
  19776. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  19777. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  19778. if (!skeletonAlreadyLoaded) {
  19779. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  19780. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  19781. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  19782. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  19783. loadedSkeletonsIds.push(parsedSkeleton.id);
  19784. }
  19785. }
  19786. }
  19787. }
  19788. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  19789. meshes.push(mesh);
  19790. }
  19791. }
  19792. // Connecting parents
  19793. for (index = 0; index < scene.meshes.length; index++) {
  19794. var currentMesh = scene.meshes[index];
  19795. if (currentMesh._waitingParentId) {
  19796. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  19797. currentMesh._waitingParentId = undefined;
  19798. }
  19799. }
  19800. // Particles
  19801. if (parsedData.particleSystems) {
  19802. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19803. var parsedParticleSystem = parsedData.particleSystems[index];
  19804. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  19805. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  19806. }
  19807. }
  19808. }
  19809. return true;
  19810. },
  19811. load: function (scene, data, rootUrl) {
  19812. var parsedData = JSON.parse(data);
  19813. // Scene
  19814. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  19815. scene.autoClear = parsedData.autoClear;
  19816. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  19817. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  19818. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  19819. // Fog
  19820. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  19821. scene.fogMode = parsedData.fogMode;
  19822. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  19823. scene.fogStart = parsedData.fogStart;
  19824. scene.fogEnd = parsedData.fogEnd;
  19825. scene.fogDensity = parsedData.fogDensity;
  19826. }
  19827. // Lights
  19828. for (var index = 0; index < parsedData.lights.length; index++) {
  19829. var parsedLight = parsedData.lights[index];
  19830. parseLight(parsedLight, scene);
  19831. }
  19832. // Materials
  19833. if (parsedData.materials) {
  19834. for (index = 0; index < parsedData.materials.length; index++) {
  19835. var parsedMaterial = parsedData.materials[index];
  19836. parseMaterial(parsedMaterial, scene, rootUrl);
  19837. }
  19838. }
  19839. if (parsedData.multiMaterials) {
  19840. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  19841. var parsedMultiMaterial = parsedData.multiMaterials[index];
  19842. parseMultiMaterial(parsedMultiMaterial, scene);
  19843. }
  19844. }
  19845. // Skeletons
  19846. if (parsedData.skeletons) {
  19847. for (index = 0; index < parsedData.skeletons.length; index++) {
  19848. var parsedSkeleton = parsedData.skeletons[index];
  19849. parseSkeleton(parsedSkeleton, scene);
  19850. }
  19851. }
  19852. // Geometries
  19853. var geometries = parsedData.geometries;
  19854. if (geometries) {
  19855. // Boxes
  19856. var boxes = geometries.boxes;
  19857. if (boxes) {
  19858. for (index = 0; index < boxes.length; index++) {
  19859. var parsedBox = boxes[index];
  19860. parseBox(parsedBox, scene);
  19861. }
  19862. }
  19863. // Spheres
  19864. var spheres = geometries.spheres;
  19865. if (spheres) {
  19866. for (index = 0; index < spheres.length; index++) {
  19867. var parsedSphere = spheres[index];
  19868. parseSphere(parsedSphere, scene);
  19869. }
  19870. }
  19871. // Cylinders
  19872. var cylinders = geometries.cylinders;
  19873. if (cylinders) {
  19874. for (index = 0; index < cylinders.length; index++) {
  19875. var parsedCylinder = cylinders[index];
  19876. parseCylinder(parsedCylinder, scene);
  19877. }
  19878. }
  19879. // Toruses
  19880. var toruses = geometries.toruses;
  19881. if (toruses) {
  19882. for (index = 0; index < toruses.length; index++) {
  19883. var parsedTorus = toruses[index];
  19884. parseTorus(parsedTorus, scene);
  19885. }
  19886. }
  19887. // Grounds
  19888. var grounds = geometries.grounds;
  19889. if (grounds) {
  19890. for (index = 0; index < grounds.length; index++) {
  19891. var parsedGround = grounds[index];
  19892. parseGround(parsedGround, scene);
  19893. }
  19894. }
  19895. // Planes
  19896. var planes = geometries.planes;
  19897. if (planes) {
  19898. for (index = 0; index < planes.length; index++) {
  19899. var parsedPlane = planes[index];
  19900. parsePlane(parsedPlane, scene);
  19901. }
  19902. }
  19903. // TorusKnots
  19904. var torusKnots = geometries.torusKnots;
  19905. if (torusKnots) {
  19906. for (index = 0; index < torusKnots.length; index++) {
  19907. var parsedTorusKnot = torusKnots[index];
  19908. parseTorusKnot(parsedTorusKnot, scene);
  19909. }
  19910. }
  19911. // VertexData
  19912. var vertexData = geometries.vertexData;
  19913. if (vertexData) {
  19914. for (index = 0; index < vertexData.length; index++) {
  19915. var parsedVertexData = vertexData[index];
  19916. parseVertexData(parsedVertexData, scene, rootUrl);
  19917. }
  19918. }
  19919. }
  19920. // Meshes
  19921. for (index = 0; index < parsedData.meshes.length; index++) {
  19922. var parsedMesh = parsedData.meshes[index];
  19923. parseMesh(parsedMesh, scene, rootUrl);
  19924. }
  19925. // Cameras
  19926. for (index = 0; index < parsedData.cameras.length; index++) {
  19927. var parsedCamera = parsedData.cameras[index];
  19928. parseCamera(parsedCamera, scene);
  19929. }
  19930. if (parsedData.activeCameraID) {
  19931. scene.setActiveCameraByID(parsedData.activeCameraID);
  19932. }
  19933. // Browsing all the graph to connect the dots
  19934. for (index = 0; index < scene.cameras.length; index++) {
  19935. var camera = scene.cameras[index];
  19936. if (camera._waitingParentId) {
  19937. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  19938. camera._waitingParentId = undefined;
  19939. }
  19940. }
  19941. for (index = 0; index < scene.lights.length; index++) {
  19942. var light = scene.lights[index];
  19943. if (light._waitingParentId) {
  19944. light.parent = scene.getLastEntryByID(light._waitingParentId);
  19945. light._waitingParentId = undefined;
  19946. }
  19947. }
  19948. // Sounds
  19949. if (parsedData.sounds) {
  19950. for (index = 0; index < parsedData.sounds.length; index++) {
  19951. var parsedSound = parsedData.sounds[index];
  19952. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  19953. parseSound(parsedSound, scene, rootUrl);
  19954. }
  19955. else {
  19956. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  19957. }
  19958. }
  19959. }
  19960. // Connect parents & children and parse actions
  19961. for (index = 0; index < scene.meshes.length; index++) {
  19962. var mesh = scene.meshes[index];
  19963. if (mesh._waitingParentId) {
  19964. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  19965. mesh._waitingParentId = undefined;
  19966. }
  19967. if (mesh._waitingActions) {
  19968. parseActions(mesh._waitingActions, mesh, scene);
  19969. mesh._waitingActions = undefined;
  19970. }
  19971. }
  19972. // Particles Systems
  19973. if (parsedData.particleSystems) {
  19974. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19975. var parsedParticleSystem = parsedData.particleSystems[index];
  19976. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  19977. }
  19978. }
  19979. // Lens flares
  19980. if (parsedData.lensFlareSystems) {
  19981. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  19982. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  19983. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  19984. }
  19985. }
  19986. // Shadows
  19987. if (parsedData.shadowGenerators) {
  19988. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  19989. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  19990. parseShadowGenerator(parsedShadowGenerator, scene);
  19991. }
  19992. }
  19993. // Actions (scene)
  19994. if (parsedData.actions) {
  19995. parseActions(parsedData.actions, null, scene);
  19996. }
  19997. // Finish
  19998. return true;
  19999. }
  20000. });
  20001. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20002. })(BABYLON || (BABYLON = {}));
  20003. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  20004. var BABYLON;
  20005. (function (BABYLON) {
  20006. var SpriteManager = (function () {
  20007. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20008. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20009. this.name = name;
  20010. this.cellSize = cellSize;
  20011. this.sprites = new Array();
  20012. this.renderingGroupId = 0;
  20013. this.fogEnabled = true;
  20014. this._vertexDeclaration = [4, 4, 4, 4];
  20015. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20016. this._capacity = capacity;
  20017. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20018. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20019. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20020. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20021. this._scene = scene;
  20022. this._scene.spriteManagers.push(this);
  20023. // VBO
  20024. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20025. var indices = [];
  20026. var index = 0;
  20027. for (var count = 0; count < capacity; count++) {
  20028. indices.push(index);
  20029. indices.push(index + 1);
  20030. indices.push(index + 2);
  20031. indices.push(index);
  20032. indices.push(index + 2);
  20033. indices.push(index + 3);
  20034. index += 4;
  20035. }
  20036. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20037. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20038. // Effects
  20039. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20040. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20041. }
  20042. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20043. var arrayOffset = index * 16;
  20044. if (offsetX === 0)
  20045. offsetX = this._epsilon;
  20046. else if (offsetX === 1)
  20047. offsetX = 1 - this._epsilon;
  20048. if (offsetY === 0)
  20049. offsetY = this._epsilon;
  20050. else if (offsetY === 1)
  20051. offsetY = 1 - this._epsilon;
  20052. this._vertices[arrayOffset] = sprite.position.x;
  20053. this._vertices[arrayOffset + 1] = sprite.position.y;
  20054. this._vertices[arrayOffset + 2] = sprite.position.z;
  20055. this._vertices[arrayOffset + 3] = sprite.angle;
  20056. this._vertices[arrayOffset + 4] = sprite.width;
  20057. this._vertices[arrayOffset + 5] = sprite.height;
  20058. this._vertices[arrayOffset + 6] = offsetX;
  20059. this._vertices[arrayOffset + 7] = offsetY;
  20060. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20061. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20062. var offset = (sprite.cellIndex / rowSize) >> 0;
  20063. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20064. this._vertices[arrayOffset + 11] = offset;
  20065. // Color
  20066. this._vertices[arrayOffset + 12] = sprite.color.r;
  20067. this._vertices[arrayOffset + 13] = sprite.color.g;
  20068. this._vertices[arrayOffset + 14] = sprite.color.b;
  20069. this._vertices[arrayOffset + 15] = sprite.color.a;
  20070. };
  20071. SpriteManager.prototype.render = function () {
  20072. // Check
  20073. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20074. return;
  20075. var engine = this._scene.getEngine();
  20076. var baseSize = this._spriteTexture.getBaseSize();
  20077. // Sprites
  20078. var deltaTime = engine.getDeltaTime();
  20079. var max = Math.min(this._capacity, this.sprites.length);
  20080. var rowSize = baseSize.width / this.cellSize;
  20081. var offset = 0;
  20082. for (var index = 0; index < max; index++) {
  20083. var sprite = this.sprites[index];
  20084. if (!sprite) {
  20085. continue;
  20086. }
  20087. sprite._animate(deltaTime);
  20088. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  20089. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  20090. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  20091. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  20092. }
  20093. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20094. // Render
  20095. var effect = this._effectBase;
  20096. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20097. effect = this._effectFog;
  20098. }
  20099. engine.enableEffect(effect);
  20100. var viewMatrix = this._scene.getViewMatrix();
  20101. effect.setTexture("diffuseSampler", this._spriteTexture);
  20102. effect.setMatrix("view", viewMatrix);
  20103. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20104. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  20105. // Fog
  20106. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20107. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  20108. effect.setColor3("vFogColor", this._scene.fogColor);
  20109. }
  20110. // VBOs
  20111. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20112. // Draw order
  20113. engine.setDepthFunctionToLessOrEqual();
  20114. effect.setBool("alphaTest", true);
  20115. engine.setColorWrite(false);
  20116. engine.draw(true, 0, max * 6);
  20117. engine.setColorWrite(true);
  20118. effect.setBool("alphaTest", false);
  20119. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20120. engine.draw(true, 0, max * 6);
  20121. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20122. };
  20123. SpriteManager.prototype.dispose = function () {
  20124. if (this._vertexBuffer) {
  20125. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20126. this._vertexBuffer = null;
  20127. }
  20128. if (this._indexBuffer) {
  20129. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20130. this._indexBuffer = null;
  20131. }
  20132. if (this._spriteTexture) {
  20133. this._spriteTexture.dispose();
  20134. this._spriteTexture = null;
  20135. }
  20136. // Remove from scene
  20137. var index = this._scene.spriteManagers.indexOf(this);
  20138. this._scene.spriteManagers.splice(index, 1);
  20139. // Callback
  20140. if (this.onDispose) {
  20141. this.onDispose();
  20142. }
  20143. };
  20144. return SpriteManager;
  20145. })();
  20146. BABYLON.SpriteManager = SpriteManager;
  20147. })(BABYLON || (BABYLON = {}));
  20148. //# sourceMappingURL=babylon.spriteManager.js.map
  20149. var BABYLON;
  20150. (function (BABYLON) {
  20151. var Sprite = (function () {
  20152. function Sprite(name, manager) {
  20153. this.name = name;
  20154. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20155. this.width = 1.0;
  20156. this.height = 1.0;
  20157. this.angle = 0;
  20158. this.cellIndex = 0;
  20159. this.invertU = 0;
  20160. this.invertV = 0;
  20161. this.animations = new Array();
  20162. this._animationStarted = false;
  20163. this._loopAnimation = false;
  20164. this._fromIndex = 0;
  20165. this._toIndex = 0;
  20166. this._delay = 0;
  20167. this._direction = 1;
  20168. this._frameCount = 0;
  20169. this._time = 0;
  20170. this._manager = manager;
  20171. this._manager.sprites.push(this);
  20172. this.position = BABYLON.Vector3.Zero();
  20173. }
  20174. Object.defineProperty(Sprite.prototype, "size", {
  20175. get: function () {
  20176. return this.width;
  20177. },
  20178. set: function (value) {
  20179. this.width = value;
  20180. this.height = value;
  20181. },
  20182. enumerable: true,
  20183. configurable: true
  20184. });
  20185. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  20186. this._fromIndex = from;
  20187. this._toIndex = to;
  20188. this._loopAnimation = loop;
  20189. this._delay = delay;
  20190. this._animationStarted = true;
  20191. this._direction = from < to ? 1 : -1;
  20192. this.cellIndex = from;
  20193. this._time = 0;
  20194. };
  20195. Sprite.prototype.stopAnimation = function () {
  20196. this._animationStarted = false;
  20197. };
  20198. Sprite.prototype._animate = function (deltaTime) {
  20199. if (!this._animationStarted)
  20200. return;
  20201. this._time += deltaTime;
  20202. if (this._time > this._delay) {
  20203. this._time = this._time % this._delay;
  20204. this.cellIndex += this._direction;
  20205. if (this.cellIndex == this._toIndex) {
  20206. if (this._loopAnimation) {
  20207. this.cellIndex = this._fromIndex;
  20208. }
  20209. else {
  20210. this._animationStarted = false;
  20211. if (this.disposeWhenFinishedAnimating) {
  20212. this.dispose();
  20213. }
  20214. }
  20215. }
  20216. }
  20217. };
  20218. Sprite.prototype.dispose = function () {
  20219. for (var i = 0; i < this._manager.sprites.length; i++) {
  20220. if (this._manager.sprites[i] == this) {
  20221. this._manager.sprites.splice(i, 1);
  20222. }
  20223. }
  20224. };
  20225. return Sprite;
  20226. })();
  20227. BABYLON.Sprite = Sprite;
  20228. })(BABYLON || (BABYLON = {}));
  20229. //# sourceMappingURL=babylon.sprite.js.map
  20230. var BABYLON;
  20231. (function (BABYLON) {
  20232. var Layer = (function () {
  20233. function Layer(name, imgUrl, scene, isBackground, color) {
  20234. this.name = name;
  20235. this._vertexDeclaration = [2];
  20236. this._vertexStrideSize = 2 * 4;
  20237. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  20238. this.isBackground = isBackground === undefined ? true : isBackground;
  20239. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  20240. this._scene = scene;
  20241. this._scene.layers.push(this);
  20242. // VBO
  20243. var vertices = [];
  20244. vertices.push(1, 1);
  20245. vertices.push(-1, 1);
  20246. vertices.push(-1, -1);
  20247. vertices.push(1, -1);
  20248. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  20249. // Indices
  20250. var indices = [];
  20251. indices.push(0);
  20252. indices.push(1);
  20253. indices.push(2);
  20254. indices.push(0);
  20255. indices.push(2);
  20256. indices.push(3);
  20257. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20258. // Effects
  20259. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  20260. }
  20261. Layer.prototype.render = function () {
  20262. // Check
  20263. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  20264. return;
  20265. var engine = this._scene.getEngine();
  20266. // Render
  20267. engine.enableEffect(this._effect);
  20268. engine.setState(false);
  20269. // Texture
  20270. this._effect.setTexture("textureSampler", this.texture);
  20271. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  20272. // Color
  20273. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  20274. // VBOs
  20275. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  20276. // Draw order
  20277. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20278. engine.draw(true, 0, 6);
  20279. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20280. };
  20281. Layer.prototype.dispose = function () {
  20282. if (this._vertexBuffer) {
  20283. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20284. this._vertexBuffer = null;
  20285. }
  20286. if (this._indexBuffer) {
  20287. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20288. this._indexBuffer = null;
  20289. }
  20290. if (this.texture) {
  20291. this.texture.dispose();
  20292. this.texture = null;
  20293. }
  20294. // Remove from scene
  20295. var index = this._scene.layers.indexOf(this);
  20296. this._scene.layers.splice(index, 1);
  20297. // Callback
  20298. if (this.onDispose) {
  20299. this.onDispose();
  20300. }
  20301. };
  20302. return Layer;
  20303. })();
  20304. BABYLON.Layer = Layer;
  20305. })(BABYLON || (BABYLON = {}));
  20306. //# sourceMappingURL=babylon.layer.js.map
  20307. var BABYLON;
  20308. (function (BABYLON) {
  20309. var Particle = (function () {
  20310. function Particle() {
  20311. this.position = BABYLON.Vector3.Zero();
  20312. this.direction = BABYLON.Vector3.Zero();
  20313. this.color = new BABYLON.Color4(0, 0, 0, 0);
  20314. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  20315. this.lifeTime = 1.0;
  20316. this.age = 0;
  20317. this.size = 0;
  20318. this.angle = 0;
  20319. this.angularSpeed = 0;
  20320. }
  20321. Particle.prototype.copyTo = function (other) {
  20322. other.position.copyFrom(this.position);
  20323. other.direction.copyFrom(this.direction);
  20324. other.color.copyFrom(this.color);
  20325. other.colorStep.copyFrom(this.colorStep);
  20326. other.lifeTime = this.lifeTime;
  20327. other.age = this.age;
  20328. other.size = this.size;
  20329. other.angle = this.angle;
  20330. other.angularSpeed = this.angularSpeed;
  20331. };
  20332. return Particle;
  20333. })();
  20334. BABYLON.Particle = Particle;
  20335. })(BABYLON || (BABYLON = {}));
  20336. //# sourceMappingURL=babylon.particle.js.map
  20337. var BABYLON;
  20338. (function (BABYLON) {
  20339. var randomNumber = function (min, max) {
  20340. if (min === max) {
  20341. return (min);
  20342. }
  20343. var random = Math.random();
  20344. return ((random * (max - min)) + min);
  20345. };
  20346. var ParticleSystem = (function () {
  20347. function ParticleSystem(name, capacity, scene, customEffect) {
  20348. var _this = this;
  20349. this.name = name;
  20350. this.renderingGroupId = 0;
  20351. this.emitter = null;
  20352. this.emitRate = 10;
  20353. this.manualEmitCount = -1;
  20354. this.updateSpeed = 0.01;
  20355. this.targetStopDuration = 0;
  20356. this.disposeOnStop = false;
  20357. this.minEmitPower = 1;
  20358. this.maxEmitPower = 1;
  20359. this.minLifeTime = 1;
  20360. this.maxLifeTime = 1;
  20361. this.minSize = 1;
  20362. this.maxSize = 1;
  20363. this.minAngularSpeed = 0;
  20364. this.maxAngularSpeed = 0;
  20365. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  20366. this.forceDepthWrite = false;
  20367. this.gravity = BABYLON.Vector3.Zero();
  20368. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  20369. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  20370. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  20371. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  20372. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20373. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20374. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  20375. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20376. this.particles = new Array();
  20377. this._vertexDeclaration = [3, 4, 4];
  20378. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  20379. this._stockParticles = new Array();
  20380. this._newPartsExcess = 0;
  20381. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  20382. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  20383. this._scaledDirection = BABYLON.Vector3.Zero();
  20384. this._scaledGravity = BABYLON.Vector3.Zero();
  20385. this._currentRenderId = -1;
  20386. this._started = false;
  20387. this._stopped = false;
  20388. this._actualFrame = 0;
  20389. this.id = name;
  20390. this._capacity = capacity;
  20391. this._scene = scene;
  20392. this._customEffect = customEffect;
  20393. scene.particleSystems.push(this);
  20394. // VBO
  20395. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20396. var indices = [];
  20397. var index = 0;
  20398. for (var count = 0; count < capacity; count++) {
  20399. indices.push(index);
  20400. indices.push(index + 1);
  20401. indices.push(index + 2);
  20402. indices.push(index);
  20403. indices.push(index + 2);
  20404. indices.push(index + 3);
  20405. index += 4;
  20406. }
  20407. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20408. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20409. // Default behaviors
  20410. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  20411. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  20412. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  20413. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  20414. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  20415. };
  20416. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  20417. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  20418. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  20419. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  20420. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  20421. };
  20422. this.updateFunction = function (particles) {
  20423. for (var index = 0; index < particles.length; index++) {
  20424. var particle = particles[index];
  20425. particle.age += _this._scaledUpdateSpeed;
  20426. if (particle.age >= particle.lifeTime) {
  20427. _this.recycleParticle(particle);
  20428. index--;
  20429. continue;
  20430. }
  20431. else {
  20432. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  20433. particle.color.addInPlace(_this._scaledColorStep);
  20434. if (particle.color.a < 0)
  20435. particle.color.a = 0;
  20436. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  20437. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  20438. particle.position.addInPlace(_this._scaledDirection);
  20439. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  20440. particle.direction.addInPlace(_this._scaledGravity);
  20441. }
  20442. }
  20443. };
  20444. }
  20445. ParticleSystem.prototype.recycleParticle = function (particle) {
  20446. var lastParticle = this.particles.pop();
  20447. if (lastParticle !== particle) {
  20448. lastParticle.copyTo(particle);
  20449. this._stockParticles.push(lastParticle);
  20450. }
  20451. };
  20452. ParticleSystem.prototype.getCapacity = function () {
  20453. return this._capacity;
  20454. };
  20455. ParticleSystem.prototype.isAlive = function () {
  20456. return this._alive;
  20457. };
  20458. ParticleSystem.prototype.isStarted = function () {
  20459. return this._started;
  20460. };
  20461. ParticleSystem.prototype.start = function () {
  20462. this._started = true;
  20463. this._stopped = false;
  20464. this._actualFrame = 0;
  20465. };
  20466. ParticleSystem.prototype.stop = function () {
  20467. this._stopped = true;
  20468. };
  20469. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  20470. var offset = index * 11;
  20471. this._vertices[offset] = particle.position.x;
  20472. this._vertices[offset + 1] = particle.position.y;
  20473. this._vertices[offset + 2] = particle.position.z;
  20474. this._vertices[offset + 3] = particle.color.r;
  20475. this._vertices[offset + 4] = particle.color.g;
  20476. this._vertices[offset + 5] = particle.color.b;
  20477. this._vertices[offset + 6] = particle.color.a;
  20478. this._vertices[offset + 7] = particle.angle;
  20479. this._vertices[offset + 8] = particle.size;
  20480. this._vertices[offset + 9] = offsetX;
  20481. this._vertices[offset + 10] = offsetY;
  20482. };
  20483. ParticleSystem.prototype._update = function (newParticles) {
  20484. // Update current
  20485. this._alive = this.particles.length > 0;
  20486. this.updateFunction(this.particles);
  20487. // Add new ones
  20488. var worldMatrix;
  20489. if (this.emitter.position) {
  20490. worldMatrix = this.emitter.getWorldMatrix();
  20491. }
  20492. else {
  20493. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  20494. }
  20495. for (var index = 0; index < newParticles; index++) {
  20496. if (this.particles.length === this._capacity) {
  20497. break;
  20498. }
  20499. if (this._stockParticles.length !== 0) {
  20500. var particle = this._stockParticles.pop();
  20501. particle.age = 0;
  20502. }
  20503. else {
  20504. particle = new BABYLON.Particle();
  20505. }
  20506. this.particles.push(particle);
  20507. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  20508. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  20509. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  20510. particle.size = randomNumber(this.minSize, this.maxSize);
  20511. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  20512. this.startPositionFunction(worldMatrix, particle.position);
  20513. var step = randomNumber(0, 1.0);
  20514. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  20515. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  20516. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  20517. }
  20518. };
  20519. ParticleSystem.prototype._getEffect = function () {
  20520. if (this._customEffect) {
  20521. return this._customEffect;
  20522. }
  20523. ;
  20524. var defines = [];
  20525. if (this._scene.clipPlane) {
  20526. defines.push("#define CLIPPLANE");
  20527. }
  20528. // Effect
  20529. var join = defines.join("\n");
  20530. if (this._cachedDefines !== join) {
  20531. this._cachedDefines = join;
  20532. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  20533. }
  20534. return this._effect;
  20535. };
  20536. ParticleSystem.prototype.animate = function () {
  20537. if (!this._started)
  20538. return;
  20539. var effect = this._getEffect();
  20540. // Check
  20541. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  20542. return;
  20543. if (this._currentRenderId === this._scene.getRenderId()) {
  20544. return;
  20545. }
  20546. this._currentRenderId = this._scene.getRenderId();
  20547. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  20548. // determine the number of particles we need to create
  20549. var emitCout;
  20550. if (this.manualEmitCount > -1) {
  20551. emitCout = this.manualEmitCount;
  20552. this.manualEmitCount = 0;
  20553. }
  20554. else {
  20555. emitCout = this.emitRate;
  20556. }
  20557. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  20558. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  20559. if (this._newPartsExcess > 1.0) {
  20560. newParticles += this._newPartsExcess >> 0;
  20561. this._newPartsExcess -= this._newPartsExcess >> 0;
  20562. }
  20563. this._alive = false;
  20564. if (!this._stopped) {
  20565. this._actualFrame += this._scaledUpdateSpeed;
  20566. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  20567. this.stop();
  20568. }
  20569. else {
  20570. newParticles = 0;
  20571. }
  20572. this._update(newParticles);
  20573. // Stopped?
  20574. if (this._stopped) {
  20575. if (!this._alive) {
  20576. this._started = false;
  20577. if (this.disposeOnStop) {
  20578. this._scene._toBeDisposed.push(this);
  20579. }
  20580. }
  20581. }
  20582. // Update VBO
  20583. var offset = 0;
  20584. for (var index = 0; index < this.particles.length; index++) {
  20585. var particle = this.particles[index];
  20586. this._appendParticleVertex(offset++, particle, 0, 0);
  20587. this._appendParticleVertex(offset++, particle, 1, 0);
  20588. this._appendParticleVertex(offset++, particle, 1, 1);
  20589. this._appendParticleVertex(offset++, particle, 0, 1);
  20590. }
  20591. var engine = this._scene.getEngine();
  20592. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20593. };
  20594. ParticleSystem.prototype.render = function () {
  20595. var effect = this._getEffect();
  20596. // Check
  20597. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  20598. return 0;
  20599. var engine = this._scene.getEngine();
  20600. // Render
  20601. engine.enableEffect(effect);
  20602. engine.setState(false);
  20603. var viewMatrix = this._scene.getViewMatrix();
  20604. effect.setTexture("diffuseSampler", this.particleTexture);
  20605. effect.setMatrix("view", viewMatrix);
  20606. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20607. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  20608. if (this._scene.clipPlane) {
  20609. var clipPlane = this._scene.clipPlane;
  20610. var invView = viewMatrix.clone();
  20611. invView.invert();
  20612. effect.setMatrix("invView", invView);
  20613. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  20614. }
  20615. // VBOs
  20616. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20617. // Draw order
  20618. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  20619. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  20620. }
  20621. else {
  20622. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20623. }
  20624. if (this.forceDepthWrite) {
  20625. engine.setDepthWrite(true);
  20626. }
  20627. engine.draw(true, 0, this.particles.length * 6);
  20628. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20629. return this.particles.length;
  20630. };
  20631. ParticleSystem.prototype.dispose = function () {
  20632. if (this._vertexBuffer) {
  20633. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20634. this._vertexBuffer = null;
  20635. }
  20636. if (this._indexBuffer) {
  20637. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20638. this._indexBuffer = null;
  20639. }
  20640. if (this.particleTexture) {
  20641. this.particleTexture.dispose();
  20642. this.particleTexture = null;
  20643. }
  20644. // Remove from scene
  20645. var index = this._scene.particleSystems.indexOf(this);
  20646. this._scene.particleSystems.splice(index, 1);
  20647. // Callback
  20648. if (this.onDispose) {
  20649. this.onDispose();
  20650. }
  20651. };
  20652. // Clone
  20653. ParticleSystem.prototype.clone = function (name, newEmitter) {
  20654. var result = new ParticleSystem(name, this._capacity, this._scene);
  20655. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  20656. if (newEmitter === undefined) {
  20657. newEmitter = this.emitter;
  20658. }
  20659. result.emitter = newEmitter;
  20660. if (this.particleTexture) {
  20661. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  20662. }
  20663. result.start();
  20664. return result;
  20665. };
  20666. // Statics
  20667. ParticleSystem.BLENDMODE_ONEONE = 0;
  20668. ParticleSystem.BLENDMODE_STANDARD = 1;
  20669. return ParticleSystem;
  20670. })();
  20671. BABYLON.ParticleSystem = ParticleSystem;
  20672. })(BABYLON || (BABYLON = {}));
  20673. //# sourceMappingURL=babylon.particleSystem.js.map
  20674. var BABYLON;
  20675. (function (BABYLON) {
  20676. var Animation = (function () {
  20677. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  20678. this.name = name;
  20679. this.targetProperty = targetProperty;
  20680. this.framePerSecond = framePerSecond;
  20681. this.dataType = dataType;
  20682. this.loopMode = loopMode;
  20683. this._offsetsCache = {};
  20684. this._highLimitsCache = {};
  20685. this._stopped = false;
  20686. this.targetPropertyPath = targetProperty.split(".");
  20687. this.dataType = dataType;
  20688. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  20689. }
  20690. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  20691. var dataType = undefined;
  20692. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  20693. dataType = Animation.ANIMATIONTYPE_FLOAT;
  20694. }
  20695. else if (from instanceof BABYLON.Quaternion) {
  20696. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  20697. }
  20698. else if (from instanceof BABYLON.Vector3) {
  20699. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  20700. }
  20701. else if (from instanceof BABYLON.Vector2) {
  20702. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  20703. }
  20704. else if (from instanceof BABYLON.Color3) {
  20705. dataType = Animation.ANIMATIONTYPE_COLOR3;
  20706. }
  20707. if (dataType == undefined) {
  20708. return null;
  20709. }
  20710. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  20711. var keys = [];
  20712. keys.push({ frame: 0, value: from });
  20713. keys.push({ frame: totalFrame, value: to });
  20714. animation.setKeys(keys);
  20715. mesh.animations.push(animation);
  20716. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  20717. };
  20718. // Methods
  20719. Animation.prototype.isStopped = function () {
  20720. return this._stopped;
  20721. };
  20722. Animation.prototype.getKeys = function () {
  20723. return this._keys;
  20724. };
  20725. Animation.prototype.getEasingFunction = function () {
  20726. return this._easingFunction;
  20727. };
  20728. Animation.prototype.setEasingFunction = function (easingFunction) {
  20729. this._easingFunction = easingFunction;
  20730. };
  20731. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  20732. return startValue + (endValue - startValue) * gradient;
  20733. };
  20734. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  20735. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  20736. };
  20737. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  20738. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  20739. };
  20740. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  20741. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  20742. };
  20743. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  20744. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  20745. };
  20746. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  20747. var startScale = new BABYLON.Vector3(0, 0, 0);
  20748. var startRotation = new BABYLON.Quaternion();
  20749. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  20750. startValue.decompose(startScale, startRotation, startTranslation);
  20751. var endScale = new BABYLON.Vector3(0, 0, 0);
  20752. var endRotation = new BABYLON.Quaternion();
  20753. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  20754. endValue.decompose(endScale, endRotation, endTranslation);
  20755. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  20756. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  20757. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  20758. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  20759. return result;
  20760. };
  20761. Animation.prototype.clone = function () {
  20762. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  20763. clone.setKeys(this._keys);
  20764. return clone;
  20765. };
  20766. Animation.prototype.setKeys = function (values) {
  20767. this._keys = values.slice(0);
  20768. this._offsetsCache = {};
  20769. this._highLimitsCache = {};
  20770. };
  20771. Animation.prototype._getKeyValue = function (value) {
  20772. if (typeof value === "function") {
  20773. return value();
  20774. }
  20775. return value;
  20776. };
  20777. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  20778. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  20779. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  20780. }
  20781. this.currentFrame = currentFrame;
  20782. // Try to get a hash to find the right key
  20783. 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));
  20784. if (this._keys[startKey].frame >= currentFrame) {
  20785. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  20786. startKey--;
  20787. }
  20788. }
  20789. for (var key = startKey; key < this._keys.length; key++) {
  20790. if (this._keys[key + 1].frame >= currentFrame) {
  20791. var startValue = this._getKeyValue(this._keys[key].value);
  20792. var endValue = this._getKeyValue(this._keys[key + 1].value);
  20793. // gradient : percent of currentFrame between the frame inf and the frame sup
  20794. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  20795. // check for easingFunction and correction of gradient
  20796. if (this._easingFunction != null) {
  20797. gradient = this._easingFunction.ease(gradient);
  20798. }
  20799. switch (this.dataType) {
  20800. // Float
  20801. case Animation.ANIMATIONTYPE_FLOAT:
  20802. switch (loopMode) {
  20803. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20804. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20805. return this.floatInterpolateFunction(startValue, endValue, gradient);
  20806. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20807. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  20808. }
  20809. break;
  20810. // Quaternion
  20811. case Animation.ANIMATIONTYPE_QUATERNION:
  20812. var quaternion = null;
  20813. switch (loopMode) {
  20814. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20815. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20816. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  20817. break;
  20818. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20819. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20820. break;
  20821. }
  20822. return quaternion;
  20823. // Vector3
  20824. case Animation.ANIMATIONTYPE_VECTOR3:
  20825. switch (loopMode) {
  20826. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20827. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20828. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  20829. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20830. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20831. }
  20832. // Vector2
  20833. case Animation.ANIMATIONTYPE_VECTOR2:
  20834. switch (loopMode) {
  20835. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20836. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20837. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  20838. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20839. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20840. }
  20841. // Color3
  20842. case Animation.ANIMATIONTYPE_COLOR3:
  20843. switch (loopMode) {
  20844. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20845. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20846. return this.color3InterpolateFunction(startValue, endValue, gradient);
  20847. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20848. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20849. }
  20850. // Matrix
  20851. case Animation.ANIMATIONTYPE_MATRIX:
  20852. switch (loopMode) {
  20853. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20854. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20855. // return this.matrixInterpolateFunction(startValue, endValue, gradient);
  20856. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20857. return startValue;
  20858. }
  20859. default:
  20860. break;
  20861. }
  20862. break;
  20863. }
  20864. }
  20865. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  20866. };
  20867. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  20868. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  20869. this._stopped = true;
  20870. return false;
  20871. }
  20872. var returnValue = true;
  20873. // Adding a start key at frame 0 if missing
  20874. if (this._keys[0].frame !== 0) {
  20875. var newKey = { frame: 0, value: this._keys[0].value };
  20876. this._keys.splice(0, 0, newKey);
  20877. }
  20878. // Check limits
  20879. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  20880. from = this._keys[0].frame;
  20881. }
  20882. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  20883. to = this._keys[this._keys.length - 1].frame;
  20884. }
  20885. // Compute ratio
  20886. var range = to - from;
  20887. var offsetValue;
  20888. // ratio represents the frame delta between from and to
  20889. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  20890. var highLimitValue = 0;
  20891. if (ratio > range && !loop) {
  20892. returnValue = false;
  20893. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  20894. }
  20895. else {
  20896. // Get max value if required
  20897. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  20898. var keyOffset = to.toString() + from.toString();
  20899. if (!this._offsetsCache[keyOffset]) {
  20900. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  20901. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  20902. switch (this.dataType) {
  20903. // Float
  20904. case Animation.ANIMATIONTYPE_FLOAT:
  20905. this._offsetsCache[keyOffset] = toValue - fromValue;
  20906. break;
  20907. // Quaternion
  20908. case Animation.ANIMATIONTYPE_QUATERNION:
  20909. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  20910. break;
  20911. // Vector3
  20912. case Animation.ANIMATIONTYPE_VECTOR3:
  20913. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  20914. // Vector2
  20915. case Animation.ANIMATIONTYPE_VECTOR2:
  20916. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  20917. // Color3
  20918. case Animation.ANIMATIONTYPE_COLOR3:
  20919. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  20920. default:
  20921. break;
  20922. }
  20923. this._highLimitsCache[keyOffset] = toValue;
  20924. }
  20925. highLimitValue = this._highLimitsCache[keyOffset];
  20926. offsetValue = this._offsetsCache[keyOffset];
  20927. }
  20928. }
  20929. if (offsetValue === undefined) {
  20930. switch (this.dataType) {
  20931. // Float
  20932. case Animation.ANIMATIONTYPE_FLOAT:
  20933. offsetValue = 0;
  20934. break;
  20935. // Quaternion
  20936. case Animation.ANIMATIONTYPE_QUATERNION:
  20937. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  20938. break;
  20939. // Vector3
  20940. case Animation.ANIMATIONTYPE_VECTOR3:
  20941. offsetValue = BABYLON.Vector3.Zero();
  20942. break;
  20943. // Vector2
  20944. case Animation.ANIMATIONTYPE_VECTOR2:
  20945. offsetValue = BABYLON.Vector2.Zero();
  20946. break;
  20947. // Color3
  20948. case Animation.ANIMATIONTYPE_COLOR3:
  20949. offsetValue = BABYLON.Color3.Black();
  20950. }
  20951. }
  20952. // Compute value
  20953. var repeatCount = (ratio / range) >> 0;
  20954. var currentFrame = returnValue ? from + ratio % range : to;
  20955. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  20956. // Set value
  20957. if (this.targetPropertyPath.length > 1) {
  20958. var property = this._target[this.targetPropertyPath[0]];
  20959. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  20960. property = property[this.targetPropertyPath[index]];
  20961. }
  20962. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  20963. }
  20964. else {
  20965. this._target[this.targetPropertyPath[0]] = currentValue;
  20966. }
  20967. if (this._target.markAsDirty) {
  20968. this._target.markAsDirty(this.targetProperty);
  20969. }
  20970. if (!returnValue) {
  20971. this._stopped = true;
  20972. }
  20973. return returnValue;
  20974. };
  20975. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  20976. get: function () {
  20977. return Animation._ANIMATIONTYPE_FLOAT;
  20978. },
  20979. enumerable: true,
  20980. configurable: true
  20981. });
  20982. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  20983. get: function () {
  20984. return Animation._ANIMATIONTYPE_VECTOR3;
  20985. },
  20986. enumerable: true,
  20987. configurable: true
  20988. });
  20989. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  20990. get: function () {
  20991. return Animation._ANIMATIONTYPE_VECTOR2;
  20992. },
  20993. enumerable: true,
  20994. configurable: true
  20995. });
  20996. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  20997. get: function () {
  20998. return Animation._ANIMATIONTYPE_QUATERNION;
  20999. },
  21000. enumerable: true,
  21001. configurable: true
  21002. });
  21003. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21004. get: function () {
  21005. return Animation._ANIMATIONTYPE_MATRIX;
  21006. },
  21007. enumerable: true,
  21008. configurable: true
  21009. });
  21010. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21011. get: function () {
  21012. return Animation._ANIMATIONTYPE_COLOR3;
  21013. },
  21014. enumerable: true,
  21015. configurable: true
  21016. });
  21017. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  21018. get: function () {
  21019. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  21020. },
  21021. enumerable: true,
  21022. configurable: true
  21023. });
  21024. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  21025. get: function () {
  21026. return Animation._ANIMATIONLOOPMODE_CYCLE;
  21027. },
  21028. enumerable: true,
  21029. configurable: true
  21030. });
  21031. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  21032. get: function () {
  21033. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  21034. },
  21035. enumerable: true,
  21036. configurable: true
  21037. });
  21038. // Statics
  21039. Animation._ANIMATIONTYPE_FLOAT = 0;
  21040. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  21041. Animation._ANIMATIONTYPE_QUATERNION = 2;
  21042. Animation._ANIMATIONTYPE_MATRIX = 3;
  21043. Animation._ANIMATIONTYPE_COLOR3 = 4;
  21044. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  21045. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  21046. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  21047. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  21048. return Animation;
  21049. })();
  21050. BABYLON.Animation = Animation;
  21051. })(BABYLON || (BABYLON = {}));
  21052. //# sourceMappingURL=babylon.animation.js.map
  21053. var BABYLON;
  21054. (function (BABYLON) {
  21055. var Animatable = (function () {
  21056. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  21057. if (fromFrame === void 0) { fromFrame = 0; }
  21058. if (toFrame === void 0) { toFrame = 100; }
  21059. if (loopAnimation === void 0) { loopAnimation = false; }
  21060. if (speedRatio === void 0) { speedRatio = 1.0; }
  21061. this.target = target;
  21062. this.fromFrame = fromFrame;
  21063. this.toFrame = toFrame;
  21064. this.loopAnimation = loopAnimation;
  21065. this.speedRatio = speedRatio;
  21066. this.onAnimationEnd = onAnimationEnd;
  21067. this._animations = new Array();
  21068. this._paused = false;
  21069. this.animationStarted = false;
  21070. if (animations) {
  21071. this.appendAnimations(target, animations);
  21072. }
  21073. this._scene = scene;
  21074. scene._activeAnimatables.push(this);
  21075. }
  21076. // Methods
  21077. Animatable.prototype.appendAnimations = function (target, animations) {
  21078. for (var index = 0; index < animations.length; index++) {
  21079. var animation = animations[index];
  21080. animation._target = target;
  21081. this._animations.push(animation);
  21082. }
  21083. };
  21084. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  21085. var animations = this._animations;
  21086. for (var index = 0; index < animations.length; index++) {
  21087. if (animations[index].targetProperty === property) {
  21088. return animations[index];
  21089. }
  21090. }
  21091. return null;
  21092. };
  21093. Animatable.prototype.pause = function () {
  21094. if (this._paused) {
  21095. return;
  21096. }
  21097. this._paused = true;
  21098. };
  21099. Animatable.prototype.restart = function () {
  21100. this._paused = false;
  21101. };
  21102. Animatable.prototype.stop = function () {
  21103. var index = this._scene._activeAnimatables.indexOf(this);
  21104. if (index > -1) {
  21105. this._scene._activeAnimatables.splice(index, 1);
  21106. }
  21107. if (this.onAnimationEnd) {
  21108. this.onAnimationEnd();
  21109. }
  21110. };
  21111. Animatable.prototype._animate = function (delay) {
  21112. if (this._paused) {
  21113. if (!this._pausedDelay) {
  21114. this._pausedDelay = delay;
  21115. }
  21116. return true;
  21117. }
  21118. if (!this._localDelayOffset) {
  21119. this._localDelayOffset = delay;
  21120. }
  21121. else if (this._pausedDelay) {
  21122. this._localDelayOffset += delay - this._pausedDelay;
  21123. this._pausedDelay = null;
  21124. }
  21125. // Animating
  21126. var running = false;
  21127. var animations = this._animations;
  21128. for (var index = 0; index < animations.length; index++) {
  21129. var animation = animations[index];
  21130. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  21131. running = running || isRunning;
  21132. }
  21133. if (!running) {
  21134. // Remove from active animatables
  21135. index = this._scene._activeAnimatables.indexOf(this);
  21136. this._scene._activeAnimatables.splice(index, 1);
  21137. }
  21138. if (!running && this.onAnimationEnd) {
  21139. this.onAnimationEnd();
  21140. }
  21141. return running;
  21142. };
  21143. return Animatable;
  21144. })();
  21145. BABYLON.Animatable = Animatable;
  21146. })(BABYLON || (BABYLON = {}));
  21147. //# sourceMappingURL=babylon.animatable.js.map
  21148. var BABYLON;
  21149. (function (BABYLON) {
  21150. var EasingFunction = (function () {
  21151. function EasingFunction() {
  21152. // Properties
  21153. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  21154. }
  21155. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  21156. get: function () {
  21157. return EasingFunction._EASINGMODE_EASEIN;
  21158. },
  21159. enumerable: true,
  21160. configurable: true
  21161. });
  21162. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  21163. get: function () {
  21164. return EasingFunction._EASINGMODE_EASEOUT;
  21165. },
  21166. enumerable: true,
  21167. configurable: true
  21168. });
  21169. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  21170. get: function () {
  21171. return EasingFunction._EASINGMODE_EASEINOUT;
  21172. },
  21173. enumerable: true,
  21174. configurable: true
  21175. });
  21176. EasingFunction.prototype.setEasingMode = function (easingMode) {
  21177. var n = Math.min(Math.max(easingMode, 0), 2);
  21178. this._easingMode = n;
  21179. };
  21180. EasingFunction.prototype.getEasingMode = function () {
  21181. return this._easingMode;
  21182. };
  21183. EasingFunction.prototype.easeInCore = function (gradient) {
  21184. throw new Error('You must implement this method');
  21185. };
  21186. EasingFunction.prototype.ease = function (gradient) {
  21187. switch (this._easingMode) {
  21188. case EasingFunction.EASINGMODE_EASEIN:
  21189. return this.easeInCore(gradient);
  21190. case EasingFunction.EASINGMODE_EASEOUT:
  21191. return (1 - this.easeInCore(1 - gradient));
  21192. }
  21193. if (gradient >= 0.5) {
  21194. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  21195. }
  21196. return (this.easeInCore(gradient * 2) * 0.5);
  21197. };
  21198. //Statics
  21199. EasingFunction._EASINGMODE_EASEIN = 0;
  21200. EasingFunction._EASINGMODE_EASEOUT = 1;
  21201. EasingFunction._EASINGMODE_EASEINOUT = 2;
  21202. return EasingFunction;
  21203. })();
  21204. BABYLON.EasingFunction = EasingFunction;
  21205. var CircleEase = (function (_super) {
  21206. __extends(CircleEase, _super);
  21207. function CircleEase() {
  21208. _super.apply(this, arguments);
  21209. }
  21210. CircleEase.prototype.easeInCore = function (gradient) {
  21211. gradient = Math.max(0, Math.min(1, gradient));
  21212. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  21213. };
  21214. return CircleEase;
  21215. })(EasingFunction);
  21216. BABYLON.CircleEase = CircleEase;
  21217. var BackEase = (function (_super) {
  21218. __extends(BackEase, _super);
  21219. function BackEase(amplitude) {
  21220. if (amplitude === void 0) { amplitude = 1; }
  21221. _super.call(this);
  21222. this.amplitude = amplitude;
  21223. }
  21224. BackEase.prototype.easeInCore = function (gradient) {
  21225. var num = Math.max(0, this.amplitude);
  21226. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  21227. };
  21228. return BackEase;
  21229. })(EasingFunction);
  21230. BABYLON.BackEase = BackEase;
  21231. var BounceEase = (function (_super) {
  21232. __extends(BounceEase, _super);
  21233. function BounceEase(bounces, bounciness) {
  21234. if (bounces === void 0) { bounces = 3; }
  21235. if (bounciness === void 0) { bounciness = 2; }
  21236. _super.call(this);
  21237. this.bounces = bounces;
  21238. this.bounciness = bounciness;
  21239. }
  21240. BounceEase.prototype.easeInCore = function (gradient) {
  21241. var y = Math.max(0.0, this.bounces);
  21242. var bounciness = this.bounciness;
  21243. if (bounciness <= 1.0) {
  21244. bounciness = 1.001;
  21245. }
  21246. var num9 = Math.pow(bounciness, y);
  21247. var num5 = 1.0 - bounciness;
  21248. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  21249. var num15 = gradient * num4;
  21250. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  21251. var num3 = Math.floor(num65);
  21252. var num13 = num3 + 1.0;
  21253. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  21254. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  21255. var num7 = (num8 + num12) * 0.5;
  21256. var num6 = gradient - num7;
  21257. var num2 = num7 - num8;
  21258. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  21259. };
  21260. return BounceEase;
  21261. })(EasingFunction);
  21262. BABYLON.BounceEase = BounceEase;
  21263. var CubicEase = (function (_super) {
  21264. __extends(CubicEase, _super);
  21265. function CubicEase() {
  21266. _super.apply(this, arguments);
  21267. }
  21268. CubicEase.prototype.easeInCore = function (gradient) {
  21269. return (gradient * gradient * gradient);
  21270. };
  21271. return CubicEase;
  21272. })(EasingFunction);
  21273. BABYLON.CubicEase = CubicEase;
  21274. var ElasticEase = (function (_super) {
  21275. __extends(ElasticEase, _super);
  21276. function ElasticEase(oscillations, springiness) {
  21277. if (oscillations === void 0) { oscillations = 3; }
  21278. if (springiness === void 0) { springiness = 3; }
  21279. _super.call(this);
  21280. this.oscillations = oscillations;
  21281. this.springiness = springiness;
  21282. }
  21283. ElasticEase.prototype.easeInCore = function (gradient) {
  21284. var num2;
  21285. var num3 = Math.max(0.0, this.oscillations);
  21286. var num = Math.max(0.0, this.springiness);
  21287. if (num == 0) {
  21288. num2 = gradient;
  21289. }
  21290. else {
  21291. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  21292. }
  21293. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  21294. };
  21295. return ElasticEase;
  21296. })(EasingFunction);
  21297. BABYLON.ElasticEase = ElasticEase;
  21298. var ExponentialEase = (function (_super) {
  21299. __extends(ExponentialEase, _super);
  21300. function ExponentialEase(exponent) {
  21301. if (exponent === void 0) { exponent = 2; }
  21302. _super.call(this);
  21303. this.exponent = exponent;
  21304. }
  21305. ExponentialEase.prototype.easeInCore = function (gradient) {
  21306. if (this.exponent <= 0) {
  21307. return gradient;
  21308. }
  21309. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  21310. };
  21311. return ExponentialEase;
  21312. })(EasingFunction);
  21313. BABYLON.ExponentialEase = ExponentialEase;
  21314. var PowerEase = (function (_super) {
  21315. __extends(PowerEase, _super);
  21316. function PowerEase(power) {
  21317. if (power === void 0) { power = 2; }
  21318. _super.call(this);
  21319. this.power = power;
  21320. }
  21321. PowerEase.prototype.easeInCore = function (gradient) {
  21322. var y = Math.max(0.0, this.power);
  21323. return Math.pow(gradient, y);
  21324. };
  21325. return PowerEase;
  21326. })(EasingFunction);
  21327. BABYLON.PowerEase = PowerEase;
  21328. var QuadraticEase = (function (_super) {
  21329. __extends(QuadraticEase, _super);
  21330. function QuadraticEase() {
  21331. _super.apply(this, arguments);
  21332. }
  21333. QuadraticEase.prototype.easeInCore = function (gradient) {
  21334. return (gradient * gradient);
  21335. };
  21336. return QuadraticEase;
  21337. })(EasingFunction);
  21338. BABYLON.QuadraticEase = QuadraticEase;
  21339. var QuarticEase = (function (_super) {
  21340. __extends(QuarticEase, _super);
  21341. function QuarticEase() {
  21342. _super.apply(this, arguments);
  21343. }
  21344. QuarticEase.prototype.easeInCore = function (gradient) {
  21345. return (gradient * gradient * gradient * gradient);
  21346. };
  21347. return QuarticEase;
  21348. })(EasingFunction);
  21349. BABYLON.QuarticEase = QuarticEase;
  21350. var QuinticEase = (function (_super) {
  21351. __extends(QuinticEase, _super);
  21352. function QuinticEase() {
  21353. _super.apply(this, arguments);
  21354. }
  21355. QuinticEase.prototype.easeInCore = function (gradient) {
  21356. return (gradient * gradient * gradient * gradient * gradient);
  21357. };
  21358. return QuinticEase;
  21359. })(EasingFunction);
  21360. BABYLON.QuinticEase = QuinticEase;
  21361. var SineEase = (function (_super) {
  21362. __extends(SineEase, _super);
  21363. function SineEase() {
  21364. _super.apply(this, arguments);
  21365. }
  21366. SineEase.prototype.easeInCore = function (gradient) {
  21367. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  21368. };
  21369. return SineEase;
  21370. })(EasingFunction);
  21371. BABYLON.SineEase = SineEase;
  21372. var BezierCurveEase = (function (_super) {
  21373. __extends(BezierCurveEase, _super);
  21374. function BezierCurveEase(x1, y1, x2, y2) {
  21375. if (x1 === void 0) { x1 = 0; }
  21376. if (y1 === void 0) { y1 = 0; }
  21377. if (x2 === void 0) { x2 = 1; }
  21378. if (y2 === void 0) { y2 = 1; }
  21379. _super.call(this);
  21380. this.x1 = x1;
  21381. this.y1 = y1;
  21382. this.x2 = x2;
  21383. this.y2 = y2;
  21384. }
  21385. BezierCurveEase.prototype.easeInCore = function (gradient) {
  21386. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  21387. };
  21388. return BezierCurveEase;
  21389. })(EasingFunction);
  21390. BABYLON.BezierCurveEase = BezierCurveEase;
  21391. })(BABYLON || (BABYLON = {}));
  21392. //# sourceMappingURL=babylon.easing.js.map
  21393. var BABYLON;
  21394. (function (BABYLON) {
  21395. var Octree = (function () {
  21396. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  21397. if (maxDepth === void 0) { maxDepth = 2; }
  21398. this.maxDepth = maxDepth;
  21399. this.dynamicContent = new Array();
  21400. this._maxBlockCapacity = maxBlockCapacity || 64;
  21401. this._selectionContent = new BABYLON.SmartArray(1024);
  21402. this._creationFunc = creationFunc;
  21403. }
  21404. // Methods
  21405. Octree.prototype.update = function (worldMin, worldMax, entries) {
  21406. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  21407. };
  21408. Octree.prototype.addMesh = function (entry) {
  21409. for (var index = 0; index < this.blocks.length; index++) {
  21410. var block = this.blocks[index];
  21411. block.addEntry(entry);
  21412. }
  21413. };
  21414. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  21415. this._selectionContent.reset();
  21416. for (var index = 0; index < this.blocks.length; index++) {
  21417. var block = this.blocks[index];
  21418. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  21419. }
  21420. if (allowDuplicate) {
  21421. this._selectionContent.concat(this.dynamicContent);
  21422. }
  21423. else {
  21424. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  21425. }
  21426. return this._selectionContent;
  21427. };
  21428. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  21429. this._selectionContent.reset();
  21430. for (var index = 0; index < this.blocks.length; index++) {
  21431. var block = this.blocks[index];
  21432. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  21433. }
  21434. if (allowDuplicate) {
  21435. this._selectionContent.concat(this.dynamicContent);
  21436. }
  21437. else {
  21438. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  21439. }
  21440. return this._selectionContent;
  21441. };
  21442. Octree.prototype.intersectsRay = function (ray) {
  21443. this._selectionContent.reset();
  21444. for (var index = 0; index < this.blocks.length; index++) {
  21445. var block = this.blocks[index];
  21446. block.intersectsRay(ray, this._selectionContent);
  21447. }
  21448. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  21449. return this._selectionContent;
  21450. };
  21451. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  21452. target.blocks = new Array();
  21453. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  21454. // Segmenting space
  21455. for (var x = 0; x < 2; x++) {
  21456. for (var y = 0; y < 2; y++) {
  21457. for (var z = 0; z < 2; z++) {
  21458. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  21459. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  21460. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  21461. block.addEntries(entries);
  21462. target.blocks.push(block);
  21463. }
  21464. }
  21465. }
  21466. };
  21467. Octree.CreationFuncForMeshes = function (entry, block) {
  21468. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  21469. block.entries.push(entry);
  21470. }
  21471. };
  21472. Octree.CreationFuncForSubMeshes = function (entry, block) {
  21473. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  21474. block.entries.push(entry);
  21475. }
  21476. };
  21477. return Octree;
  21478. })();
  21479. BABYLON.Octree = Octree;
  21480. })(BABYLON || (BABYLON = {}));
  21481. //# sourceMappingURL=babylon.octree.js.map
  21482. var BABYLON;
  21483. (function (BABYLON) {
  21484. var OctreeBlock = (function () {
  21485. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  21486. this.entries = new Array();
  21487. this._boundingVectors = new Array();
  21488. this._capacity = capacity;
  21489. this._depth = depth;
  21490. this._maxDepth = maxDepth;
  21491. this._creationFunc = creationFunc;
  21492. this._minPoint = minPoint;
  21493. this._maxPoint = maxPoint;
  21494. this._boundingVectors.push(minPoint.clone());
  21495. this._boundingVectors.push(maxPoint.clone());
  21496. this._boundingVectors.push(minPoint.clone());
  21497. this._boundingVectors[2].x = maxPoint.x;
  21498. this._boundingVectors.push(minPoint.clone());
  21499. this._boundingVectors[3].y = maxPoint.y;
  21500. this._boundingVectors.push(minPoint.clone());
  21501. this._boundingVectors[4].z = maxPoint.z;
  21502. this._boundingVectors.push(maxPoint.clone());
  21503. this._boundingVectors[5].z = minPoint.z;
  21504. this._boundingVectors.push(maxPoint.clone());
  21505. this._boundingVectors[6].x = minPoint.x;
  21506. this._boundingVectors.push(maxPoint.clone());
  21507. this._boundingVectors[7].y = minPoint.y;
  21508. }
  21509. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  21510. // Property
  21511. get: function () {
  21512. return this._capacity;
  21513. },
  21514. enumerable: true,
  21515. configurable: true
  21516. });
  21517. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  21518. get: function () {
  21519. return this._minPoint;
  21520. },
  21521. enumerable: true,
  21522. configurable: true
  21523. });
  21524. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  21525. get: function () {
  21526. return this._maxPoint;
  21527. },
  21528. enumerable: true,
  21529. configurable: true
  21530. });
  21531. // Methods
  21532. OctreeBlock.prototype.addEntry = function (entry) {
  21533. if (this.blocks) {
  21534. for (var index = 0; index < this.blocks.length; index++) {
  21535. var block = this.blocks[index];
  21536. block.addEntry(entry);
  21537. }
  21538. return;
  21539. }
  21540. this._creationFunc(entry, this);
  21541. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  21542. this.createInnerBlocks();
  21543. }
  21544. };
  21545. OctreeBlock.prototype.addEntries = function (entries) {
  21546. for (var index = 0; index < entries.length; index++) {
  21547. var mesh = entries[index];
  21548. this.addEntry(mesh);
  21549. }
  21550. };
  21551. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  21552. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  21553. if (this.blocks) {
  21554. for (var index = 0; index < this.blocks.length; index++) {
  21555. var block = this.blocks[index];
  21556. block.select(frustumPlanes, selection, allowDuplicate);
  21557. }
  21558. return;
  21559. }
  21560. if (allowDuplicate) {
  21561. selection.concat(this.entries);
  21562. }
  21563. else {
  21564. selection.concatWithNoDuplicate(this.entries);
  21565. }
  21566. }
  21567. };
  21568. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  21569. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  21570. if (this.blocks) {
  21571. for (var index = 0; index < this.blocks.length; index++) {
  21572. var block = this.blocks[index];
  21573. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  21574. }
  21575. return;
  21576. }
  21577. if (allowDuplicate) {
  21578. selection.concat(this.entries);
  21579. }
  21580. else {
  21581. selection.concatWithNoDuplicate(this.entries);
  21582. }
  21583. }
  21584. };
  21585. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  21586. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  21587. if (this.blocks) {
  21588. for (var index = 0; index < this.blocks.length; index++) {
  21589. var block = this.blocks[index];
  21590. block.intersectsRay(ray, selection);
  21591. }
  21592. return;
  21593. }
  21594. selection.concatWithNoDuplicate(this.entries);
  21595. }
  21596. };
  21597. OctreeBlock.prototype.createInnerBlocks = function () {
  21598. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  21599. };
  21600. return OctreeBlock;
  21601. })();
  21602. BABYLON.OctreeBlock = OctreeBlock;
  21603. })(BABYLON || (BABYLON = {}));
  21604. //# sourceMappingURL=babylon.octreeBlock.js.map
  21605. var BABYLON;
  21606. (function (BABYLON) {
  21607. var Bone = (function () {
  21608. function Bone(name, skeleton, parentBone, matrix) {
  21609. this.name = name;
  21610. this.children = new Array();
  21611. this.animations = new Array();
  21612. this._worldTransform = new BABYLON.Matrix();
  21613. this._absoluteTransform = new BABYLON.Matrix();
  21614. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  21615. this._skeleton = skeleton;
  21616. this._matrix = matrix;
  21617. this._baseMatrix = matrix;
  21618. skeleton.bones.push(this);
  21619. if (parentBone) {
  21620. this._parent = parentBone;
  21621. parentBone.children.push(this);
  21622. }
  21623. else {
  21624. this._parent = null;
  21625. }
  21626. this._updateDifferenceMatrix();
  21627. }
  21628. // Members
  21629. Bone.prototype.getParent = function () {
  21630. return this._parent;
  21631. };
  21632. Bone.prototype.getLocalMatrix = function () {
  21633. return this._matrix;
  21634. };
  21635. Bone.prototype.getBaseMatrix = function () {
  21636. return this._baseMatrix;
  21637. };
  21638. Bone.prototype.getWorldMatrix = function () {
  21639. return this._worldTransform;
  21640. };
  21641. Bone.prototype.getInvertedAbsoluteTransform = function () {
  21642. return this._invertedAbsoluteTransform;
  21643. };
  21644. Bone.prototype.getAbsoluteMatrix = function () {
  21645. var matrix = this._matrix.clone();
  21646. var parent = this._parent;
  21647. while (parent) {
  21648. matrix = matrix.multiply(parent.getLocalMatrix());
  21649. parent = parent.getParent();
  21650. }
  21651. return matrix;
  21652. };
  21653. // Methods
  21654. Bone.prototype.updateMatrix = function (matrix) {
  21655. this._matrix = matrix;
  21656. this._skeleton._markAsDirty();
  21657. this._updateDifferenceMatrix();
  21658. };
  21659. Bone.prototype._updateDifferenceMatrix = function () {
  21660. if (this._parent) {
  21661. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  21662. }
  21663. else {
  21664. this._absoluteTransform.copyFrom(this._matrix);
  21665. }
  21666. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  21667. for (var index = 0; index < this.children.length; index++) {
  21668. this.children[index]._updateDifferenceMatrix();
  21669. }
  21670. };
  21671. Bone.prototype.markAsDirty = function () {
  21672. this._skeleton._markAsDirty();
  21673. };
  21674. return Bone;
  21675. })();
  21676. BABYLON.Bone = Bone;
  21677. })(BABYLON || (BABYLON = {}));
  21678. //# sourceMappingURL=babylon.bone.js.map
  21679. var BABYLON;
  21680. (function (BABYLON) {
  21681. var Skeleton = (function () {
  21682. function Skeleton(name, id, scene) {
  21683. this.name = name;
  21684. this.id = id;
  21685. this.bones = new Array();
  21686. this._isDirty = true;
  21687. this._identity = BABYLON.Matrix.Identity();
  21688. this.bones = [];
  21689. this._scene = scene;
  21690. scene.skeletons.push(this);
  21691. this.prepare();
  21692. //make sure it will recalculate the matrix next time prepare is called.
  21693. this._isDirty = true;
  21694. }
  21695. // Members
  21696. Skeleton.prototype.getTransformMatrices = function () {
  21697. return this._transformMatrices;
  21698. };
  21699. // Methods
  21700. Skeleton.prototype._markAsDirty = function () {
  21701. this._isDirty = true;
  21702. };
  21703. Skeleton.prototype.prepare = function () {
  21704. if (!this._isDirty) {
  21705. return;
  21706. }
  21707. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  21708. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  21709. }
  21710. for (var index = 0; index < this.bones.length; index++) {
  21711. var bone = this.bones[index];
  21712. var parentBone = bone.getParent();
  21713. if (parentBone) {
  21714. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  21715. }
  21716. else {
  21717. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  21718. }
  21719. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  21720. }
  21721. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  21722. this._isDirty = false;
  21723. this._scene._activeBones += this.bones.length;
  21724. };
  21725. Skeleton.prototype.getAnimatables = function () {
  21726. if (!this._animatables || this._animatables.length !== this.bones.length) {
  21727. this._animatables = [];
  21728. for (var index = 0; index < this.bones.length; index++) {
  21729. this._animatables.push(this.bones[index]);
  21730. }
  21731. }
  21732. return this._animatables;
  21733. };
  21734. Skeleton.prototype.clone = function (name, id) {
  21735. var result = new Skeleton(name, id || name, this._scene);
  21736. for (var index = 0; index < this.bones.length; index++) {
  21737. var source = this.bones[index];
  21738. var parentBone = null;
  21739. if (source.getParent()) {
  21740. var parentIndex = this.bones.indexOf(source.getParent());
  21741. parentBone = result.bones[parentIndex];
  21742. }
  21743. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  21744. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  21745. }
  21746. return result;
  21747. };
  21748. return Skeleton;
  21749. })();
  21750. BABYLON.Skeleton = Skeleton;
  21751. })(BABYLON || (BABYLON = {}));
  21752. //# sourceMappingURL=babylon.skeleton.js.map
  21753. var BABYLON;
  21754. (function (BABYLON) {
  21755. var PostProcess = (function () {
  21756. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  21757. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  21758. this.name = name;
  21759. this.width = -1;
  21760. this.height = -1;
  21761. this._reusable = false;
  21762. this._textures = new BABYLON.SmartArray(2);
  21763. this._currentRenderTextureInd = 0;
  21764. if (camera != null) {
  21765. this._camera = camera;
  21766. this._scene = camera.getScene();
  21767. camera.attachPostProcess(this);
  21768. this._engine = this._scene.getEngine();
  21769. }
  21770. else {
  21771. this._engine = engine;
  21772. }
  21773. this._renderRatio = ratio;
  21774. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  21775. this._reusable = reusable || false;
  21776. samplers = samplers || [];
  21777. samplers.push("textureSampler");
  21778. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  21779. }
  21780. PostProcess.prototype.isReusable = function () {
  21781. return this._reusable;
  21782. };
  21783. PostProcess.prototype.activate = function (camera, sourceTexture) {
  21784. camera = camera || this._camera;
  21785. var scene = camera.getScene();
  21786. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  21787. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  21788. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  21789. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  21790. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  21791. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  21792. if (this._textures.length > 0) {
  21793. for (var i = 0; i < this._textures.length; i++) {
  21794. this._engine._releaseTexture(this._textures.data[i]);
  21795. }
  21796. this._textures.reset();
  21797. }
  21798. this.width = desiredWidth;
  21799. this.height = desiredHeight;
  21800. 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 }));
  21801. if (this._reusable) {
  21802. 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 }));
  21803. }
  21804. if (this.onSizeChanged) {
  21805. this.onSizeChanged();
  21806. }
  21807. }
  21808. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  21809. if (this.onActivate) {
  21810. this.onActivate(camera);
  21811. }
  21812. // Clear
  21813. if (this.clearColor) {
  21814. this._engine.clear(this.clearColor, true, true);
  21815. }
  21816. else {
  21817. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  21818. }
  21819. if (this._reusable) {
  21820. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  21821. }
  21822. };
  21823. PostProcess.prototype.apply = function () {
  21824. // Check
  21825. if (!this._effect.isReady())
  21826. return null;
  21827. // States
  21828. this._engine.enableEffect(this._effect);
  21829. this._engine.setState(false);
  21830. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21831. this._engine.setDepthBuffer(false);
  21832. this._engine.setDepthWrite(false);
  21833. // Texture
  21834. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  21835. // Parameters
  21836. if (this.onApply) {
  21837. this.onApply(this._effect);
  21838. }
  21839. return this._effect;
  21840. };
  21841. PostProcess.prototype.dispose = function (camera) {
  21842. camera = camera || this._camera;
  21843. if (this._textures.length > 0) {
  21844. for (var i = 0; i < this._textures.length; i++) {
  21845. this._engine._releaseTexture(this._textures.data[i]);
  21846. }
  21847. this._textures.reset();
  21848. }
  21849. if (!camera) {
  21850. return;
  21851. }
  21852. camera.detachPostProcess(this);
  21853. var index = camera._postProcesses.indexOf(this);
  21854. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  21855. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  21856. }
  21857. };
  21858. return PostProcess;
  21859. })();
  21860. BABYLON.PostProcess = PostProcess;
  21861. })(BABYLON || (BABYLON = {}));
  21862. //# sourceMappingURL=babylon.postProcess.js.map
  21863. var BABYLON;
  21864. (function (BABYLON) {
  21865. var PostProcessManager = (function () {
  21866. function PostProcessManager(scene) {
  21867. this._vertexDeclaration = [2];
  21868. this._vertexStrideSize = 2 * 4;
  21869. this._scene = scene;
  21870. }
  21871. PostProcessManager.prototype._prepareBuffers = function () {
  21872. if (this._vertexBuffer) {
  21873. return;
  21874. }
  21875. // VBO
  21876. var vertices = [];
  21877. vertices.push(1, 1);
  21878. vertices.push(-1, 1);
  21879. vertices.push(-1, -1);
  21880. vertices.push(1, -1);
  21881. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  21882. // Indices
  21883. var indices = [];
  21884. indices.push(0);
  21885. indices.push(1);
  21886. indices.push(2);
  21887. indices.push(0);
  21888. indices.push(2);
  21889. indices.push(3);
  21890. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  21891. };
  21892. // Methods
  21893. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  21894. var postProcesses = this._scene.activeCamera._postProcesses;
  21895. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  21896. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  21897. return false;
  21898. }
  21899. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  21900. return true;
  21901. };
  21902. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  21903. var engine = this._scene.getEngine();
  21904. for (var index = 0; index < postProcesses.length; index++) {
  21905. if (index < postProcesses.length - 1) {
  21906. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  21907. }
  21908. else {
  21909. if (targetTexture) {
  21910. engine.bindFramebuffer(targetTexture);
  21911. }
  21912. else {
  21913. engine.restoreDefaultFramebuffer();
  21914. }
  21915. }
  21916. var pp = postProcesses[index];
  21917. var effect = pp.apply();
  21918. if (effect) {
  21919. if (pp.onBeforeRender) {
  21920. pp.onBeforeRender(effect);
  21921. }
  21922. // VBOs
  21923. this._prepareBuffers();
  21924. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21925. // Draw order
  21926. engine.draw(true, 0, 6);
  21927. }
  21928. }
  21929. // Restore depth buffer
  21930. engine.setDepthBuffer(true);
  21931. engine.setDepthWrite(true);
  21932. };
  21933. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  21934. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  21935. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  21936. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  21937. return;
  21938. }
  21939. var engine = this._scene.getEngine();
  21940. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  21941. if (index < postProcessesTakenIndices.length - 1) {
  21942. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  21943. }
  21944. else {
  21945. if (targetTexture) {
  21946. engine.bindFramebuffer(targetTexture);
  21947. }
  21948. else {
  21949. engine.restoreDefaultFramebuffer();
  21950. }
  21951. }
  21952. if (doNotPresent) {
  21953. break;
  21954. }
  21955. var pp = postProcesses[postProcessesTakenIndices[index]];
  21956. var effect = pp.apply();
  21957. if (effect) {
  21958. if (pp.onBeforeRender) {
  21959. pp.onBeforeRender(effect);
  21960. }
  21961. // VBOs
  21962. this._prepareBuffers();
  21963. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21964. // Draw order
  21965. engine.draw(true, 0, 6);
  21966. }
  21967. }
  21968. // Restore depth buffer
  21969. engine.setDepthBuffer(true);
  21970. engine.setDepthWrite(true);
  21971. };
  21972. PostProcessManager.prototype.dispose = function () {
  21973. if (this._vertexBuffer) {
  21974. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  21975. this._vertexBuffer = null;
  21976. }
  21977. if (this._indexBuffer) {
  21978. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  21979. this._indexBuffer = null;
  21980. }
  21981. };
  21982. return PostProcessManager;
  21983. })();
  21984. BABYLON.PostProcessManager = PostProcessManager;
  21985. })(BABYLON || (BABYLON = {}));
  21986. //# sourceMappingURL=babylon.postProcessManager.js.map
  21987. var BABYLON;
  21988. (function (BABYLON) {
  21989. var PassPostProcess = (function (_super) {
  21990. __extends(PassPostProcess, _super);
  21991. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21992. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  21993. }
  21994. return PassPostProcess;
  21995. })(BABYLON.PostProcess);
  21996. BABYLON.PassPostProcess = PassPostProcess;
  21997. })(BABYLON || (BABYLON = {}));
  21998. //# sourceMappingURL=babylon.passPostProcess.js.map
  21999. var BABYLON;
  22000. (function (BABYLON) {
  22001. var BlurPostProcess = (function (_super) {
  22002. __extends(BlurPostProcess, _super);
  22003. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  22004. var _this = this;
  22005. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  22006. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  22007. this.direction = direction;
  22008. this.blurWidth = blurWidth;
  22009. this.onApply = function (effect) {
  22010. effect.setFloat2("screenSize", _this.width, _this.height);
  22011. effect.setVector2("direction", _this.direction);
  22012. effect.setFloat("blurWidth", _this.blurWidth);
  22013. };
  22014. }
  22015. return BlurPostProcess;
  22016. })(BABYLON.PostProcess);
  22017. BABYLON.BlurPostProcess = BlurPostProcess;
  22018. })(BABYLON || (BABYLON = {}));
  22019. //# sourceMappingURL=babylon.blurPostProcess.js.map
  22020. var BABYLON;
  22021. (function (BABYLON) {
  22022. var RefractionPostProcess = (function (_super) {
  22023. __extends(RefractionPostProcess, _super);
  22024. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  22025. var _this = this;
  22026. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  22027. this.color = color;
  22028. this.depth = depth;
  22029. this.colorLevel = colorLevel;
  22030. this.onActivate = function (cam) {
  22031. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  22032. };
  22033. this.onApply = function (effect) {
  22034. effect.setColor3("baseColor", _this.color);
  22035. effect.setFloat("depth", _this.depth);
  22036. effect.setFloat("colorLevel", _this.colorLevel);
  22037. effect.setTexture("refractionSampler", _this._refRexture);
  22038. };
  22039. }
  22040. // Methods
  22041. RefractionPostProcess.prototype.dispose = function (camera) {
  22042. if (this._refRexture) {
  22043. this._refRexture.dispose();
  22044. }
  22045. _super.prototype.dispose.call(this, camera);
  22046. };
  22047. return RefractionPostProcess;
  22048. })(BABYLON.PostProcess);
  22049. BABYLON.RefractionPostProcess = RefractionPostProcess;
  22050. })(BABYLON || (BABYLON = {}));
  22051. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  22052. var BABYLON;
  22053. (function (BABYLON) {
  22054. var BlackAndWhitePostProcess = (function (_super) {
  22055. __extends(BlackAndWhitePostProcess, _super);
  22056. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22057. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  22058. }
  22059. return BlackAndWhitePostProcess;
  22060. })(BABYLON.PostProcess);
  22061. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  22062. })(BABYLON || (BABYLON = {}));
  22063. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  22064. var BABYLON;
  22065. (function (BABYLON) {
  22066. var ConvolutionPostProcess = (function (_super) {
  22067. __extends(ConvolutionPostProcess, _super);
  22068. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  22069. var _this = this;
  22070. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  22071. this.kernel = kernel;
  22072. this.onApply = function (effect) {
  22073. effect.setFloat2("screenSize", _this.width, _this.height);
  22074. effect.setArray("kernel", _this.kernel);
  22075. };
  22076. }
  22077. // Statics
  22078. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  22079. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  22080. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  22081. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  22082. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  22083. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  22084. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  22085. return ConvolutionPostProcess;
  22086. })(BABYLON.PostProcess);
  22087. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  22088. })(BABYLON || (BABYLON = {}));
  22089. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  22090. var BABYLON;
  22091. (function (BABYLON) {
  22092. var FilterPostProcess = (function (_super) {
  22093. __extends(FilterPostProcess, _super);
  22094. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  22095. var _this = this;
  22096. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  22097. this.kernelMatrix = kernelMatrix;
  22098. this.onApply = function (effect) {
  22099. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  22100. };
  22101. }
  22102. return FilterPostProcess;
  22103. })(BABYLON.PostProcess);
  22104. BABYLON.FilterPostProcess = FilterPostProcess;
  22105. })(BABYLON || (BABYLON = {}));
  22106. //# sourceMappingURL=babylon.filterPostProcess.js.map
  22107. var BABYLON;
  22108. (function (BABYLON) {
  22109. var FxaaPostProcess = (function (_super) {
  22110. __extends(FxaaPostProcess, _super);
  22111. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22112. var _this = this;
  22113. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  22114. this.onSizeChanged = function () {
  22115. _this.texelWidth = 1.0 / _this.width;
  22116. _this.texelHeight = 1.0 / _this.height;
  22117. };
  22118. this.onApply = function (effect) {
  22119. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  22120. };
  22121. }
  22122. return FxaaPostProcess;
  22123. })(BABYLON.PostProcess);
  22124. BABYLON.FxaaPostProcess = FxaaPostProcess;
  22125. })(BABYLON || (BABYLON = {}));
  22126. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  22127. var BABYLON;
  22128. (function (BABYLON) {
  22129. var StereoscopicInterlacePostProcess = (function (_super) {
  22130. __extends(StereoscopicInterlacePostProcess, _super);
  22131. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  22132. var _this = this;
  22133. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  22134. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  22135. this.onSizeChanged = function () {
  22136. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  22137. };
  22138. this.onApply = function (effect) {
  22139. effect.setTextureFromPostProcess("camASampler", postProcessA);
  22140. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  22141. };
  22142. }
  22143. return StereoscopicInterlacePostProcess;
  22144. })(BABYLON.PostProcess);
  22145. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  22146. })(BABYLON || (BABYLON = {}));
  22147. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  22148. var BABYLON;
  22149. (function (BABYLON) {
  22150. var LensFlare = (function () {
  22151. function LensFlare(size, position, color, imgUrl, system) {
  22152. this.size = size;
  22153. this.position = position;
  22154. this.dispose = function () {
  22155. if (this.texture) {
  22156. this.texture.dispose();
  22157. }
  22158. // Remove from scene
  22159. var index = this._system.lensFlares.indexOf(this);
  22160. this._system.lensFlares.splice(index, 1);
  22161. };
  22162. this.color = color || new BABYLON.Color3(1, 1, 1);
  22163. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  22164. this._system = system;
  22165. system.lensFlares.push(this);
  22166. }
  22167. return LensFlare;
  22168. })();
  22169. BABYLON.LensFlare = LensFlare;
  22170. })(BABYLON || (BABYLON = {}));
  22171. //# sourceMappingURL=babylon.lensFlare.js.map
  22172. var BABYLON;
  22173. (function (BABYLON) {
  22174. var LensFlareSystem = (function () {
  22175. function LensFlareSystem(name, emitter, scene) {
  22176. this.name = name;
  22177. this.lensFlares = new Array();
  22178. this.borderLimit = 300;
  22179. this._vertexDeclaration = [2];
  22180. this._vertexStrideSize = 2 * 4;
  22181. this._isEnabled = true;
  22182. this._scene = scene;
  22183. this._emitter = emitter;
  22184. scene.lensFlareSystems.push(this);
  22185. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  22186. // VBO
  22187. var vertices = [];
  22188. vertices.push(1, 1);
  22189. vertices.push(-1, 1);
  22190. vertices.push(-1, -1);
  22191. vertices.push(1, -1);
  22192. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  22193. // Indices
  22194. var indices = [];
  22195. indices.push(0);
  22196. indices.push(1);
  22197. indices.push(2);
  22198. indices.push(0);
  22199. indices.push(2);
  22200. indices.push(3);
  22201. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  22202. // Effects
  22203. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  22204. }
  22205. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  22206. get: function () {
  22207. return this._isEnabled;
  22208. },
  22209. set: function (value) {
  22210. this._isEnabled = value;
  22211. },
  22212. enumerable: true,
  22213. configurable: true
  22214. });
  22215. LensFlareSystem.prototype.getScene = function () {
  22216. return this._scene;
  22217. };
  22218. LensFlareSystem.prototype.getEmitter = function () {
  22219. return this._emitter;
  22220. };
  22221. LensFlareSystem.prototype.getEmitterPosition = function () {
  22222. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  22223. };
  22224. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  22225. var position = this.getEmitterPosition();
  22226. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  22227. this._positionX = position.x;
  22228. this._positionY = position.y;
  22229. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  22230. if (position.z > 0) {
  22231. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  22232. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  22233. return true;
  22234. }
  22235. }
  22236. return false;
  22237. };
  22238. LensFlareSystem.prototype._isVisible = function () {
  22239. if (!this._isEnabled) {
  22240. return false;
  22241. }
  22242. var emitterPosition = this.getEmitterPosition();
  22243. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  22244. var distance = direction.length();
  22245. direction.normalize();
  22246. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  22247. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  22248. return !pickInfo.hit || pickInfo.distance > distance;
  22249. };
  22250. LensFlareSystem.prototype.render = function () {
  22251. if (!this._effect.isReady())
  22252. return false;
  22253. var engine = this._scene.getEngine();
  22254. var viewport = this._scene.activeCamera.viewport;
  22255. var globalViewport = viewport.toGlobal(engine);
  22256. // Position
  22257. if (!this.computeEffectivePosition(globalViewport)) {
  22258. return false;
  22259. }
  22260. // Visibility
  22261. if (!this._isVisible()) {
  22262. return false;
  22263. }
  22264. // Intensity
  22265. var awayX;
  22266. var awayY;
  22267. if (this._positionX < this.borderLimit + globalViewport.x) {
  22268. awayX = this.borderLimit + globalViewport.x - this._positionX;
  22269. }
  22270. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  22271. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  22272. }
  22273. else {
  22274. awayX = 0;
  22275. }
  22276. if (this._positionY < this.borderLimit + globalViewport.y) {
  22277. awayY = this.borderLimit + globalViewport.y - this._positionY;
  22278. }
  22279. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  22280. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  22281. }
  22282. else {
  22283. awayY = 0;
  22284. }
  22285. var away = (awayX > awayY) ? awayX : awayY;
  22286. if (away > this.borderLimit) {
  22287. away = this.borderLimit;
  22288. }
  22289. var intensity = 1.0 - (away / this.borderLimit);
  22290. if (intensity < 0) {
  22291. return false;
  22292. }
  22293. if (intensity > 1.0) {
  22294. intensity = 1.0;
  22295. }
  22296. // Position
  22297. var centerX = globalViewport.x + globalViewport.width / 2;
  22298. var centerY = globalViewport.y + globalViewport.height / 2;
  22299. var distX = centerX - this._positionX;
  22300. var distY = centerY - this._positionY;
  22301. // Effects
  22302. engine.enableEffect(this._effect);
  22303. engine.setState(false);
  22304. engine.setDepthBuffer(false);
  22305. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  22306. // VBOs
  22307. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  22308. // Flares
  22309. for (var index = 0; index < this.lensFlares.length; index++) {
  22310. var flare = this.lensFlares[index];
  22311. var x = centerX - (distX * flare.position);
  22312. var y = centerY - (distY * flare.position);
  22313. var cw = flare.size;
  22314. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  22315. var cx = 2 * (x / globalViewport.width) - 1.0;
  22316. var cy = 1.0 - 2 * (y / globalViewport.height);
  22317. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  22318. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  22319. // Texture
  22320. this._effect.setTexture("textureSampler", flare.texture);
  22321. // Color
  22322. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  22323. // Draw order
  22324. engine.draw(true, 0, 6);
  22325. }
  22326. engine.setDepthBuffer(true);
  22327. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22328. return true;
  22329. };
  22330. LensFlareSystem.prototype.dispose = function () {
  22331. if (this._vertexBuffer) {
  22332. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22333. this._vertexBuffer = null;
  22334. }
  22335. if (this._indexBuffer) {
  22336. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22337. this._indexBuffer = null;
  22338. }
  22339. while (this.lensFlares.length) {
  22340. this.lensFlares[0].dispose();
  22341. }
  22342. // Remove from scene
  22343. var index = this._scene.lensFlareSystems.indexOf(this);
  22344. this._scene.lensFlareSystems.splice(index, 1);
  22345. };
  22346. return LensFlareSystem;
  22347. })();
  22348. BABYLON.LensFlareSystem = LensFlareSystem;
  22349. })(BABYLON || (BABYLON = {}));
  22350. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  22351. var BABYLON;
  22352. (function (BABYLON) {
  22353. var CannonJSPlugin = (function () {
  22354. function CannonJSPlugin() {
  22355. this._registeredMeshes = [];
  22356. this._physicsMaterials = [];
  22357. this.updateBodyPosition = function (mesh) {
  22358. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22359. var registeredMesh = this._registeredMeshes[index];
  22360. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22361. var body = registeredMesh.body;
  22362. var center = mesh.getBoundingInfo().boundingBox.center;
  22363. body.position.set(center.x, center.z, center.y);
  22364. body.quaternion.x = mesh.rotationQuaternion.x;
  22365. body.quaternion.z = mesh.rotationQuaternion.y;
  22366. body.quaternion.y = mesh.rotationQuaternion.z;
  22367. body.quaternion.w = -mesh.rotationQuaternion.w;
  22368. return;
  22369. }
  22370. }
  22371. };
  22372. }
  22373. CannonJSPlugin.prototype.initialize = function (iterations) {
  22374. if (iterations === void 0) { iterations = 10; }
  22375. this._world = new CANNON.World();
  22376. this._world.broadphase = new CANNON.NaiveBroadphase();
  22377. this._world.solver.iterations = iterations;
  22378. };
  22379. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  22380. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  22381. };
  22382. CannonJSPlugin.prototype.runOneStep = function (delta) {
  22383. this._world.step(delta);
  22384. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22385. var registeredMesh = this._registeredMeshes[index];
  22386. if (registeredMesh.isChild) {
  22387. continue;
  22388. }
  22389. // Body position
  22390. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  22391. var deltaPos = registeredMesh.delta;
  22392. if (deltaPos) {
  22393. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  22394. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  22395. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  22396. }
  22397. else {
  22398. registeredMesh.mesh.position.x = bodyX;
  22399. registeredMesh.mesh.position.y = bodyZ;
  22400. registeredMesh.mesh.position.z = bodyY;
  22401. }
  22402. if (!registeredMesh.mesh.rotationQuaternion) {
  22403. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22404. }
  22405. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  22406. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  22407. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  22408. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  22409. }
  22410. };
  22411. CannonJSPlugin.prototype.setGravity = function (gravity) {
  22412. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  22413. };
  22414. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  22415. this.unregisterMesh(mesh);
  22416. mesh.computeWorldMatrix(true);
  22417. switch (impostor) {
  22418. case BABYLON.PhysicsEngine.SphereImpostor:
  22419. var bbox = mesh.getBoundingInfo().boundingBox;
  22420. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22421. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22422. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22423. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  22424. case BABYLON.PhysicsEngine.BoxImpostor:
  22425. bbox = mesh.getBoundingInfo().boundingBox;
  22426. var min = bbox.minimumWorld;
  22427. var max = bbox.maximumWorld;
  22428. var box = max.subtract(min).scale(0.5);
  22429. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  22430. case BABYLON.PhysicsEngine.PlaneImpostor:
  22431. return this._createPlane(mesh, options);
  22432. case BABYLON.PhysicsEngine.MeshImpostor:
  22433. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22434. var rawFaces = mesh.getIndices();
  22435. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  22436. }
  22437. return null;
  22438. };
  22439. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  22440. var shape = new CANNON.Sphere(radius);
  22441. if (!options) {
  22442. return shape;
  22443. }
  22444. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22445. };
  22446. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  22447. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  22448. if (!options) {
  22449. return shape;
  22450. }
  22451. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22452. };
  22453. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  22454. var shape = new CANNON.Plane();
  22455. if (!options) {
  22456. return shape;
  22457. }
  22458. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22459. };
  22460. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  22461. var verts = [], faces = [];
  22462. mesh.computeWorldMatrix(true);
  22463. // Get vertices
  22464. for (var i = 0; i < rawVerts.length; i += 3) {
  22465. var transformed = BABYLON.Vector3.Zero();
  22466. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  22467. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  22468. }
  22469. // Get faces
  22470. for (var j = 0; j < rawFaces.length; j += 3) {
  22471. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  22472. }
  22473. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  22474. if (!options) {
  22475. return shape;
  22476. }
  22477. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22478. };
  22479. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  22480. var index;
  22481. var mat;
  22482. for (index = 0; index < this._physicsMaterials.length; index++) {
  22483. mat = this._physicsMaterials[index];
  22484. if (mat.friction === friction && mat.restitution === restitution) {
  22485. return mat;
  22486. }
  22487. }
  22488. var currentMat = new CANNON.Material();
  22489. currentMat.friction = friction;
  22490. currentMat.restitution = restitution;
  22491. this._physicsMaterials.push(currentMat);
  22492. for (index = 0; index < this._physicsMaterials.length; index++) {
  22493. mat = this._physicsMaterials[index];
  22494. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  22495. contactMaterial.contactEquationStiffness = 1e10;
  22496. contactMaterial.contactEquationRegularizationTime = 10;
  22497. this._world.addContactMaterial(contactMaterial);
  22498. }
  22499. return currentMat;
  22500. };
  22501. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  22502. var initialRotation = null;
  22503. if (mesh.rotationQuaternion) {
  22504. initialRotation = mesh.rotationQuaternion.clone();
  22505. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22506. }
  22507. // The delta between the mesh position and the mesh bounding box center
  22508. var bbox = mesh.getBoundingInfo().boundingBox;
  22509. var deltaPosition = mesh.position.subtract(bbox.center);
  22510. var material = this._addMaterial(friction, restitution);
  22511. var body = new CANNON.RigidBody(mass, shape, material);
  22512. if (initialRotation) {
  22513. body.quaternion.x = initialRotation.x;
  22514. body.quaternion.z = initialRotation.y;
  22515. body.quaternion.y = initialRotation.z;
  22516. body.quaternion.w = -initialRotation.w;
  22517. }
  22518. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  22519. this._world.add(body);
  22520. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  22521. return body;
  22522. };
  22523. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  22524. var compoundShape = new CANNON.Compound();
  22525. for (var index = 0; index < parts.length; index++) {
  22526. var mesh = parts[index].mesh;
  22527. var shape = this.registerMesh(mesh, parts[index].impostor);
  22528. if (index == 0) {
  22529. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  22530. }
  22531. else {
  22532. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  22533. }
  22534. }
  22535. var initialMesh = parts[0].mesh;
  22536. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  22537. body.parts = parts;
  22538. return body;
  22539. };
  22540. CannonJSPlugin.prototype._unbindBody = function (body) {
  22541. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22542. var registeredMesh = this._registeredMeshes[index];
  22543. if (registeredMesh.body === body) {
  22544. registeredMesh.body = null;
  22545. registeredMesh.delta = 0;
  22546. }
  22547. }
  22548. };
  22549. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  22550. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22551. var registeredMesh = this._registeredMeshes[index];
  22552. if (registeredMesh.mesh === mesh) {
  22553. // Remove body
  22554. if (registeredMesh.body) {
  22555. this._world.remove(registeredMesh.body);
  22556. this._unbindBody(registeredMesh.body);
  22557. }
  22558. this._registeredMeshes.splice(index, 1);
  22559. return;
  22560. }
  22561. }
  22562. };
  22563. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  22564. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  22565. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  22566. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22567. var registeredMesh = this._registeredMeshes[index];
  22568. if (registeredMesh.mesh === mesh) {
  22569. registeredMesh.body.applyImpulse(impulse, worldPoint);
  22570. return;
  22571. }
  22572. }
  22573. };
  22574. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  22575. var body1 = null, body2 = null;
  22576. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22577. var registeredMesh = this._registeredMeshes[index];
  22578. if (registeredMesh.mesh === mesh1) {
  22579. body1 = registeredMesh.body;
  22580. }
  22581. else if (registeredMesh.mesh === mesh2) {
  22582. body2 = registeredMesh.body;
  22583. }
  22584. }
  22585. if (!body1 || !body2) {
  22586. return false;
  22587. }
  22588. 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));
  22589. this._world.addConstraint(constraint);
  22590. return true;
  22591. };
  22592. CannonJSPlugin.prototype.dispose = function () {
  22593. while (this._registeredMeshes.length) {
  22594. this.unregisterMesh(this._registeredMeshes[0].mesh);
  22595. }
  22596. };
  22597. CannonJSPlugin.prototype.isSupported = function () {
  22598. return window.CANNON !== undefined;
  22599. };
  22600. return CannonJSPlugin;
  22601. })();
  22602. BABYLON.CannonJSPlugin = CannonJSPlugin;
  22603. })(BABYLON || (BABYLON = {}));
  22604. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  22605. var BABYLON;
  22606. (function (BABYLON) {
  22607. var OimoJSPlugin = (function () {
  22608. function OimoJSPlugin() {
  22609. this._registeredMeshes = [];
  22610. /**
  22611. * Update the body position according to the mesh position
  22612. * @param mesh
  22613. */
  22614. this.updateBodyPosition = function (mesh) {
  22615. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22616. var registeredMesh = this._registeredMeshes[index];
  22617. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22618. var body = registeredMesh.body.body;
  22619. mesh.computeWorldMatrix(true);
  22620. var center = mesh.getBoundingInfo().boundingBox.center;
  22621. body.setPosition(new OIMO.Vec3(center.x, center.y, center.z));
  22622. body.setRotation(new OIMO.Vec3(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z));
  22623. body.sleeping = false;
  22624. return;
  22625. }
  22626. // Case where the parent has been updated
  22627. if (registeredMesh.mesh.parent === mesh) {
  22628. mesh.computeWorldMatrix(true);
  22629. registeredMesh.mesh.computeWorldMatrix(true);
  22630. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  22631. var absoluteRotation = mesh.rotation;
  22632. body = registeredMesh.body.body;
  22633. body.setPosition(new OIMO.Vec3(absolutePosition.x, absolutePosition.y, absolutePosition.z));
  22634. body.setRotation(new OIMO.Vec3(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z));
  22635. body.sleeping = false;
  22636. return;
  22637. }
  22638. }
  22639. };
  22640. }
  22641. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  22642. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  22643. };
  22644. OimoJSPlugin.prototype.initialize = function (iterations) {
  22645. this._world = new OIMO.World();
  22646. this._world.clear();
  22647. };
  22648. OimoJSPlugin.prototype.setGravity = function (gravity) {
  22649. this._world.gravity = gravity;
  22650. };
  22651. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  22652. var body = null;
  22653. this.unregisterMesh(mesh);
  22654. mesh.computeWorldMatrix(true);
  22655. var initialRotation = null;
  22656. if (mesh.rotationQuaternion) {
  22657. initialRotation = mesh.rotationQuaternion.clone();
  22658. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22659. mesh.computeWorldMatrix(true);
  22660. }
  22661. var bbox = mesh.getBoundingInfo().boundingBox;
  22662. // The delta between the mesh position and the mesh bounding box center
  22663. var deltaPosition = mesh.position.subtract(bbox.center);
  22664. // Transform delta position with the rotation
  22665. if (initialRotation) {
  22666. var m = new BABYLON.Matrix();
  22667. initialRotation.toRotationMatrix(m);
  22668. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  22669. }
  22670. // register mesh
  22671. switch (impostor) {
  22672. case BABYLON.PhysicsEngine.SphereImpostor:
  22673. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22674. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22675. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22676. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  22677. body = new OIMO.Body({
  22678. type: 'sphere',
  22679. size: [size],
  22680. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  22681. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  22682. move: options.mass != 0,
  22683. config: [options.mass, options.friction, options.restitution],
  22684. world: this._world
  22685. });
  22686. break;
  22687. case BABYLON.PhysicsEngine.PlaneImpostor:
  22688. //Oimo "fakes" a cylinder as a box, so why don't we!
  22689. case BABYLON.PhysicsEngine.CylinderImpostor:
  22690. case BABYLON.PhysicsEngine.BoxImpostor:
  22691. var min = bbox.minimumWorld;
  22692. var max = bbox.maximumWorld;
  22693. var box = max.subtract(min);
  22694. var sizeX = this._checkWithEpsilon(box.x);
  22695. var sizeY = this._checkWithEpsilon(box.y);
  22696. var sizeZ = this._checkWithEpsilon(box.z);
  22697. body = new OIMO.Body({
  22698. type: 'box',
  22699. size: [sizeX, sizeY, sizeZ],
  22700. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  22701. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  22702. move: options.mass != 0,
  22703. config: [options.mass, options.friction, options.restitution],
  22704. world: this._world
  22705. });
  22706. break;
  22707. }
  22708. //If quaternion was set as the rotation of the object
  22709. if (initialRotation) {
  22710. //We have to access the rigid body's properties to set the quaternion.
  22711. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  22712. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  22713. //update the internal rotation matrix
  22714. body.body.syncShapes();
  22715. }
  22716. this._registeredMeshes.push({
  22717. mesh: mesh,
  22718. body: body,
  22719. delta: deltaPosition
  22720. });
  22721. return body;
  22722. };
  22723. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  22724. var types = [], sizes = [], positions = [], rotations = [];
  22725. var initialMesh = parts[0].mesh;
  22726. for (var index = 0; index < parts.length; index++) {
  22727. var part = parts[index];
  22728. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  22729. types.push(bodyParameters.type);
  22730. sizes.push.apply(sizes, bodyParameters.size);
  22731. positions.push.apply(positions, bodyParameters.pos);
  22732. rotations.push.apply(rotations, bodyParameters.rot);
  22733. }
  22734. var body = new OIMO.Body({
  22735. type: types,
  22736. size: sizes,
  22737. pos: positions,
  22738. rot: rotations,
  22739. move: options.mass != 0,
  22740. config: [options.mass, options.friction, options.restitution],
  22741. world: this._world
  22742. });
  22743. this._registeredMeshes.push({
  22744. mesh: initialMesh,
  22745. body: body
  22746. });
  22747. return body;
  22748. };
  22749. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  22750. var bodyParameters = null;
  22751. var mesh = part.mesh;
  22752. // We need the bounding box/sphere info to compute the physics body
  22753. mesh.computeWorldMatrix();
  22754. switch (part.impostor) {
  22755. case BABYLON.PhysicsEngine.SphereImpostor:
  22756. var bbox = mesh.getBoundingInfo().boundingBox;
  22757. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22758. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22759. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22760. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  22761. bodyParameters = {
  22762. type: 'sphere',
  22763. /* bug with oimo : sphere needs 3 sizes in this case */
  22764. size: [size, -1, -1],
  22765. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  22766. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  22767. };
  22768. break;
  22769. case BABYLON.PhysicsEngine.PlaneImpostor:
  22770. case BABYLON.PhysicsEngine.BoxImpostor:
  22771. bbox = mesh.getBoundingInfo().boundingBox;
  22772. var min = bbox.minimumWorld;
  22773. var max = bbox.maximumWorld;
  22774. var box = max.subtract(min);
  22775. var sizeX = this._checkWithEpsilon(box.x);
  22776. var sizeY = this._checkWithEpsilon(box.y);
  22777. var sizeZ = this._checkWithEpsilon(box.z);
  22778. var relativePosition = mesh.position;
  22779. bodyParameters = {
  22780. type: 'box',
  22781. size: [sizeX, sizeY, sizeZ],
  22782. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  22783. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  22784. };
  22785. break;
  22786. }
  22787. return bodyParameters;
  22788. };
  22789. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  22790. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22791. var registeredMesh = this._registeredMeshes[index];
  22792. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22793. if (registeredMesh.body) {
  22794. this._world.removeRigidBody(registeredMesh.body.body);
  22795. this._unbindBody(registeredMesh.body);
  22796. }
  22797. this._registeredMeshes.splice(index, 1);
  22798. return;
  22799. }
  22800. }
  22801. };
  22802. OimoJSPlugin.prototype._unbindBody = function (body) {
  22803. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22804. var registeredMesh = this._registeredMeshes[index];
  22805. if (registeredMesh.body === body) {
  22806. registeredMesh.body = null;
  22807. }
  22808. }
  22809. };
  22810. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  22811. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22812. var registeredMesh = this._registeredMeshes[index];
  22813. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22814. // Get object mass to have a behaviour similar to cannon.js
  22815. var mass = registeredMesh.body.body.massInfo.mass;
  22816. // The force is scaled with the mass of object
  22817. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  22818. return;
  22819. }
  22820. }
  22821. };
  22822. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22823. var body1 = null, body2 = null;
  22824. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22825. var registeredMesh = this._registeredMeshes[index];
  22826. if (registeredMesh.mesh === mesh1) {
  22827. body1 = registeredMesh.body.body;
  22828. }
  22829. else if (registeredMesh.mesh === mesh2) {
  22830. body2 = registeredMesh.body.body;
  22831. }
  22832. }
  22833. if (!body1 || !body2) {
  22834. return false;
  22835. }
  22836. if (!options) {
  22837. options = {};
  22838. }
  22839. new OIMO.Link({
  22840. type: options.type,
  22841. body1: body1,
  22842. body2: body2,
  22843. min: options.min,
  22844. max: options.max,
  22845. axe1: options.axe1,
  22846. axe2: options.axe2,
  22847. pos1: [pivot1.x, pivot1.y, pivot1.z],
  22848. pos2: [pivot2.x, pivot2.y, pivot2.z],
  22849. collision: options.collision,
  22850. spring: options.spring,
  22851. world: this._world
  22852. });
  22853. return true;
  22854. };
  22855. OimoJSPlugin.prototype.dispose = function () {
  22856. this._world.clear();
  22857. while (this._registeredMeshes.length) {
  22858. this.unregisterMesh(this._registeredMeshes[0].mesh);
  22859. }
  22860. };
  22861. OimoJSPlugin.prototype.isSupported = function () {
  22862. return OIMO !== undefined;
  22863. };
  22864. OimoJSPlugin.prototype._getLastShape = function (body) {
  22865. var lastShape = body.shapes;
  22866. while (lastShape.next) {
  22867. lastShape = lastShape.next;
  22868. }
  22869. return lastShape;
  22870. };
  22871. OimoJSPlugin.prototype.runOneStep = function (time) {
  22872. this._world.step();
  22873. // Update the position of all registered meshes
  22874. var i = this._registeredMeshes.length;
  22875. var m;
  22876. while (i--) {
  22877. var body = this._registeredMeshes[i].body.body;
  22878. var mesh = this._registeredMeshes[i].mesh;
  22879. var delta = this._registeredMeshes[i].delta;
  22880. if (!body.sleeping) {
  22881. if (body.shapes.next) {
  22882. var parentShape = this._getLastShape(body);
  22883. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  22884. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  22885. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  22886. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  22887. if (!mesh.rotationQuaternion) {
  22888. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22889. }
  22890. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  22891. mesh.computeWorldMatrix();
  22892. }
  22893. else {
  22894. m = body.getMatrix();
  22895. mtx = BABYLON.Matrix.FromArray(m);
  22896. // Body position
  22897. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  22898. if (!delta) {
  22899. mesh.position.x = bodyX;
  22900. mesh.position.y = bodyY;
  22901. mesh.position.z = bodyZ;
  22902. }
  22903. else {
  22904. mesh.position.x = bodyX + delta.x;
  22905. mesh.position.y = bodyY + delta.y;
  22906. mesh.position.z = bodyZ + delta.z;
  22907. }
  22908. if (!mesh.rotationQuaternion) {
  22909. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22910. }
  22911. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  22912. mesh.computeWorldMatrix();
  22913. }
  22914. }
  22915. }
  22916. };
  22917. return OimoJSPlugin;
  22918. })();
  22919. BABYLON.OimoJSPlugin = OimoJSPlugin;
  22920. })(BABYLON || (BABYLON = {}));
  22921. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  22922. var BABYLON;
  22923. (function (BABYLON) {
  22924. var PhysicsEngine = (function () {
  22925. function PhysicsEngine(plugin) {
  22926. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  22927. }
  22928. PhysicsEngine.prototype._initialize = function (gravity) {
  22929. this._currentPlugin.initialize();
  22930. this._setGravity(gravity);
  22931. };
  22932. PhysicsEngine.prototype._runOneStep = function (delta) {
  22933. if (delta > 0.1) {
  22934. delta = 0.1;
  22935. }
  22936. else if (delta <= 0) {
  22937. delta = 1.0 / 60.0;
  22938. }
  22939. this._currentPlugin.runOneStep(delta);
  22940. };
  22941. PhysicsEngine.prototype._setGravity = function (gravity) {
  22942. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  22943. this._currentPlugin.setGravity(this.gravity);
  22944. };
  22945. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  22946. return this._currentPlugin.registerMesh(mesh, impostor, options);
  22947. };
  22948. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  22949. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  22950. };
  22951. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  22952. this._currentPlugin.unregisterMesh(mesh);
  22953. };
  22954. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  22955. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  22956. };
  22957. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22958. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  22959. };
  22960. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  22961. this._currentPlugin.updateBodyPosition(mesh);
  22962. };
  22963. PhysicsEngine.prototype.dispose = function () {
  22964. this._currentPlugin.dispose();
  22965. };
  22966. PhysicsEngine.prototype.isSupported = function () {
  22967. return this._currentPlugin.isSupported();
  22968. };
  22969. // Statics
  22970. PhysicsEngine.NoImpostor = 0;
  22971. PhysicsEngine.SphereImpostor = 1;
  22972. PhysicsEngine.BoxImpostor = 2;
  22973. PhysicsEngine.PlaneImpostor = 3;
  22974. PhysicsEngine.MeshImpostor = 4;
  22975. PhysicsEngine.CapsuleImpostor = 5;
  22976. PhysicsEngine.ConeImpostor = 6;
  22977. PhysicsEngine.CylinderImpostor = 7;
  22978. PhysicsEngine.ConvexHullImpostor = 8;
  22979. PhysicsEngine.Epsilon = 0.001;
  22980. return PhysicsEngine;
  22981. })();
  22982. BABYLON.PhysicsEngine = PhysicsEngine;
  22983. })(BABYLON || (BABYLON = {}));
  22984. //# sourceMappingURL=babylon.physicsEngine.js.map
  22985. var BABYLON;
  22986. (function (BABYLON) {
  22987. var serializeLight = function (light) {
  22988. var serializationObject = {};
  22989. serializationObject.name = light.name;
  22990. serializationObject.id = light.id;
  22991. serializationObject.tags = BABYLON.Tags.GetTags(light);
  22992. if (light instanceof BABYLON.PointLight) {
  22993. serializationObject.type = 0;
  22994. serializationObject.position = light.position.asArray();
  22995. }
  22996. else if (light instanceof BABYLON.DirectionalLight) {
  22997. serializationObject.type = 1;
  22998. var directionalLight = light;
  22999. serializationObject.position = directionalLight.position.asArray();
  23000. serializationObject.direction = directionalLight.direction.asArray();
  23001. }
  23002. else if (light instanceof BABYLON.SpotLight) {
  23003. serializationObject.type = 2;
  23004. var spotLight = light;
  23005. serializationObject.position = spotLight.position.asArray();
  23006. serializationObject.direction = spotLight.position.asArray();
  23007. serializationObject.angle = spotLight.angle;
  23008. serializationObject.exponent = spotLight.exponent;
  23009. }
  23010. else if (light instanceof BABYLON.HemisphericLight) {
  23011. serializationObject.type = 3;
  23012. var hemisphericLight = light;
  23013. serializationObject.direction = hemisphericLight.direction.asArray();
  23014. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  23015. }
  23016. if (light.intensity) {
  23017. serializationObject.intensity = light.intensity;
  23018. }
  23019. serializationObject.range = light.range;
  23020. serializationObject.diffuse = light.diffuse.asArray();
  23021. serializationObject.specular = light.specular.asArray();
  23022. return serializationObject;
  23023. };
  23024. var serializeFresnelParameter = function (fresnelParameter) {
  23025. var serializationObject = {};
  23026. serializationObject.isEnabled = fresnelParameter.isEnabled;
  23027. serializationObject.leftColor = fresnelParameter.leftColor;
  23028. serializationObject.rightColor = fresnelParameter.rightColor;
  23029. serializationObject.bias = fresnelParameter.bias;
  23030. serializationObject.power = fresnelParameter.power;
  23031. return serializationObject;
  23032. };
  23033. var appendAnimations = function (source, destination) {
  23034. if (source.animations) {
  23035. destination.animations = [];
  23036. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  23037. var animation = source.animations[animationIndex];
  23038. destination.animations.push(serializeAnimation(animation));
  23039. }
  23040. }
  23041. };
  23042. var serializeCamera = function (camera) {
  23043. var serializationObject = {};
  23044. serializationObject.name = camera.name;
  23045. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  23046. serializationObject.id = camera.id;
  23047. serializationObject.position = camera.position.asArray();
  23048. // Parent
  23049. if (camera.parent) {
  23050. serializationObject.parentId = camera.parent.id;
  23051. }
  23052. serializationObject.fov = camera.fov;
  23053. serializationObject.minZ = camera.minZ;
  23054. serializationObject.maxZ = camera.maxZ;
  23055. serializationObject.inertia = camera.inertia;
  23056. //setting the type
  23057. if (camera instanceof BABYLON.FreeCamera) {
  23058. serializationObject.type = "FreeCamera";
  23059. }
  23060. else if (camera instanceof BABYLON.ArcRotateCamera) {
  23061. serializationObject.type = "ArcRotateCamera";
  23062. }
  23063. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23064. serializationObject.type = "AnaglyphArcRotateCamera";
  23065. }
  23066. else if (camera instanceof BABYLON.GamepadCamera) {
  23067. serializationObject.type = "GamepadCamera";
  23068. }
  23069. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  23070. serializationObject.type = "AnaglyphFreeCamera";
  23071. }
  23072. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  23073. serializationObject.type = "DeviceOrientationCamera";
  23074. }
  23075. else if (camera instanceof BABYLON.FollowCamera) {
  23076. serializationObject.type = "FollowCamera";
  23077. }
  23078. else if (camera instanceof BABYLON.TouchCamera) {
  23079. serializationObject.type = "TouchCamera";
  23080. }
  23081. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  23082. serializationObject.type = "VirtualJoysticksCamera";
  23083. }
  23084. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  23085. serializationObject.type = "WebVRFreeCamera";
  23086. }
  23087. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  23088. serializationObject.type = "VRDeviceOrientationFreeCamera";
  23089. }
  23090. //special properties of specific cameras
  23091. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23092. var arcCamera = camera;
  23093. serializationObject.alpha = arcCamera.alpha;
  23094. serializationObject.beta = arcCamera.beta;
  23095. serializationObject.radius = arcCamera.radius;
  23096. if (arcCamera.target && arcCamera.target.id) {
  23097. serializationObject.lockedTargetId = arcCamera.target.id;
  23098. }
  23099. }
  23100. else if (camera instanceof BABYLON.FollowCamera) {
  23101. var followCam = camera;
  23102. serializationObject.radius = followCam.radius;
  23103. serializationObject.heightOffset = followCam.heightOffset;
  23104. serializationObject.rotationOffset = followCam.rotationOffset;
  23105. }
  23106. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23107. //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.
  23108. if (camera['_eyeSpace'] !== undefined) {
  23109. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  23110. }
  23111. }
  23112. //general properties that not all cameras have. The [] is due to typescript's type safety
  23113. if (camera['speed'] !== undefined) {
  23114. serializationObject.speed = camera['speed'];
  23115. }
  23116. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  23117. serializationObject.target = camera['target'].asArray();
  23118. }
  23119. // Target
  23120. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  23121. serializationObject.rotation = camera['rotation'].asArray();
  23122. }
  23123. // Locked target
  23124. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  23125. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  23126. }
  23127. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  23128. serializationObject.applyGravity = camera['applyGravity'] || false;
  23129. if (camera['ellipsoid']) {
  23130. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  23131. }
  23132. // Animations
  23133. appendAnimations(camera, serializationObject);
  23134. // Layer mask
  23135. serializationObject.layerMask = camera.layerMask;
  23136. return serializationObject;
  23137. };
  23138. var serializeAnimation = function (animation) {
  23139. var serializationObject = {};
  23140. serializationObject.name = animation.name;
  23141. serializationObject.property = animation.targetProperty;
  23142. serializationObject.framePerSecond = animation.framePerSecond;
  23143. serializationObject.dataType = animation.dataType;
  23144. serializationObject.loopBehavior = animation.loopMode;
  23145. var dataType = animation.dataType;
  23146. serializationObject.keys = [];
  23147. var keys = animation.getKeys();
  23148. for (var index = 0; index < keys.length; index++) {
  23149. var animationKey = keys[index];
  23150. var key = {};
  23151. key.frame = animationKey.frame;
  23152. switch (dataType) {
  23153. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  23154. key.values = [animationKey.value];
  23155. break;
  23156. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  23157. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  23158. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  23159. key.values = animationKey.value.asArray();
  23160. break;
  23161. }
  23162. serializationObject.keys.push(key);
  23163. }
  23164. return serializationObject;
  23165. };
  23166. var serializeMultiMaterial = function (material) {
  23167. var serializationObject = {};
  23168. serializationObject.name = material.name;
  23169. serializationObject.id = material.id;
  23170. serializationObject.tags = BABYLON.Tags.GetTags(material);
  23171. serializationObject.materials = [];
  23172. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  23173. var subMat = material.subMaterials[matIndex];
  23174. if (subMat) {
  23175. serializationObject.materials.push(subMat.id);
  23176. }
  23177. else {
  23178. serializationObject.materials.push(null);
  23179. }
  23180. }
  23181. return serializationObject;
  23182. };
  23183. var serializeMaterial = function (material) {
  23184. var serializationObject = {};
  23185. serializationObject.name = material.name;
  23186. serializationObject.ambient = material.ambientColor.asArray();
  23187. serializationObject.diffuse = material.diffuseColor.asArray();
  23188. serializationObject.specular = material.specularColor.asArray();
  23189. serializationObject.specularPower = material.specularPower;
  23190. serializationObject.emissive = material.emissiveColor.asArray();
  23191. serializationObject.alpha = material.alpha;
  23192. serializationObject.id = material.id;
  23193. serializationObject.tags = BABYLON.Tags.GetTags(material);
  23194. serializationObject.backFaceCulling = material.backFaceCulling;
  23195. if (material.diffuseTexture) {
  23196. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  23197. }
  23198. if (material.diffuseFresnelParameters) {
  23199. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  23200. }
  23201. if (material.ambientTexture) {
  23202. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  23203. }
  23204. if (material.opacityTexture) {
  23205. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  23206. }
  23207. if (material.opacityFresnelParameters) {
  23208. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  23209. }
  23210. if (material.reflectionTexture) {
  23211. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  23212. }
  23213. if (material.reflectionFresnelParameters) {
  23214. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  23215. }
  23216. if (material.emissiveTexture) {
  23217. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  23218. }
  23219. if (material.emissiveFresnelParameters) {
  23220. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  23221. }
  23222. if (material.specularTexture) {
  23223. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  23224. }
  23225. if (material.bumpTexture) {
  23226. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  23227. }
  23228. return serializationObject;
  23229. };
  23230. var serializeTexture = function (texture) {
  23231. var serializationObject = {};
  23232. if (!texture.name) {
  23233. return null;
  23234. }
  23235. if (texture instanceof BABYLON.CubeTexture) {
  23236. serializationObject.name = texture.name;
  23237. serializationObject.hasAlpha = texture.hasAlpha;
  23238. serializationObject.level = texture.level;
  23239. serializationObject.coordinatesMode = texture.coordinatesMode;
  23240. return serializationObject;
  23241. }
  23242. if (texture instanceof BABYLON.MirrorTexture) {
  23243. var mirrorTexture = texture;
  23244. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  23245. serializationObject.renderList = [];
  23246. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  23247. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  23248. }
  23249. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  23250. }
  23251. else if (texture instanceof BABYLON.RenderTargetTexture) {
  23252. var renderTargetTexture = texture;
  23253. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  23254. serializationObject.renderList = [];
  23255. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  23256. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  23257. }
  23258. }
  23259. var regularTexture = texture;
  23260. serializationObject.name = texture.name;
  23261. serializationObject.hasAlpha = texture.hasAlpha;
  23262. serializationObject.level = texture.level;
  23263. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  23264. serializationObject.coordinatesMode = texture.coordinatesMode;
  23265. serializationObject.uOffset = regularTexture.uOffset;
  23266. serializationObject.vOffset = regularTexture.vOffset;
  23267. serializationObject.uScale = regularTexture.uScale;
  23268. serializationObject.vScale = regularTexture.vScale;
  23269. serializationObject.uAng = regularTexture.uAng;
  23270. serializationObject.vAng = regularTexture.vAng;
  23271. serializationObject.wAng = regularTexture.wAng;
  23272. serializationObject.wrapU = texture.wrapU;
  23273. serializationObject.wrapV = texture.wrapV;
  23274. // Animations
  23275. appendAnimations(texture, serializationObject);
  23276. return serializationObject;
  23277. };
  23278. var serializeSkeleton = function (skeleton) {
  23279. var serializationObject = {};
  23280. serializationObject.name = skeleton.name;
  23281. serializationObject.id = skeleton.id;
  23282. serializationObject.bones = [];
  23283. for (var index = 0; index < skeleton.bones.length; index++) {
  23284. var bone = skeleton.bones[index];
  23285. var serializedBone = {
  23286. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  23287. name: bone.name,
  23288. matrix: bone.getLocalMatrix().toArray()
  23289. };
  23290. serializationObject.bones.push(serializedBone);
  23291. if (bone.animations && bone.animations.length > 0) {
  23292. serializedBone.animation = serializeAnimation(bone.animations[0]);
  23293. }
  23294. }
  23295. return serializationObject;
  23296. };
  23297. var serializeParticleSystem = function (particleSystem) {
  23298. var serializationObject = {};
  23299. serializationObject.emitterId = particleSystem.emitter.id;
  23300. serializationObject.capacity = particleSystem.getCapacity();
  23301. if (particleSystem.particleTexture) {
  23302. serializationObject.textureName = particleSystem.particleTexture.name;
  23303. }
  23304. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  23305. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  23306. serializationObject.minSize = particleSystem.minSize;
  23307. serializationObject.maxSize = particleSystem.maxSize;
  23308. serializationObject.minLifeTime = particleSystem.minLifeTime;
  23309. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  23310. serializationObject.emitRate = particleSystem.emitRate;
  23311. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  23312. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  23313. serializationObject.gravity = particleSystem.gravity.asArray();
  23314. serializationObject.direction1 = particleSystem.direction1.asArray();
  23315. serializationObject.direction2 = particleSystem.direction2.asArray();
  23316. serializationObject.color1 = particleSystem.color1.asArray();
  23317. serializationObject.color2 = particleSystem.color2.asArray();
  23318. serializationObject.colorDead = particleSystem.colorDead.asArray();
  23319. serializationObject.updateSpeed = particleSystem.updateSpeed;
  23320. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  23321. serializationObject.textureMask = particleSystem.textureMask.asArray();
  23322. serializationObject.blendMode = particleSystem.blendMode;
  23323. return serializationObject;
  23324. };
  23325. var serializeLensFlareSystem = function (lensFlareSystem) {
  23326. var serializationObject = {};
  23327. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  23328. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  23329. serializationObject.flares = [];
  23330. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  23331. var flare = lensFlareSystem.lensFlares[index];
  23332. serializationObject.flares.push({
  23333. size: flare.size,
  23334. position: flare.position,
  23335. color: flare.color.asArray(),
  23336. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  23337. });
  23338. }
  23339. return serializationObject;
  23340. };
  23341. var serializeShadowGenerator = function (light) {
  23342. var serializationObject = {};
  23343. var shadowGenerator = light.getShadowGenerator();
  23344. serializationObject.lightId = light.id;
  23345. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  23346. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  23347. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  23348. serializationObject.renderList = [];
  23349. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  23350. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  23351. serializationObject.renderList.push(mesh.id);
  23352. }
  23353. return serializationObject;
  23354. };
  23355. var serializedGeometries = [];
  23356. var serializeGeometry = function (geometry, serializationGeometries) {
  23357. if (serializedGeometries[geometry.id]) {
  23358. return;
  23359. }
  23360. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  23361. serializationGeometries.boxes.push(serializeBox(geometry));
  23362. }
  23363. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  23364. serializationGeometries.spheres.push(serializeSphere(geometry));
  23365. }
  23366. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  23367. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  23368. }
  23369. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  23370. serializationGeometries.toruses.push(serializeTorus(geometry));
  23371. }
  23372. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  23373. serializationGeometries.grounds.push(serializeGround(geometry));
  23374. }
  23375. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  23376. serializationGeometries.planes.push(serializePlane(geometry));
  23377. }
  23378. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  23379. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  23380. }
  23381. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  23382. throw new Error("Unknow primitive type");
  23383. }
  23384. else {
  23385. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  23386. }
  23387. serializedGeometries[geometry.id] = true;
  23388. };
  23389. var serializeGeometryBase = function (geometry) {
  23390. var serializationObject = {};
  23391. serializationObject.id = geometry.id;
  23392. if (BABYLON.Tags.HasTags(geometry)) {
  23393. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  23394. }
  23395. return serializationObject;
  23396. };
  23397. var serializeVertexData = function (vertexData) {
  23398. var serializationObject = serializeGeometryBase(vertexData);
  23399. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23400. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23401. }
  23402. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23403. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23404. }
  23405. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23406. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  23407. }
  23408. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23409. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  23410. }
  23411. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23412. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  23413. }
  23414. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23415. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23416. serializationObject.matricesIndices._isExpanded = true;
  23417. }
  23418. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23419. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23420. }
  23421. serializationObject.indices = vertexData.getIndices();
  23422. return serializationObject;
  23423. };
  23424. var serializePrimitive = function (primitive) {
  23425. var serializationObject = serializeGeometryBase(primitive);
  23426. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  23427. return serializationObject;
  23428. };
  23429. var serializeBox = function (box) {
  23430. var serializationObject = serializePrimitive(box);
  23431. serializationObject.size = box.size;
  23432. return serializationObject;
  23433. };
  23434. var serializeSphere = function (sphere) {
  23435. var serializationObject = serializePrimitive(sphere);
  23436. serializationObject.segments = sphere.segments;
  23437. serializationObject.diameter = sphere.diameter;
  23438. return serializationObject;
  23439. };
  23440. var serializeCylinder = function (cylinder) {
  23441. var serializationObject = serializePrimitive(cylinder);
  23442. serializationObject.height = cylinder.height;
  23443. serializationObject.diameterTop = cylinder.diameterTop;
  23444. serializationObject.diameterBottom = cylinder.diameterBottom;
  23445. serializationObject.tessellation = cylinder.tessellation;
  23446. return serializationObject;
  23447. };
  23448. var serializeTorus = function (torus) {
  23449. var serializationObject = serializePrimitive(torus);
  23450. serializationObject.diameter = torus.diameter;
  23451. serializationObject.thickness = torus.thickness;
  23452. serializationObject.tessellation = torus.tessellation;
  23453. return serializationObject;
  23454. };
  23455. var serializeGround = function (ground) {
  23456. var serializationObject = serializePrimitive(ground);
  23457. serializationObject.width = ground.width;
  23458. serializationObject.height = ground.height;
  23459. serializationObject.subdivisions = ground.subdivisions;
  23460. return serializationObject;
  23461. };
  23462. var serializePlane = function (plane) {
  23463. var serializationObject = serializePrimitive(plane);
  23464. serializationObject.size = plane.size;
  23465. return serializationObject;
  23466. };
  23467. var serializeTorusKnot = function (torusKnot) {
  23468. var serializationObject = serializePrimitive(torusKnot);
  23469. serializationObject.radius = torusKnot.radius;
  23470. serializationObject.tube = torusKnot.tube;
  23471. serializationObject.radialSegments = torusKnot.radialSegments;
  23472. serializationObject.tubularSegments = torusKnot.tubularSegments;
  23473. serializationObject.p = torusKnot.p;
  23474. serializationObject.q = torusKnot.q;
  23475. return serializationObject;
  23476. };
  23477. var serializeMesh = function (mesh, serializationScene) {
  23478. var serializationObject = {};
  23479. serializationObject.name = mesh.name;
  23480. serializationObject.id = mesh.id;
  23481. if (BABYLON.Tags.HasTags(mesh)) {
  23482. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  23483. }
  23484. serializationObject.position = mesh.position.asArray();
  23485. if (mesh.rotationQuaternion) {
  23486. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  23487. }
  23488. else if (mesh.rotation) {
  23489. serializationObject.rotation = mesh.rotation.asArray();
  23490. }
  23491. serializationObject.scaling = mesh.scaling.asArray();
  23492. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  23493. serializationObject.isEnabled = mesh.isEnabled();
  23494. serializationObject.isVisible = mesh.isVisible;
  23495. serializationObject.infiniteDistance = mesh.infiniteDistance;
  23496. serializationObject.pickable = mesh.isPickable;
  23497. serializationObject.receiveShadows = mesh.receiveShadows;
  23498. serializationObject.billboardMode = mesh.billboardMode;
  23499. serializationObject.visibility = mesh.visibility;
  23500. serializationObject.checkCollisions = mesh.checkCollisions;
  23501. // Parent
  23502. if (mesh.parent) {
  23503. serializationObject.parentId = mesh.parent.id;
  23504. }
  23505. // Geometry
  23506. var geometry = mesh._geometry;
  23507. if (geometry) {
  23508. var geometryId = geometry.id;
  23509. serializationObject.geometryId = geometryId;
  23510. if (!mesh.getScene().getGeometryByID(geometryId)) {
  23511. // 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
  23512. serializeGeometry(geometry, serializationScene.geometries);
  23513. }
  23514. // SubMeshes
  23515. serializationObject.subMeshes = [];
  23516. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  23517. var subMesh = mesh.subMeshes[subIndex];
  23518. serializationObject.subMeshes.push({
  23519. materialIndex: subMesh.materialIndex,
  23520. verticesStart: subMesh.verticesStart,
  23521. verticesCount: subMesh.verticesCount,
  23522. indexStart: subMesh.indexStart,
  23523. indexCount: subMesh.indexCount
  23524. });
  23525. }
  23526. }
  23527. // Material
  23528. if (mesh.material) {
  23529. serializationObject.materialId = mesh.material.id;
  23530. }
  23531. else {
  23532. mesh.material = null;
  23533. }
  23534. // Skeleton
  23535. if (mesh.skeleton) {
  23536. serializationObject.skeletonId = mesh.skeleton.id;
  23537. }
  23538. // Physics
  23539. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  23540. serializationObject.physicsMass = mesh.getPhysicsMass();
  23541. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  23542. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  23543. switch (mesh.getPhysicsImpostor()) {
  23544. case BABYLON.PhysicsEngine.BoxImpostor:
  23545. serializationObject.physicsImpostor = 1;
  23546. break;
  23547. case BABYLON.PhysicsEngine.SphereImpostor:
  23548. serializationObject.physicsImpostor = 2;
  23549. break;
  23550. }
  23551. }
  23552. // Instances
  23553. serializationObject.instances = [];
  23554. for (var index = 0; index < mesh.instances.length; index++) {
  23555. var instance = mesh.instances[index];
  23556. var serializationInstance = {
  23557. name: instance.name,
  23558. position: instance.position,
  23559. rotation: instance.rotation,
  23560. rotationQuaternion: instance.rotationQuaternion,
  23561. scaling: instance.scaling
  23562. };
  23563. serializationObject.instances.push(serializationInstance);
  23564. // Animations
  23565. appendAnimations(instance, serializationInstance);
  23566. }
  23567. // Animations
  23568. appendAnimations(mesh, serializationObject);
  23569. // Layer mask
  23570. serializationObject.layerMask = mesh.layerMask;
  23571. return serializationObject;
  23572. };
  23573. var SceneSerializer = (function () {
  23574. function SceneSerializer() {
  23575. }
  23576. SceneSerializer.Serialize = function (scene) {
  23577. var serializationObject = {};
  23578. // Scene
  23579. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  23580. serializationObject.autoClear = scene.autoClear;
  23581. serializationObject.clearColor = scene.clearColor.asArray();
  23582. serializationObject.ambientColor = scene.ambientColor.asArray();
  23583. serializationObject.gravity = scene.gravity.asArray();
  23584. // Fog
  23585. if (scene.fogMode && scene.fogMode !== 0) {
  23586. serializationObject.fogMode = scene.fogMode;
  23587. serializationObject.fogColor = scene.fogColor.asArray();
  23588. serializationObject.fogStart = scene.fogStart;
  23589. serializationObject.fogEnd = scene.fogEnd;
  23590. serializationObject.fogDensity = scene.fogDensity;
  23591. }
  23592. // Lights
  23593. serializationObject.lights = [];
  23594. for (var index = 0; index < scene.lights.length; index++) {
  23595. var light = scene.lights[index];
  23596. serializationObject.lights.push(serializeLight(light));
  23597. }
  23598. // Cameras
  23599. serializationObject.cameras = [];
  23600. for (index = 0; index < scene.cameras.length; index++) {
  23601. var camera = scene.cameras[index];
  23602. serializationObject.cameras.push(serializeCamera(camera));
  23603. }
  23604. if (scene.activeCamera) {
  23605. serializationObject.activeCameraID = scene.activeCamera.id;
  23606. }
  23607. // Materials
  23608. serializationObject.materials = [];
  23609. serializationObject.multiMaterials = [];
  23610. for (index = 0; index < scene.materials.length; index++) {
  23611. var material = scene.materials[index];
  23612. if (material instanceof BABYLON.StandardMaterial) {
  23613. serializationObject.materials.push(serializeMaterial(material));
  23614. }
  23615. else if (material instanceof BABYLON.MultiMaterial) {
  23616. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  23617. }
  23618. }
  23619. // Skeletons
  23620. serializationObject.skeletons = [];
  23621. for (index = 0; index < scene.skeletons.length; index++) {
  23622. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  23623. }
  23624. // Geometries
  23625. serializationObject.geometries = {};
  23626. serializationObject.geometries.boxes = [];
  23627. serializationObject.geometries.spheres = [];
  23628. serializationObject.geometries.cylinders = [];
  23629. serializationObject.geometries.toruses = [];
  23630. serializationObject.geometries.grounds = [];
  23631. serializationObject.geometries.planes = [];
  23632. serializationObject.geometries.torusKnots = [];
  23633. serializationObject.geometries.vertexData = [];
  23634. serializedGeometries = [];
  23635. var geometries = scene.getGeometries();
  23636. for (index = 0; index < geometries.length; index++) {
  23637. var geometry = geometries[index];
  23638. if (geometry.isReady()) {
  23639. serializeGeometry(geometry, serializationObject.geometries);
  23640. }
  23641. }
  23642. // Meshes
  23643. serializationObject.meshes = [];
  23644. for (index = 0; index < scene.meshes.length; index++) {
  23645. var abstractMesh = scene.meshes[index];
  23646. if (abstractMesh instanceof BABYLON.Mesh) {
  23647. var mesh = abstractMesh;
  23648. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  23649. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  23650. }
  23651. }
  23652. }
  23653. // Particles Systems
  23654. serializationObject.particleSystems = [];
  23655. for (index = 0; index < scene.particleSystems.length; index++) {
  23656. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  23657. }
  23658. // Lens flares
  23659. serializationObject.lensFlareSystems = [];
  23660. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  23661. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  23662. }
  23663. // Shadows
  23664. serializationObject.shadowGenerators = [];
  23665. for (index = 0; index < scene.lights.length; index++) {
  23666. light = scene.lights[index];
  23667. if (light.getShadowGenerator()) {
  23668. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  23669. }
  23670. }
  23671. return serializationObject;
  23672. };
  23673. return SceneSerializer;
  23674. })();
  23675. BABYLON.SceneSerializer = SceneSerializer;
  23676. })(BABYLON || (BABYLON = {}));
  23677. //# sourceMappingURL=babylon.sceneSerializer.js.map
  23678. var BABYLON;
  23679. (function (BABYLON) {
  23680. // Unique ID when we import meshes from Babylon to CSG
  23681. var currentCSGMeshId = 0;
  23682. // # class Vertex
  23683. // Represents a vertex of a polygon. Use your own vertex class instead of this
  23684. // one to provide additional features like texture coordinates and vertex
  23685. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  23686. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  23687. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  23688. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  23689. // is not used anywhere else.
  23690. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  23691. var Vertex = (function () {
  23692. function Vertex(pos, normal, uv) {
  23693. this.pos = pos;
  23694. this.normal = normal;
  23695. this.uv = uv;
  23696. }
  23697. Vertex.prototype.clone = function () {
  23698. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  23699. };
  23700. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  23701. // orientation of a polygon is flipped.
  23702. Vertex.prototype.flip = function () {
  23703. this.normal = this.normal.scale(-1);
  23704. };
  23705. // Create a new vertex between this vertex and `other` by linearly
  23706. // interpolating all properties using a parameter of `t`. Subclasses should
  23707. // override this to interpolate additional properties.
  23708. Vertex.prototype.interpolate = function (other, t) {
  23709. 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));
  23710. };
  23711. return Vertex;
  23712. })();
  23713. // # class Plane
  23714. // Represents a plane in 3D space.
  23715. var Plane = (function () {
  23716. function Plane(normal, w) {
  23717. this.normal = normal;
  23718. this.w = w;
  23719. }
  23720. Plane.FromPoints = function (a, b, c) {
  23721. var v0 = c.subtract(a);
  23722. var v1 = b.subtract(a);
  23723. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  23724. return null;
  23725. }
  23726. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  23727. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  23728. };
  23729. Plane.prototype.clone = function () {
  23730. return new Plane(this.normal.clone(), this.w);
  23731. };
  23732. Plane.prototype.flip = function () {
  23733. this.normal.scaleInPlace(-1);
  23734. this.w = -this.w;
  23735. };
  23736. // Split `polygon` by this plane if needed, then put the polygon or polygon
  23737. // fragments in the appropriate lists. Coplanar polygons go into either
  23738. // `coplanarFront` or `coplanarBack` depending on their orientation with
  23739. // respect to this plane. Polygons in front or in back of this plane go into
  23740. // either `front` or `back`.
  23741. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  23742. var COPLANAR = 0;
  23743. var FRONT = 1;
  23744. var BACK = 2;
  23745. var SPANNING = 3;
  23746. // Classify each point as well as the entire polygon into one of the above
  23747. // four classes.
  23748. var polygonType = 0;
  23749. var types = [];
  23750. for (var i = 0; i < polygon.vertices.length; i++) {
  23751. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  23752. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  23753. polygonType |= type;
  23754. types.push(type);
  23755. }
  23756. // Put the polygon in the correct list, splitting it when necessary.
  23757. switch (polygonType) {
  23758. case COPLANAR:
  23759. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  23760. break;
  23761. case FRONT:
  23762. front.push(polygon);
  23763. break;
  23764. case BACK:
  23765. back.push(polygon);
  23766. break;
  23767. case SPANNING:
  23768. var f = [], b = [];
  23769. for (i = 0; i < polygon.vertices.length; i++) {
  23770. var j = (i + 1) % polygon.vertices.length;
  23771. var ti = types[i], tj = types[j];
  23772. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  23773. if (ti != BACK)
  23774. f.push(vi);
  23775. if (ti != FRONT)
  23776. b.push(ti != BACK ? vi.clone() : vi);
  23777. if ((ti | tj) == SPANNING) {
  23778. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  23779. var v = vi.interpolate(vj, t);
  23780. f.push(v);
  23781. b.push(v.clone());
  23782. }
  23783. }
  23784. if (f.length >= 3) {
  23785. var poly = new Polygon(f, polygon.shared);
  23786. if (poly.plane)
  23787. front.push(poly);
  23788. }
  23789. if (b.length >= 3) {
  23790. poly = new Polygon(b, polygon.shared);
  23791. if (poly.plane)
  23792. back.push(poly);
  23793. }
  23794. break;
  23795. }
  23796. };
  23797. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  23798. // point is on the plane.
  23799. Plane.EPSILON = 1e-5;
  23800. return Plane;
  23801. })();
  23802. // # class Polygon
  23803. // Represents a convex polygon. The vertices used to initialize a polygon must
  23804. // be coplanar and form a convex loop.
  23805. //
  23806. // Each convex polygon has a `shared` property, which is shared between all
  23807. // polygons that are clones of each other or were split from the same polygon.
  23808. // This can be used to define per-polygon properties (such as surface color).
  23809. var Polygon = (function () {
  23810. function Polygon(vertices, shared) {
  23811. this.vertices = vertices;
  23812. this.shared = shared;
  23813. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  23814. }
  23815. Polygon.prototype.clone = function () {
  23816. var vertices = this.vertices.map(function (v) { return v.clone(); });
  23817. return new Polygon(vertices, this.shared);
  23818. };
  23819. Polygon.prototype.flip = function () {
  23820. this.vertices.reverse().map(function (v) { v.flip(); });
  23821. this.plane.flip();
  23822. };
  23823. return Polygon;
  23824. })();
  23825. // # class Node
  23826. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  23827. // by picking a polygon to split along. That polygon (and all other coplanar
  23828. // polygons) are added directly to that node and the other polygons are added to
  23829. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  23830. // no distinction between internal and leaf nodes.
  23831. var Node = (function () {
  23832. function Node(polygons) {
  23833. this.plane = null;
  23834. this.front = null;
  23835. this.back = null;
  23836. this.polygons = [];
  23837. if (polygons) {
  23838. this.build(polygons);
  23839. }
  23840. }
  23841. Node.prototype.clone = function () {
  23842. var node = new Node();
  23843. node.plane = this.plane && this.plane.clone();
  23844. node.front = this.front && this.front.clone();
  23845. node.back = this.back && this.back.clone();
  23846. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  23847. return node;
  23848. };
  23849. // Convert solid space to empty space and empty space to solid space.
  23850. Node.prototype.invert = function () {
  23851. for (var i = 0; i < this.polygons.length; i++) {
  23852. this.polygons[i].flip();
  23853. }
  23854. if (this.plane) {
  23855. this.plane.flip();
  23856. }
  23857. if (this.front) {
  23858. this.front.invert();
  23859. }
  23860. if (this.back) {
  23861. this.back.invert();
  23862. }
  23863. var temp = this.front;
  23864. this.front = this.back;
  23865. this.back = temp;
  23866. };
  23867. // Recursively remove all polygons in `polygons` that are inside this BSP
  23868. // tree.
  23869. Node.prototype.clipPolygons = function (polygons) {
  23870. if (!this.plane)
  23871. return polygons.slice();
  23872. var front = [], back = [];
  23873. for (var i = 0; i < polygons.length; i++) {
  23874. this.plane.splitPolygon(polygons[i], front, back, front, back);
  23875. }
  23876. if (this.front) {
  23877. front = this.front.clipPolygons(front);
  23878. }
  23879. if (this.back) {
  23880. back = this.back.clipPolygons(back);
  23881. }
  23882. else {
  23883. back = [];
  23884. }
  23885. return front.concat(back);
  23886. };
  23887. // Remove all polygons in this BSP tree that are inside the other BSP tree
  23888. // `bsp`.
  23889. Node.prototype.clipTo = function (bsp) {
  23890. this.polygons = bsp.clipPolygons(this.polygons);
  23891. if (this.front)
  23892. this.front.clipTo(bsp);
  23893. if (this.back)
  23894. this.back.clipTo(bsp);
  23895. };
  23896. // Return a list of all polygons in this BSP tree.
  23897. Node.prototype.allPolygons = function () {
  23898. var polygons = this.polygons.slice();
  23899. if (this.front)
  23900. polygons = polygons.concat(this.front.allPolygons());
  23901. if (this.back)
  23902. polygons = polygons.concat(this.back.allPolygons());
  23903. return polygons;
  23904. };
  23905. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  23906. // new polygons are filtered down to the bottom of the tree and become new
  23907. // nodes there. Each set of polygons is partitioned using the first polygon
  23908. // (no heuristic is used to pick a good split).
  23909. Node.prototype.build = function (polygons) {
  23910. if (!polygons.length)
  23911. return;
  23912. if (!this.plane)
  23913. this.plane = polygons[0].plane.clone();
  23914. var front = [], back = [];
  23915. for (var i = 0; i < polygons.length; i++) {
  23916. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  23917. }
  23918. if (front.length) {
  23919. if (!this.front)
  23920. this.front = new Node();
  23921. this.front.build(front);
  23922. }
  23923. if (back.length) {
  23924. if (!this.back)
  23925. this.back = new Node();
  23926. this.back.build(back);
  23927. }
  23928. };
  23929. return Node;
  23930. })();
  23931. var CSG = (function () {
  23932. function CSG() {
  23933. this.polygons = new Array();
  23934. }
  23935. // Convert BABYLON.Mesh to BABYLON.CSG
  23936. CSG.FromMesh = function (mesh) {
  23937. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  23938. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  23939. if (mesh instanceof BABYLON.Mesh) {
  23940. mesh.computeWorldMatrix(true);
  23941. matrix = mesh.getWorldMatrix();
  23942. meshPosition = mesh.position.clone();
  23943. meshRotation = mesh.rotation.clone();
  23944. if (mesh.rotationQuaternion) {
  23945. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  23946. }
  23947. meshScaling = mesh.scaling.clone();
  23948. }
  23949. else {
  23950. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  23951. }
  23952. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  23953. var subMeshes = mesh.subMeshes;
  23954. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  23955. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  23956. vertices = [];
  23957. for (var j = 0; j < 3; j++) {
  23958. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  23959. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  23960. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  23961. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  23962. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  23963. vertex = new Vertex(position, normal, uv);
  23964. vertices.push(vertex);
  23965. }
  23966. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  23967. // To handle the case of degenerated triangle
  23968. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  23969. if (polygon.plane)
  23970. polygons.push(polygon);
  23971. }
  23972. }
  23973. var csg = CSG.FromPolygons(polygons);
  23974. csg.matrix = matrix;
  23975. csg.position = meshPosition;
  23976. csg.rotation = meshRotation;
  23977. csg.scaling = meshScaling;
  23978. csg.rotationQuaternion = meshRotationQuaternion;
  23979. currentCSGMeshId++;
  23980. return csg;
  23981. };
  23982. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  23983. CSG.FromPolygons = function (polygons) {
  23984. var csg = new CSG();
  23985. csg.polygons = polygons;
  23986. return csg;
  23987. };
  23988. CSG.prototype.clone = function () {
  23989. var csg = new CSG();
  23990. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  23991. csg.copyTransformAttributes(this);
  23992. return csg;
  23993. };
  23994. CSG.prototype.toPolygons = function () {
  23995. return this.polygons;
  23996. };
  23997. CSG.prototype.union = function (csg) {
  23998. var a = new Node(this.clone().polygons);
  23999. var b = new Node(csg.clone().polygons);
  24000. a.clipTo(b);
  24001. b.clipTo(a);
  24002. b.invert();
  24003. b.clipTo(a);
  24004. b.invert();
  24005. a.build(b.allPolygons());
  24006. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  24007. };
  24008. CSG.prototype.unionInPlace = function (csg) {
  24009. var a = new Node(this.polygons);
  24010. var b = new Node(csg.polygons);
  24011. a.clipTo(b);
  24012. b.clipTo(a);
  24013. b.invert();
  24014. b.clipTo(a);
  24015. b.invert();
  24016. a.build(b.allPolygons());
  24017. this.polygons = a.allPolygons();
  24018. };
  24019. CSG.prototype.subtract = function (csg) {
  24020. var a = new Node(this.clone().polygons);
  24021. var b = new Node(csg.clone().polygons);
  24022. a.invert();
  24023. a.clipTo(b);
  24024. b.clipTo(a);
  24025. b.invert();
  24026. b.clipTo(a);
  24027. b.invert();
  24028. a.build(b.allPolygons());
  24029. a.invert();
  24030. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  24031. };
  24032. CSG.prototype.subtractInPlace = function (csg) {
  24033. var a = new Node(this.polygons);
  24034. var b = new Node(csg.polygons);
  24035. a.invert();
  24036. a.clipTo(b);
  24037. b.clipTo(a);
  24038. b.invert();
  24039. b.clipTo(a);
  24040. b.invert();
  24041. a.build(b.allPolygons());
  24042. a.invert();
  24043. this.polygons = a.allPolygons();
  24044. };
  24045. CSG.prototype.intersect = function (csg) {
  24046. var a = new Node(this.clone().polygons);
  24047. var b = new Node(csg.clone().polygons);
  24048. a.invert();
  24049. b.clipTo(a);
  24050. b.invert();
  24051. a.clipTo(b);
  24052. b.clipTo(a);
  24053. a.build(b.allPolygons());
  24054. a.invert();
  24055. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  24056. };
  24057. CSG.prototype.intersectInPlace = function (csg) {
  24058. var a = new Node(this.polygons);
  24059. var b = new Node(csg.polygons);
  24060. a.invert();
  24061. b.clipTo(a);
  24062. b.invert();
  24063. a.clipTo(b);
  24064. b.clipTo(a);
  24065. a.build(b.allPolygons());
  24066. a.invert();
  24067. this.polygons = a.allPolygons();
  24068. };
  24069. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  24070. // not modified.
  24071. CSG.prototype.inverse = function () {
  24072. var csg = this.clone();
  24073. csg.inverseInPlace();
  24074. return csg;
  24075. };
  24076. CSG.prototype.inverseInPlace = function () {
  24077. this.polygons.map(function (p) { p.flip(); });
  24078. };
  24079. // This is used to keep meshes transformations so they can be restored
  24080. // when we build back a Babylon Mesh
  24081. // NB : All CSG operations are performed in world coordinates
  24082. CSG.prototype.copyTransformAttributes = function (csg) {
  24083. this.matrix = csg.matrix;
  24084. this.position = csg.position;
  24085. this.rotation = csg.rotation;
  24086. this.scaling = csg.scaling;
  24087. this.rotationQuaternion = csg.rotationQuaternion;
  24088. return this;
  24089. };
  24090. // Build Raw mesh from CSG
  24091. // Coordinates here are in world space
  24092. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  24093. var matrix = this.matrix.clone();
  24094. matrix.invert();
  24095. 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;
  24096. if (keepSubMeshes) {
  24097. // Sort Polygons, since subMeshes are indices range
  24098. polygons.sort(function (a, b) {
  24099. if (a.shared.meshId === b.shared.meshId) {
  24100. return a.shared.subMeshId - b.shared.subMeshId;
  24101. }
  24102. else {
  24103. return a.shared.meshId - b.shared.meshId;
  24104. }
  24105. });
  24106. }
  24107. for (var i = 0, il = polygons.length; i < il; i++) {
  24108. polygon = polygons[i];
  24109. // Building SubMeshes
  24110. if (!subMesh_dict[polygon.shared.meshId]) {
  24111. subMesh_dict[polygon.shared.meshId] = {};
  24112. }
  24113. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  24114. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  24115. indexStart: +Infinity,
  24116. indexEnd: -Infinity,
  24117. materialIndex: polygon.shared.materialIndex
  24118. };
  24119. }
  24120. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  24121. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  24122. polygonIndices[0] = 0;
  24123. polygonIndices[1] = j - 1;
  24124. polygonIndices[2] = j;
  24125. for (var k = 0; k < 3; k++) {
  24126. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  24127. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  24128. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  24129. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  24130. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  24131. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  24132. // Check if 2 points can be merged
  24133. if (!(typeof vertex_idx !== 'undefined' &&
  24134. normals[vertex_idx * 3] === localNormal.x &&
  24135. normals[vertex_idx * 3 + 1] === localNormal.y &&
  24136. normals[vertex_idx * 3 + 2] === localNormal.z &&
  24137. uvs[vertex_idx * 2] === uv.x &&
  24138. uvs[vertex_idx * 2 + 1] === uv.y)) {
  24139. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  24140. uvs.push(uv.x, uv.y);
  24141. normals.push(normal.x, normal.y, normal.z);
  24142. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  24143. }
  24144. indices.push(vertex_idx);
  24145. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  24146. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  24147. currentIndex++;
  24148. }
  24149. }
  24150. }
  24151. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  24152. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  24153. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  24154. mesh.setIndices(indices);
  24155. if (keepSubMeshes) {
  24156. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  24157. var materialIndexOffset = 0, materialMaxIndex;
  24158. mesh.subMeshes.length = 0;
  24159. for (var m in subMesh_dict) {
  24160. materialMaxIndex = -1;
  24161. for (var sm in subMesh_dict[m]) {
  24162. subMesh_obj = subMesh_dict[m][sm];
  24163. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  24164. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  24165. }
  24166. materialIndexOffset += ++materialMaxIndex;
  24167. }
  24168. }
  24169. return mesh;
  24170. };
  24171. // Build Mesh from CSG taking material and transforms into account
  24172. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  24173. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  24174. mesh.material = material;
  24175. mesh.position.copyFrom(this.position);
  24176. mesh.rotation.copyFrom(this.rotation);
  24177. if (this.rotationQuaternion) {
  24178. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  24179. }
  24180. mesh.scaling.copyFrom(this.scaling);
  24181. mesh.computeWorldMatrix(true);
  24182. return mesh;
  24183. };
  24184. return CSG;
  24185. })();
  24186. BABYLON.CSG = CSG;
  24187. })(BABYLON || (BABYLON = {}));
  24188. //# sourceMappingURL=babylon.csg.js.map
  24189. var BABYLON;
  24190. (function (BABYLON) {
  24191. var VRDistortionCorrectionPostProcess = (function (_super) {
  24192. __extends(VRDistortionCorrectionPostProcess, _super);
  24193. //ANY
  24194. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  24195. var _this = this;
  24196. _super.call(this, name, "vrDistortionCorrection", [
  24197. 'LensCenter',
  24198. 'Scale',
  24199. 'ScaleIn',
  24200. 'HmdWarpParam'
  24201. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  24202. this._isRightEye = isRightEye;
  24203. this._distortionFactors = vrMetrics.distortionK;
  24204. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  24205. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  24206. this.onSizeChanged = function () {
  24207. _this.aspectRatio = _this.width * .5 / _this.height;
  24208. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  24209. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  24210. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  24211. };
  24212. this.onApply = function (effect) {
  24213. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  24214. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  24215. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  24216. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  24217. };
  24218. }
  24219. return VRDistortionCorrectionPostProcess;
  24220. })(BABYLON.PostProcess);
  24221. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  24222. })(BABYLON || (BABYLON = {}));
  24223. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  24224. // Mainly based on these 2 articles :
  24225. // 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
  24226. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  24227. var BABYLON;
  24228. (function (BABYLON) {
  24229. (function (JoystickAxis) {
  24230. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  24231. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  24232. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  24233. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  24234. var JoystickAxis = BABYLON.JoystickAxis;
  24235. var VirtualJoystick = (function () {
  24236. function VirtualJoystick(leftJoystick) {
  24237. var _this = this;
  24238. if (leftJoystick) {
  24239. this._leftJoystick = true;
  24240. }
  24241. else {
  24242. this._leftJoystick = false;
  24243. }
  24244. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  24245. VirtualJoystick._globalJoystickIndex++;
  24246. // By default left & right arrow keys are moving the X
  24247. // and up & down keys are moving the Y
  24248. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  24249. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  24250. this.reverseLeftRight = false;
  24251. this.reverseUpDown = false;
  24252. // collections of pointers
  24253. this._touches = new BABYLON.SmartCollection();
  24254. this.deltaPosition = BABYLON.Vector3.Zero();
  24255. this._joystickSensibility = 25;
  24256. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  24257. this._rotationSpeed = 25;
  24258. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  24259. this._rotateOnAxisRelativeToMesh = false;
  24260. // injecting a canvas element on top of the canvas 3D game
  24261. if (!VirtualJoystick.vjCanvas) {
  24262. window.addEventListener("resize", function () {
  24263. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  24264. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  24265. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  24266. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  24267. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  24268. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  24269. }, false);
  24270. VirtualJoystick.vjCanvas = document.createElement("canvas");
  24271. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  24272. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  24273. VirtualJoystick.vjCanvas.width = window.innerWidth;
  24274. VirtualJoystick.vjCanvas.height = window.innerHeight;
  24275. VirtualJoystick.vjCanvas.style.width = "100%";
  24276. VirtualJoystick.vjCanvas.style.height = "100%";
  24277. VirtualJoystick.vjCanvas.style.position = "absolute";
  24278. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  24279. VirtualJoystick.vjCanvas.style.top = "0px";
  24280. VirtualJoystick.vjCanvas.style.left = "0px";
  24281. VirtualJoystick.vjCanvas.style.zIndex = "5";
  24282. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  24283. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  24284. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  24285. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  24286. document.body.appendChild(VirtualJoystick.vjCanvas);
  24287. }
  24288. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  24289. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  24290. this.pressed = false;
  24291. // default joystick color
  24292. this._joystickColor = "cyan";
  24293. this._joystickPointerID = -1;
  24294. // current joystick position
  24295. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  24296. // origin joystick position
  24297. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  24298. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  24299. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  24300. _this._onPointerDown(evt);
  24301. }, false);
  24302. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  24303. _this._onPointerMove(evt);
  24304. }, false);
  24305. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  24306. _this._onPointerUp(evt);
  24307. }, false);
  24308. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  24309. _this._onPointerUp(evt);
  24310. }, false);
  24311. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  24312. evt.preventDefault(); // Disables system menu
  24313. }, false);
  24314. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  24315. }
  24316. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  24317. this._joystickSensibility = newJoystickSensibility;
  24318. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  24319. };
  24320. VirtualJoystick.prototype._onPointerDown = function (e) {
  24321. var positionOnScreenCondition;
  24322. e.preventDefault();
  24323. if (this._leftJoystick === true) {
  24324. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  24325. }
  24326. else {
  24327. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  24328. }
  24329. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  24330. // First contact will be dedicated to the virtual joystick
  24331. this._joystickPointerID = e.pointerId;
  24332. this._joystickPointerStartPos.x = e.clientX;
  24333. this._joystickPointerStartPos.y = e.clientY;
  24334. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  24335. this._deltaJoystickVector.x = 0;
  24336. this._deltaJoystickVector.y = 0;
  24337. this.pressed = true;
  24338. this._touches.add(e.pointerId.toString(), e);
  24339. }
  24340. else {
  24341. // You can only trigger the action buttons with a joystick declared
  24342. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  24343. this._action();
  24344. this._touches.add(e.pointerId.toString(), e);
  24345. }
  24346. }
  24347. };
  24348. VirtualJoystick.prototype._onPointerMove = function (e) {
  24349. // If the current pointer is the one associated to the joystick (first touch contact)
  24350. if (this._joystickPointerID == e.pointerId) {
  24351. this._joystickPointerPos.x = e.clientX;
  24352. this._joystickPointerPos.y = e.clientY;
  24353. this._deltaJoystickVector = this._joystickPointerPos.clone();
  24354. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  24355. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  24356. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  24357. switch (this._axisTargetedByLeftAndRight) {
  24358. case JoystickAxis.X:
  24359. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  24360. break;
  24361. case JoystickAxis.Y:
  24362. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  24363. break;
  24364. case JoystickAxis.Z:
  24365. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  24366. break;
  24367. }
  24368. var directionUpDown = this.reverseUpDown ? 1 : -1;
  24369. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  24370. switch (this._axisTargetedByUpAndDown) {
  24371. case JoystickAxis.X:
  24372. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  24373. break;
  24374. case JoystickAxis.Y:
  24375. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  24376. break;
  24377. case JoystickAxis.Z:
  24378. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  24379. break;
  24380. }
  24381. }
  24382. else {
  24383. if (this._touches.item(e.pointerId.toString())) {
  24384. this._touches.item(e.pointerId.toString()).x = e.clientX;
  24385. this._touches.item(e.pointerId.toString()).y = e.clientY;
  24386. }
  24387. }
  24388. };
  24389. VirtualJoystick.prototype._onPointerUp = function (e) {
  24390. this._clearCanvas();
  24391. if (this._joystickPointerID == e.pointerId) {
  24392. this._joystickPointerID = -1;
  24393. this.pressed = false;
  24394. }
  24395. this._deltaJoystickVector.x = 0;
  24396. this._deltaJoystickVector.y = 0;
  24397. this._touches.remove(e.pointerId.toString());
  24398. };
  24399. /**
  24400. * Change the color of the virtual joystick
  24401. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  24402. */
  24403. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  24404. this._joystickColor = newColor;
  24405. };
  24406. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  24407. this._action = action;
  24408. };
  24409. // Define which axis you'd like to control for left & right
  24410. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  24411. switch (axis) {
  24412. case JoystickAxis.X:
  24413. case JoystickAxis.Y:
  24414. case JoystickAxis.Z:
  24415. this._axisTargetedByLeftAndRight = axis;
  24416. break;
  24417. default:
  24418. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  24419. break;
  24420. }
  24421. };
  24422. // Define which axis you'd like to control for up & down
  24423. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  24424. switch (axis) {
  24425. case JoystickAxis.X:
  24426. case JoystickAxis.Y:
  24427. case JoystickAxis.Z:
  24428. this._axisTargetedByUpAndDown = axis;
  24429. break;
  24430. default:
  24431. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  24432. break;
  24433. }
  24434. };
  24435. VirtualJoystick.prototype._clearCanvas = function () {
  24436. if (this._leftJoystick) {
  24437. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  24438. }
  24439. else {
  24440. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  24441. }
  24442. };
  24443. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  24444. var _this = this;
  24445. if (this.pressed) {
  24446. this._clearCanvas();
  24447. this._touches.forEach(function (touch) {
  24448. if (touch.pointerId === _this._joystickPointerID) {
  24449. VirtualJoystick.vjCanvasContext.beginPath();
  24450. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  24451. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  24452. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  24453. VirtualJoystick.vjCanvasContext.stroke();
  24454. VirtualJoystick.vjCanvasContext.beginPath();
  24455. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  24456. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  24457. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  24458. VirtualJoystick.vjCanvasContext.stroke();
  24459. VirtualJoystick.vjCanvasContext.beginPath();
  24460. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  24461. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  24462. VirtualJoystick.vjCanvasContext.stroke();
  24463. }
  24464. else {
  24465. VirtualJoystick.vjCanvasContext.beginPath();
  24466. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  24467. VirtualJoystick.vjCanvasContext.beginPath();
  24468. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  24469. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  24470. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  24471. VirtualJoystick.vjCanvasContext.stroke();
  24472. }
  24473. ;
  24474. });
  24475. }
  24476. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  24477. };
  24478. VirtualJoystick.prototype.releaseCanvas = function () {
  24479. if (VirtualJoystick.vjCanvas) {
  24480. document.body.removeChild(VirtualJoystick.vjCanvas);
  24481. VirtualJoystick.vjCanvas = null;
  24482. }
  24483. };
  24484. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  24485. VirtualJoystick._globalJoystickIndex = 0;
  24486. return VirtualJoystick;
  24487. })();
  24488. BABYLON.VirtualJoystick = VirtualJoystick;
  24489. })(BABYLON || (BABYLON = {}));
  24490. //# sourceMappingURL=babylon.virtualJoystick.js.map
  24491. var BABYLON;
  24492. (function (BABYLON) {
  24493. // We're mainly based on the logic defined into the FreeCamera code
  24494. var VirtualJoysticksCamera = (function (_super) {
  24495. __extends(VirtualJoysticksCamera, _super);
  24496. function VirtualJoysticksCamera(name, position, scene) {
  24497. _super.call(this, name, position, scene);
  24498. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  24499. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  24500. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  24501. this._leftjoystick.setJoystickSensibility(0.15);
  24502. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  24503. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  24504. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  24505. this._rightjoystick.reverseUpDown = true;
  24506. this._rightjoystick.setJoystickSensibility(0.05);
  24507. this._rightjoystick.setJoystickColor("yellow");
  24508. }
  24509. VirtualJoysticksCamera.prototype._checkInputs = function () {
  24510. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  24511. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  24512. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  24513. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  24514. if (!this._leftjoystick.pressed) {
  24515. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  24516. }
  24517. if (!this._rightjoystick.pressed) {
  24518. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  24519. }
  24520. _super.prototype._checkInputs.call(this);
  24521. };
  24522. VirtualJoysticksCamera.prototype.dispose = function () {
  24523. this._leftjoystick.releaseCanvas();
  24524. _super.prototype.dispose.call(this);
  24525. };
  24526. return VirtualJoysticksCamera;
  24527. })(BABYLON.FreeCamera);
  24528. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  24529. })(BABYLON || (BABYLON = {}));
  24530. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  24531. var BABYLON;
  24532. (function (BABYLON) {
  24533. var ShaderMaterial = (function (_super) {
  24534. __extends(ShaderMaterial, _super);
  24535. function ShaderMaterial(name, scene, shaderPath, options) {
  24536. _super.call(this, name, scene);
  24537. this._textures = new Array();
  24538. this._floats = new Array();
  24539. this._floatsArrays = {};
  24540. this._colors3 = new Array();
  24541. this._colors4 = new Array();
  24542. this._vectors2 = new Array();
  24543. this._vectors3 = new Array();
  24544. this._matrices = new Array();
  24545. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  24546. this._shaderPath = shaderPath;
  24547. options.needAlphaBlending = options.needAlphaBlending || false;
  24548. options.needAlphaTesting = options.needAlphaTesting || false;
  24549. options.attributes = options.attributes || ["position", "normal", "uv"];
  24550. options.uniforms = options.uniforms || ["worldViewProjection"];
  24551. options.samplers = options.samplers || [];
  24552. this._options = options;
  24553. }
  24554. ShaderMaterial.prototype.needAlphaBlending = function () {
  24555. return this._options.needAlphaBlending;
  24556. };
  24557. ShaderMaterial.prototype.needAlphaTesting = function () {
  24558. return this._options.needAlphaTesting;
  24559. };
  24560. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  24561. if (this._options.uniforms.indexOf(uniformName) === -1) {
  24562. this._options.uniforms.push(uniformName);
  24563. }
  24564. };
  24565. ShaderMaterial.prototype.setTexture = function (name, texture) {
  24566. if (this._options.samplers.indexOf(name) === -1) {
  24567. this._options.samplers.push(name);
  24568. }
  24569. this._textures[name] = texture;
  24570. return this;
  24571. };
  24572. ShaderMaterial.prototype.setFloat = function (name, value) {
  24573. this._checkUniform(name);
  24574. this._floats[name] = value;
  24575. return this;
  24576. };
  24577. ShaderMaterial.prototype.setFloats = function (name, value) {
  24578. this._checkUniform(name);
  24579. this._floatsArrays[name] = value;
  24580. return this;
  24581. };
  24582. ShaderMaterial.prototype.setColor3 = function (name, value) {
  24583. this._checkUniform(name);
  24584. this._colors3[name] = value;
  24585. return this;
  24586. };
  24587. ShaderMaterial.prototype.setColor4 = function (name, value) {
  24588. this._checkUniform(name);
  24589. this._colors4[name] = value;
  24590. return this;
  24591. };
  24592. ShaderMaterial.prototype.setVector2 = function (name, value) {
  24593. this._checkUniform(name);
  24594. this._vectors2[name] = value;
  24595. return this;
  24596. };
  24597. ShaderMaterial.prototype.setVector3 = function (name, value) {
  24598. this._checkUniform(name);
  24599. this._vectors3[name] = value;
  24600. return this;
  24601. };
  24602. ShaderMaterial.prototype.setMatrix = function (name, value) {
  24603. this._checkUniform(name);
  24604. this._matrices[name] = value;
  24605. return this;
  24606. };
  24607. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  24608. var scene = this.getScene();
  24609. var engine = scene.getEngine();
  24610. if (!this.checkReadyOnEveryCall) {
  24611. if (this._renderId === scene.getRenderId()) {
  24612. return true;
  24613. }
  24614. }
  24615. // Instances
  24616. var defines = [];
  24617. var fallbacks = new BABYLON.EffectFallbacks();
  24618. if (useInstances) {
  24619. defines.push("#define INSTANCES");
  24620. }
  24621. // Bones
  24622. if (mesh && mesh.useBones) {
  24623. defines.push("#define BONES");
  24624. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  24625. defines.push("#define BONES4");
  24626. fallbacks.addFallback(0, "BONES4");
  24627. }
  24628. // Alpha test
  24629. if (engine.getAlphaTesting()) {
  24630. defines.push("#define ALPHATEST");
  24631. }
  24632. var previousEffect = this._effect;
  24633. var join = defines.join("\n");
  24634. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  24635. if (!this._effect.isReady()) {
  24636. return false;
  24637. }
  24638. if (previousEffect !== this._effect) {
  24639. scene.resetCachedMaterial();
  24640. }
  24641. this._renderId = scene.getRenderId();
  24642. return true;
  24643. };
  24644. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24645. var scene = this.getScene();
  24646. if (this._options.uniforms.indexOf("world") !== -1) {
  24647. this._effect.setMatrix("world", world);
  24648. }
  24649. if (this._options.uniforms.indexOf("worldView") !== -1) {
  24650. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  24651. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  24652. }
  24653. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  24654. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  24655. }
  24656. };
  24657. ShaderMaterial.prototype.bind = function (world, mesh) {
  24658. // Std values
  24659. this.bindOnlyWorldMatrix(world);
  24660. if (this.getScene().getCachedMaterial() !== this) {
  24661. if (this._options.uniforms.indexOf("view") !== -1) {
  24662. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  24663. }
  24664. if (this._options.uniforms.indexOf("projection") !== -1) {
  24665. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  24666. }
  24667. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  24668. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  24669. }
  24670. // Bones
  24671. if (mesh && mesh.useBones) {
  24672. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  24673. }
  24674. // Texture
  24675. for (var name in this._textures) {
  24676. this._effect.setTexture(name, this._textures[name]);
  24677. }
  24678. // Float
  24679. for (name in this._floats) {
  24680. this._effect.setFloat(name, this._floats[name]);
  24681. }
  24682. // Float s
  24683. for (name in this._floatsArrays) {
  24684. this._effect.setArray(name, this._floatsArrays[name]);
  24685. }
  24686. // Color3
  24687. for (name in this._colors3) {
  24688. this._effect.setColor3(name, this._colors3[name]);
  24689. }
  24690. // Color4
  24691. for (name in this._colors4) {
  24692. var color = this._colors4[name];
  24693. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  24694. }
  24695. // Vector2
  24696. for (name in this._vectors2) {
  24697. this._effect.setVector2(name, this._vectors2[name]);
  24698. }
  24699. // Vector3
  24700. for (name in this._vectors3) {
  24701. this._effect.setVector3(name, this._vectors3[name]);
  24702. }
  24703. // Matrix
  24704. for (name in this._matrices) {
  24705. this._effect.setMatrix(name, this._matrices[name]);
  24706. }
  24707. }
  24708. _super.prototype.bind.call(this, world, mesh);
  24709. };
  24710. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  24711. for (var name in this._textures) {
  24712. this._textures[name].dispose();
  24713. }
  24714. this._textures = [];
  24715. _super.prototype.dispose.call(this, forceDisposeEffect);
  24716. };
  24717. return ShaderMaterial;
  24718. })(BABYLON.Material);
  24719. BABYLON.ShaderMaterial = ShaderMaterial;
  24720. })(BABYLON || (BABYLON = {}));
  24721. //# sourceMappingURL=babylon.shaderMaterial.js.map
  24722. var BABYLON;
  24723. (function (BABYLON) {
  24724. var VertexData = (function () {
  24725. function VertexData() {
  24726. }
  24727. VertexData.prototype.set = function (data, kind) {
  24728. switch (kind) {
  24729. case BABYLON.VertexBuffer.PositionKind:
  24730. this.positions = data;
  24731. break;
  24732. case BABYLON.VertexBuffer.NormalKind:
  24733. this.normals = data;
  24734. break;
  24735. case BABYLON.VertexBuffer.UVKind:
  24736. this.uvs = data;
  24737. break;
  24738. case BABYLON.VertexBuffer.UV2Kind:
  24739. this.uv2s = data;
  24740. break;
  24741. case BABYLON.VertexBuffer.ColorKind:
  24742. this.colors = data;
  24743. break;
  24744. case BABYLON.VertexBuffer.MatricesIndicesKind:
  24745. this.matricesIndices = data;
  24746. break;
  24747. case BABYLON.VertexBuffer.MatricesWeightsKind:
  24748. this.matricesWeights = data;
  24749. break;
  24750. }
  24751. };
  24752. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  24753. this._applyTo(mesh, updatable);
  24754. };
  24755. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  24756. this._applyTo(geometry, updatable);
  24757. };
  24758. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  24759. this._update(mesh);
  24760. };
  24761. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  24762. this._update(geometry);
  24763. };
  24764. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  24765. if (this.positions) {
  24766. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  24767. }
  24768. if (this.normals) {
  24769. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  24770. }
  24771. if (this.uvs) {
  24772. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  24773. }
  24774. if (this.uv2s) {
  24775. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  24776. }
  24777. if (this.colors) {
  24778. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  24779. }
  24780. if (this.matricesIndices) {
  24781. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  24782. }
  24783. if (this.matricesWeights) {
  24784. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  24785. }
  24786. if (this.indices) {
  24787. meshOrGeometry.setIndices(this.indices);
  24788. }
  24789. };
  24790. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  24791. if (this.positions) {
  24792. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  24793. }
  24794. if (this.normals) {
  24795. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  24796. }
  24797. if (this.uvs) {
  24798. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  24799. }
  24800. if (this.uv2s) {
  24801. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  24802. }
  24803. if (this.colors) {
  24804. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  24805. }
  24806. if (this.matricesIndices) {
  24807. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  24808. }
  24809. if (this.matricesWeights) {
  24810. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  24811. }
  24812. if (this.indices) {
  24813. meshOrGeometry.setIndices(this.indices);
  24814. }
  24815. };
  24816. VertexData.prototype.transform = function (matrix) {
  24817. var transformed = BABYLON.Vector3.Zero();
  24818. if (this.positions) {
  24819. var position = BABYLON.Vector3.Zero();
  24820. for (var index = 0; index < this.positions.length; index += 3) {
  24821. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  24822. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  24823. this.positions[index] = transformed.x;
  24824. this.positions[index + 1] = transformed.y;
  24825. this.positions[index + 2] = transformed.z;
  24826. }
  24827. }
  24828. if (this.normals) {
  24829. var normal = BABYLON.Vector3.Zero();
  24830. for (index = 0; index < this.normals.length; index += 3) {
  24831. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  24832. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  24833. this.normals[index] = transformed.x;
  24834. this.normals[index + 1] = transformed.y;
  24835. this.normals[index + 2] = transformed.z;
  24836. }
  24837. }
  24838. };
  24839. VertexData.prototype.merge = function (other) {
  24840. if (other.indices) {
  24841. if (!this.indices) {
  24842. this.indices = [];
  24843. }
  24844. var offset = this.positions ? this.positions.length / 3 : 0;
  24845. for (var index = 0; index < other.indices.length; index++) {
  24846. this.indices.push(other.indices[index] + offset);
  24847. }
  24848. }
  24849. if (other.positions) {
  24850. if (!this.positions) {
  24851. this.positions = [];
  24852. }
  24853. for (index = 0; index < other.positions.length; index++) {
  24854. this.positions.push(other.positions[index]);
  24855. }
  24856. }
  24857. if (other.normals) {
  24858. if (!this.normals) {
  24859. this.normals = [];
  24860. }
  24861. for (index = 0; index < other.normals.length; index++) {
  24862. this.normals.push(other.normals[index]);
  24863. }
  24864. }
  24865. if (other.uvs) {
  24866. if (!this.uvs) {
  24867. this.uvs = [];
  24868. }
  24869. for (index = 0; index < other.uvs.length; index++) {
  24870. this.uvs.push(other.uvs[index]);
  24871. }
  24872. }
  24873. if (other.uv2s) {
  24874. if (!this.uv2s) {
  24875. this.uv2s = [];
  24876. }
  24877. for (index = 0; index < other.uv2s.length; index++) {
  24878. this.uv2s.push(other.uv2s[index]);
  24879. }
  24880. }
  24881. if (other.matricesIndices) {
  24882. if (!this.matricesIndices) {
  24883. this.matricesIndices = [];
  24884. }
  24885. for (index = 0; index < other.matricesIndices.length; index++) {
  24886. this.matricesIndices.push(other.matricesIndices[index]);
  24887. }
  24888. }
  24889. if (other.matricesWeights) {
  24890. if (!this.matricesWeights) {
  24891. this.matricesWeights = [];
  24892. }
  24893. for (index = 0; index < other.matricesWeights.length; index++) {
  24894. this.matricesWeights.push(other.matricesWeights[index]);
  24895. }
  24896. }
  24897. if (other.colors) {
  24898. if (!this.colors) {
  24899. this.colors = [];
  24900. }
  24901. for (index = 0; index < other.colors.length; index++) {
  24902. this.colors.push(other.colors[index]);
  24903. }
  24904. }
  24905. };
  24906. // Statics
  24907. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  24908. return VertexData._ExtractFrom(mesh, copyWhenShared);
  24909. };
  24910. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  24911. return VertexData._ExtractFrom(geometry, copyWhenShared);
  24912. };
  24913. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  24914. var result = new VertexData();
  24915. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24916. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  24917. }
  24918. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24919. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  24920. }
  24921. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24922. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  24923. }
  24924. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24925. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  24926. }
  24927. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24928. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  24929. }
  24930. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24931. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  24932. }
  24933. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24934. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  24935. }
  24936. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  24937. return result;
  24938. };
  24939. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  24940. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24941. closeArray = closeArray || false;
  24942. closePath = closePath || false;
  24943. var defaultOffset = Math.floor(pathArray[0].length / 2);
  24944. offset = offset || defaultOffset;
  24945. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  24946. var positions = [];
  24947. var indices = [];
  24948. var normals = [];
  24949. var uvs = [];
  24950. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  24951. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  24952. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  24953. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  24954. var minlg; // minimal length among all paths from pathArray
  24955. var lg = []; // array of path lengths : nb of vertex per path
  24956. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  24957. var p; // path iterator
  24958. var i; // point iterator
  24959. var j; // point iterator
  24960. // if single path in pathArray
  24961. if (pathArray.length < 2) {
  24962. var ar1 = [];
  24963. var ar2 = [];
  24964. for (i = 0; i < pathArray[0].length - offset; i++) {
  24965. ar1.push(pathArray[0][i]);
  24966. ar2.push(pathArray[0][i + offset]);
  24967. }
  24968. pathArray = [ar1, ar2];
  24969. }
  24970. // positions and horizontal distances (u)
  24971. var idc = 0;
  24972. minlg = pathArray[0].length;
  24973. for (p = 0; p < pathArray.length; p++) {
  24974. uTotalDistance[p] = 0;
  24975. us[p] = [0];
  24976. var path = pathArray[p];
  24977. var l = path.length;
  24978. minlg = (minlg < l) ? minlg : l;
  24979. lg[p] = l;
  24980. idx[p] = idc;
  24981. j = 0;
  24982. while (j < l) {
  24983. positions.push(path[j].x, path[j].y, path[j].z);
  24984. if (j > 0) {
  24985. var vectlg = path[j].subtract(path[j - 1]).length();
  24986. var dist = vectlg + uTotalDistance[p];
  24987. us[p].push(dist);
  24988. uTotalDistance[p] = dist;
  24989. }
  24990. j++;
  24991. }
  24992. if (closePath) {
  24993. vectlg = path[0].subtract(path[j - 1]).length();
  24994. dist = vectlg + uTotalDistance[p];
  24995. uTotalDistance[p] = dist;
  24996. }
  24997. idc += l;
  24998. }
  24999. // vertical distances (v)
  25000. for (i = 0; i < minlg; i++) {
  25001. vTotalDistance[i] = 0;
  25002. vs[i] = [0];
  25003. var path1;
  25004. var path2;
  25005. for (p = 0; p < pathArray.length - 1; p++) {
  25006. path1 = pathArray[p];
  25007. path2 = pathArray[p + 1];
  25008. vectlg = path2[i].subtract(path1[i]).length();
  25009. dist = vectlg + vTotalDistance[i];
  25010. vs[i].push(dist);
  25011. vTotalDistance[i] = dist;
  25012. }
  25013. if (closeArray) {
  25014. path1 = pathArray[p];
  25015. path2 = pathArray[0];
  25016. vectlg = path2[i].subtract(path1[i]).length();
  25017. dist = vectlg + vTotalDistance[i];
  25018. vTotalDistance[i] = dist;
  25019. }
  25020. }
  25021. // uvs
  25022. var u;
  25023. var v;
  25024. for (p = 0; p < pathArray.length; p++) {
  25025. for (i = 0; i < minlg; i++) {
  25026. u = us[p][i] / uTotalDistance[p];
  25027. v = vs[i][p] / vTotalDistance[i];
  25028. uvs.push(u, v);
  25029. }
  25030. }
  25031. // indices
  25032. p = 0; // path index
  25033. var pi = 0; // positions array index
  25034. var l1 = lg[p] - 1; // path1 length
  25035. var l2 = lg[p + 1] - 1; // path2 length
  25036. var min = (l1 < l2) ? l1 : l2; // current path stop index
  25037. var shft = idx[1] - idx[0]; // shift
  25038. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  25039. var t1; // two consecutive triangles, so 4 points : point1
  25040. var t2; // point2
  25041. var t3; // point3
  25042. var t4; // point4
  25043. while (pi <= min && p < path1nb) {
  25044. // 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
  25045. t1 = pi;
  25046. t2 = pi + shft;
  25047. t3 = pi + 1;
  25048. t4 = pi + shft + 1;
  25049. indices.push(pi, pi + shft, pi + 1);
  25050. indices.push(pi + shft + 1, pi + 1, pi + shft);
  25051. pi += 1;
  25052. if (pi === min) {
  25053. if (closePath) {
  25054. indices.push(pi, pi + shft, idx[p]);
  25055. indices.push(idx[p] + shft, idx[p], pi + shft);
  25056. t3 = idx[p];
  25057. t4 = idx[p] + shft;
  25058. }
  25059. p++;
  25060. if (p === lg.length - 1) {
  25061. shft = idx[0] - idx[p];
  25062. l1 = lg[p] - 1;
  25063. l2 = lg[0] - 1;
  25064. }
  25065. else {
  25066. shft = idx[p + 1] - idx[p];
  25067. l1 = lg[p] - 1;
  25068. l2 = lg[p + 1] - 1;
  25069. }
  25070. pi = idx[p];
  25071. min = (l1 < l2) ? l1 + pi : l2 + pi;
  25072. }
  25073. }
  25074. // normals
  25075. VertexData.ComputeNormals(positions, indices, normals);
  25076. // sides
  25077. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25078. // Result
  25079. var vertexData = new VertexData();
  25080. vertexData.indices = indices;
  25081. vertexData.positions = positions;
  25082. vertexData.normals = normals;
  25083. vertexData.uvs = uvs;
  25084. return vertexData;
  25085. };
  25086. VertexData.CreateBox = function (size, sideOrientation) {
  25087. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25088. var normalsSource = [
  25089. new BABYLON.Vector3(0, 0, 1),
  25090. new BABYLON.Vector3(0, 0, -1),
  25091. new BABYLON.Vector3(1, 0, 0),
  25092. new BABYLON.Vector3(-1, 0, 0),
  25093. new BABYLON.Vector3(0, 1, 0),
  25094. new BABYLON.Vector3(0, -1, 0)
  25095. ];
  25096. var indices = [];
  25097. var positions = [];
  25098. var normals = [];
  25099. var uvs = [];
  25100. size = size || 1;
  25101. // Create each face in turn.
  25102. for (var index = 0; index < normalsSource.length; index++) {
  25103. var normal = normalsSource[index];
  25104. // Get two vectors perpendicular to the face normal and to each other.
  25105. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  25106. var side2 = BABYLON.Vector3.Cross(normal, side1);
  25107. // Six indices (two triangles) per face.
  25108. var verticesLength = positions.length / 3;
  25109. indices.push(verticesLength);
  25110. indices.push(verticesLength + 1);
  25111. indices.push(verticesLength + 2);
  25112. indices.push(verticesLength);
  25113. indices.push(verticesLength + 2);
  25114. indices.push(verticesLength + 3);
  25115. // Four vertices per face.
  25116. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  25117. positions.push(vertex.x, vertex.y, vertex.z);
  25118. normals.push(normal.x, normal.y, normal.z);
  25119. uvs.push(1.0, 1.0);
  25120. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  25121. positions.push(vertex.x, vertex.y, vertex.z);
  25122. normals.push(normal.x, normal.y, normal.z);
  25123. uvs.push(0.0, 1.0);
  25124. vertex = normal.add(side1).add(side2).scale(size / 2);
  25125. positions.push(vertex.x, vertex.y, vertex.z);
  25126. normals.push(normal.x, normal.y, normal.z);
  25127. uvs.push(0.0, 0.0);
  25128. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  25129. positions.push(vertex.x, vertex.y, vertex.z);
  25130. normals.push(normal.x, normal.y, normal.z);
  25131. uvs.push(1.0, 0.0);
  25132. }
  25133. // sides
  25134. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25135. // Result
  25136. var vertexData = new VertexData();
  25137. vertexData.indices = indices;
  25138. vertexData.positions = positions;
  25139. vertexData.normals = normals;
  25140. vertexData.uvs = uvs;
  25141. return vertexData;
  25142. };
  25143. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  25144. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25145. segments = segments || 32;
  25146. diameter = diameter || 1;
  25147. var radius = diameter / 2;
  25148. var totalZRotationSteps = 2 + segments;
  25149. var totalYRotationSteps = 2 * totalZRotationSteps;
  25150. var indices = [];
  25151. var positions = [];
  25152. var normals = [];
  25153. var uvs = [];
  25154. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  25155. var normalizedZ = zRotationStep / totalZRotationSteps;
  25156. var angleZ = (normalizedZ * Math.PI);
  25157. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  25158. var normalizedY = yRotationStep / totalYRotationSteps;
  25159. var angleY = normalizedY * Math.PI * 2;
  25160. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  25161. var rotationY = BABYLON.Matrix.RotationY(angleY);
  25162. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  25163. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  25164. var vertex = complete.scale(radius);
  25165. var normal = BABYLON.Vector3.Normalize(vertex);
  25166. positions.push(vertex.x, vertex.y, vertex.z);
  25167. normals.push(normal.x, normal.y, normal.z);
  25168. uvs.push(normalizedZ, normalizedY);
  25169. }
  25170. if (zRotationStep > 0) {
  25171. var verticesCount = positions.length / 3;
  25172. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  25173. indices.push((firstIndex));
  25174. indices.push((firstIndex + 1));
  25175. indices.push(firstIndex + totalYRotationSteps + 1);
  25176. indices.push((firstIndex + totalYRotationSteps + 1));
  25177. indices.push((firstIndex + 1));
  25178. indices.push((firstIndex + totalYRotationSteps + 2));
  25179. }
  25180. }
  25181. }
  25182. // Sides
  25183. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25184. // Result
  25185. var vertexData = new VertexData();
  25186. vertexData.indices = indices;
  25187. vertexData.positions = positions;
  25188. vertexData.normals = normals;
  25189. vertexData.uvs = uvs;
  25190. return vertexData;
  25191. };
  25192. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  25193. if (subdivisions === void 0) { subdivisions = 1; }
  25194. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25195. var radiusTop = diameterTop / 2;
  25196. var radiusBottom = diameterBottom / 2;
  25197. var indices = [];
  25198. var positions = [];
  25199. var normals = [];
  25200. var uvs = [];
  25201. height = height || 1;
  25202. diameterTop = diameterTop || 0.5;
  25203. diameterBottom = diameterBottom || 1;
  25204. tessellation = tessellation || 16;
  25205. subdivisions = subdivisions || 1;
  25206. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  25207. var getCircleVector = function (i) {
  25208. var angle = (i * 2.0 * Math.PI / tessellation);
  25209. var dx = Math.cos(angle);
  25210. var dz = Math.sin(angle);
  25211. return new BABYLON.Vector3(dx, 0, dz);
  25212. };
  25213. var createCylinderCap = function (isTop) {
  25214. var radius = isTop ? radiusTop : radiusBottom;
  25215. if (radius === 0) {
  25216. return;
  25217. }
  25218. var vbase = positions.length / 3;
  25219. var offset = new BABYLON.Vector3(0, height / 2, 0);
  25220. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  25221. if (!isTop) {
  25222. offset.scaleInPlace(-1);
  25223. textureScale.x = -textureScale.x;
  25224. }
  25225. // Positions, normals & uvs
  25226. for (var i = 0; i < tessellation; i++) {
  25227. var circleVector = getCircleVector(i);
  25228. var position = circleVector.scale(radius).add(offset);
  25229. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  25230. positions.push(position.x, position.y, position.z);
  25231. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25232. }
  25233. // Indices
  25234. for (i = 0; i < tessellation - 2; i++) {
  25235. if (!isTop) {
  25236. indices.push(vbase);
  25237. indices.push(vbase + (i + 2) % tessellation);
  25238. indices.push(vbase + (i + 1) % tessellation);
  25239. }
  25240. else {
  25241. indices.push(vbase);
  25242. indices.push(vbase + (i + 1) % tessellation);
  25243. indices.push(vbase + (i + 2) % tessellation);
  25244. }
  25245. }
  25246. };
  25247. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  25248. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  25249. var stride = tessellation + 1;
  25250. // Positions, normals & uvs
  25251. for (var i = 0; i <= tessellation; i++) {
  25252. var circleVector = getCircleVector(i);
  25253. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  25254. var position, radius = radiusBottom;
  25255. for (var s = 0; s <= subdivisions; s++) {
  25256. // Update variables
  25257. position = circleVector.scale(radius);
  25258. position.addInPlace(base.add(offset.scale(s)));
  25259. textureCoordinate.y += 1 / subdivisions;
  25260. radius += (radiusTop - radiusBottom) / subdivisions;
  25261. // Push in arrays
  25262. positions.push(position.x, position.y, position.z);
  25263. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25264. }
  25265. }
  25266. subdivisions += 1;
  25267. // Indices
  25268. for (s = 0; s < subdivisions - 1; s++) {
  25269. for (i = 0; i <= tessellation; i++) {
  25270. indices.push(i * subdivisions + s);
  25271. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  25272. indices.push(i * subdivisions + (s + 1));
  25273. indices.push(i * subdivisions + (s + 1));
  25274. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  25275. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  25276. }
  25277. }
  25278. // Create flat triangle fan caps to seal the top and bottom.
  25279. createCylinderCap(true);
  25280. createCylinderCap(false);
  25281. // Normals
  25282. VertexData.ComputeNormals(positions, indices, normals);
  25283. // Sides
  25284. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25285. // Result
  25286. var vertexData = new VertexData();
  25287. vertexData.indices = indices;
  25288. vertexData.positions = positions;
  25289. vertexData.normals = normals;
  25290. vertexData.uvs = uvs;
  25291. return vertexData;
  25292. };
  25293. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  25294. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25295. var indices = [];
  25296. var positions = [];
  25297. var normals = [];
  25298. var uvs = [];
  25299. diameter = diameter || 1;
  25300. thickness = thickness || 0.5;
  25301. tessellation = tessellation || 16;
  25302. var stride = tessellation + 1;
  25303. for (var i = 0; i <= tessellation; i++) {
  25304. var u = i / tessellation;
  25305. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  25306. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  25307. for (var j = 0; j <= tessellation; j++) {
  25308. var v = 1 - j / tessellation;
  25309. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  25310. var dx = Math.cos(innerAngle);
  25311. var dy = Math.sin(innerAngle);
  25312. // Create a vertex.
  25313. var normal = new BABYLON.Vector3(dx, dy, 0);
  25314. var position = normal.scale(thickness / 2);
  25315. var textureCoordinate = new BABYLON.Vector2(u, v);
  25316. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  25317. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  25318. positions.push(position.x, position.y, position.z);
  25319. normals.push(normal.x, normal.y, normal.z);
  25320. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25321. // And create indices for two triangles.
  25322. var nextI = (i + 1) % stride;
  25323. var nextJ = (j + 1) % stride;
  25324. indices.push(i * stride + j);
  25325. indices.push(i * stride + nextJ);
  25326. indices.push(nextI * stride + j);
  25327. indices.push(i * stride + nextJ);
  25328. indices.push(nextI * stride + nextJ);
  25329. indices.push(nextI * stride + j);
  25330. }
  25331. }
  25332. // Sides
  25333. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25334. // Result
  25335. var vertexData = new VertexData();
  25336. vertexData.indices = indices;
  25337. vertexData.positions = positions;
  25338. vertexData.normals = normals;
  25339. vertexData.uvs = uvs;
  25340. return vertexData;
  25341. };
  25342. VertexData.CreateLines = function (points) {
  25343. var indices = [];
  25344. var positions = [];
  25345. for (var index = 0; index < points.length; index++) {
  25346. positions.push(points[index].x, points[index].y, points[index].z);
  25347. if (index > 0) {
  25348. indices.push(index - 1);
  25349. indices.push(index);
  25350. }
  25351. }
  25352. // Result
  25353. var vertexData = new VertexData();
  25354. vertexData.indices = indices;
  25355. vertexData.positions = positions;
  25356. return vertexData;
  25357. };
  25358. VertexData.CreateDashedLines = function (points, dashSize, gapSize, dashNb) {
  25359. dashSize = dashSize || 3;
  25360. gapSize = gapSize || 1;
  25361. dashNb = dashNb || 200;
  25362. var positions = new Array();
  25363. var indices = new Array();
  25364. var curvect = BABYLON.Vector3.Zero();
  25365. var lg = 0;
  25366. var nb = 0;
  25367. var shft = 0;
  25368. var dashshft = 0;
  25369. var curshft = 0;
  25370. var idx = 0;
  25371. var i = 0;
  25372. for (i = 0; i < points.length - 1; i++) {
  25373. points[i + 1].subtractToRef(points[i], curvect);
  25374. lg += curvect.length();
  25375. }
  25376. shft = lg / dashNb;
  25377. dashshft = dashSize * shft / (dashSize + gapSize);
  25378. for (i = 0; i < points.length - 1; i++) {
  25379. points[i + 1].subtractToRef(points[i], curvect);
  25380. nb = Math.floor(curvect.length() / shft);
  25381. curvect.normalize();
  25382. for (var j = 0; j < nb; j++) {
  25383. curshft = shft * j;
  25384. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  25385. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  25386. indices.push(idx, idx + 1);
  25387. idx += 2;
  25388. }
  25389. }
  25390. // Result
  25391. var vertexData = new VertexData();
  25392. vertexData.positions = positions;
  25393. vertexData.indices = indices;
  25394. return vertexData;
  25395. };
  25396. VertexData.CreateGround = function (width, height, subdivisions) {
  25397. var indices = [];
  25398. var positions = [];
  25399. var normals = [];
  25400. var uvs = [];
  25401. var row, col;
  25402. width = width || 1;
  25403. height = height || 1;
  25404. subdivisions = subdivisions || 1;
  25405. for (row = 0; row <= subdivisions; row++) {
  25406. for (col = 0; col <= subdivisions; col++) {
  25407. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  25408. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25409. positions.push(position.x, position.y, position.z);
  25410. normals.push(normal.x, normal.y, normal.z);
  25411. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  25412. }
  25413. }
  25414. for (row = 0; row < subdivisions; row++) {
  25415. for (col = 0; col < subdivisions; col++) {
  25416. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25417. indices.push(col + 1 + row * (subdivisions + 1));
  25418. indices.push(col + row * (subdivisions + 1));
  25419. indices.push(col + (row + 1) * (subdivisions + 1));
  25420. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25421. indices.push(col + row * (subdivisions + 1));
  25422. }
  25423. }
  25424. // Result
  25425. var vertexData = new VertexData();
  25426. vertexData.indices = indices;
  25427. vertexData.positions = positions;
  25428. vertexData.normals = normals;
  25429. vertexData.uvs = uvs;
  25430. return vertexData;
  25431. };
  25432. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  25433. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  25434. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  25435. var indices = [];
  25436. var positions = [];
  25437. var normals = [];
  25438. var uvs = [];
  25439. var row, col, tileRow, tileCol;
  25440. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  25441. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  25442. precision.w = (precision.w < 1) ? 1 : precision.w;
  25443. precision.h = (precision.h < 1) ? 1 : precision.h;
  25444. var tileSize = {
  25445. 'w': (xmax - xmin) / subdivisions.w,
  25446. 'h': (zmax - zmin) / subdivisions.h
  25447. };
  25448. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  25449. // Indices
  25450. var base = positions.length / 3;
  25451. var rowLength = precision.w + 1;
  25452. for (row = 0; row < precision.h; row++) {
  25453. for (col = 0; col < precision.w; col++) {
  25454. var square = [
  25455. base + col + row * rowLength,
  25456. base + (col + 1) + row * rowLength,
  25457. base + (col + 1) + (row + 1) * rowLength,
  25458. base + col + (row + 1) * rowLength
  25459. ];
  25460. indices.push(square[1]);
  25461. indices.push(square[2]);
  25462. indices.push(square[3]);
  25463. indices.push(square[0]);
  25464. indices.push(square[1]);
  25465. indices.push(square[3]);
  25466. }
  25467. }
  25468. // Position, normals and uvs
  25469. var position = BABYLON.Vector3.Zero();
  25470. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25471. for (row = 0; row <= precision.h; row++) {
  25472. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  25473. for (col = 0; col <= precision.w; col++) {
  25474. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  25475. position.y = 0;
  25476. positions.push(position.x, position.y, position.z);
  25477. normals.push(normal.x, normal.y, normal.z);
  25478. uvs.push(col / precision.w, row / precision.h);
  25479. }
  25480. }
  25481. }
  25482. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  25483. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  25484. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  25485. }
  25486. }
  25487. // Result
  25488. var vertexData = new VertexData();
  25489. vertexData.indices = indices;
  25490. vertexData.positions = positions;
  25491. vertexData.normals = normals;
  25492. vertexData.uvs = uvs;
  25493. return vertexData;
  25494. };
  25495. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  25496. var indices = [];
  25497. var positions = [];
  25498. var normals = [];
  25499. var uvs = [];
  25500. var row, col;
  25501. // Vertices
  25502. for (row = 0; row <= subdivisions; row++) {
  25503. for (col = 0; col <= subdivisions; col++) {
  25504. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  25505. // Compute height
  25506. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  25507. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  25508. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  25509. var r = buffer[pos] / 255.0;
  25510. var g = buffer[pos + 1] / 255.0;
  25511. var b = buffer[pos + 2] / 255.0;
  25512. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  25513. position.y = minHeight + (maxHeight - minHeight) * gradient;
  25514. // Add vertex
  25515. positions.push(position.x, position.y, position.z);
  25516. normals.push(0, 0, 0);
  25517. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  25518. }
  25519. }
  25520. // Indices
  25521. for (row = 0; row < subdivisions; row++) {
  25522. for (col = 0; col < subdivisions; col++) {
  25523. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25524. indices.push(col + 1 + row * (subdivisions + 1));
  25525. indices.push(col + row * (subdivisions + 1));
  25526. indices.push(col + (row + 1) * (subdivisions + 1));
  25527. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25528. indices.push(col + row * (subdivisions + 1));
  25529. }
  25530. }
  25531. // Normals
  25532. VertexData.ComputeNormals(positions, indices, normals);
  25533. // Result
  25534. var vertexData = new VertexData();
  25535. vertexData.indices = indices;
  25536. vertexData.positions = positions;
  25537. vertexData.normals = normals;
  25538. vertexData.uvs = uvs;
  25539. return vertexData;
  25540. };
  25541. VertexData.CreatePlane = function (size, sideOrientation) {
  25542. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25543. var indices = [];
  25544. var positions = [];
  25545. var normals = [];
  25546. var uvs = [];
  25547. size = size || 1;
  25548. // Vertices
  25549. var halfSize = size / 2.0;
  25550. positions.push(-halfSize, -halfSize, 0);
  25551. normals.push(0, 0, -1.0);
  25552. uvs.push(0.0, 0.0);
  25553. positions.push(halfSize, -halfSize, 0);
  25554. normals.push(0, 0, -1.0);
  25555. uvs.push(1.0, 0.0);
  25556. positions.push(halfSize, halfSize, 0);
  25557. normals.push(0, 0, -1.0);
  25558. uvs.push(1.0, 1.0);
  25559. positions.push(-halfSize, halfSize, 0);
  25560. normals.push(0, 0, -1.0);
  25561. uvs.push(0.0, 1.0);
  25562. // Indices
  25563. indices.push(0);
  25564. indices.push(1);
  25565. indices.push(2);
  25566. indices.push(0);
  25567. indices.push(2);
  25568. indices.push(3);
  25569. // Sides
  25570. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25571. // Result
  25572. var vertexData = new VertexData();
  25573. vertexData.indices = indices;
  25574. vertexData.positions = positions;
  25575. vertexData.normals = normals;
  25576. vertexData.uvs = uvs;
  25577. return vertexData;
  25578. };
  25579. VertexData.CreateDisc = function (radius, tessellation, sideOrientation) {
  25580. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25581. var positions = [];
  25582. var indices = [];
  25583. var normals = [];
  25584. var uvs = [];
  25585. // positions and uvs
  25586. positions.push(0, 0, 0); // disc center first
  25587. uvs.push(0.5, 0.5);
  25588. var step = Math.PI * 2 / tessellation;
  25589. for (var a = 0; a < Math.PI * 2; a += step) {
  25590. var x = Math.cos(a);
  25591. var y = Math.sin(a);
  25592. var u = (x + 1) / 2;
  25593. var v = (1 - y) / 2;
  25594. positions.push(radius * x, radius * y, 0);
  25595. uvs.push(u, v);
  25596. }
  25597. positions.push(positions[3], positions[4], positions[5]); // close the circle
  25598. uvs.push(uvs[2], uvs[3]);
  25599. //indices
  25600. var vertexNb = positions.length / 3;
  25601. for (var i = 1; i < vertexNb - 1; i++) {
  25602. indices.push(i + 1, 0, i);
  25603. }
  25604. // result
  25605. VertexData.ComputeNormals(positions, indices, normals);
  25606. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25607. var vertexData = new VertexData();
  25608. vertexData.indices = indices;
  25609. vertexData.positions = positions;
  25610. vertexData.normals = normals;
  25611. vertexData.uvs = uvs;
  25612. return vertexData;
  25613. };
  25614. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  25615. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  25616. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25617. var indices = [];
  25618. var positions = [];
  25619. var normals = [];
  25620. var uvs = [];
  25621. radius = radius || 2;
  25622. tube = tube || 0.5;
  25623. radialSegments = radialSegments || 32;
  25624. tubularSegments = tubularSegments || 32;
  25625. p = p || 2;
  25626. q = q || 3;
  25627. // Helper
  25628. var getPos = function (angle) {
  25629. var cu = Math.cos(angle);
  25630. var su = Math.sin(angle);
  25631. var quOverP = q / p * angle;
  25632. var cs = Math.cos(quOverP);
  25633. var tx = radius * (2 + cs) * 0.5 * cu;
  25634. var ty = radius * (2 + cs) * su * 0.5;
  25635. var tz = radius * Math.sin(quOverP) * 0.5;
  25636. return new BABYLON.Vector3(tx, ty, tz);
  25637. };
  25638. // Vertices
  25639. for (var i = 0; i <= radialSegments; i++) {
  25640. var modI = i % radialSegments;
  25641. var u = modI / radialSegments * 2 * p * Math.PI;
  25642. var p1 = getPos(u);
  25643. var p2 = getPos(u + 0.01);
  25644. var tang = p2.subtract(p1);
  25645. var n = p2.add(p1);
  25646. var bitan = BABYLON.Vector3.Cross(tang, n);
  25647. n = BABYLON.Vector3.Cross(bitan, tang);
  25648. bitan.normalize();
  25649. n.normalize();
  25650. for (var j = 0; j < tubularSegments; j++) {
  25651. var modJ = j % tubularSegments;
  25652. var v = modJ / tubularSegments * 2 * Math.PI;
  25653. var cx = -tube * Math.cos(v);
  25654. var cy = tube * Math.sin(v);
  25655. positions.push(p1.x + cx * n.x + cy * bitan.x);
  25656. positions.push(p1.y + cx * n.y + cy * bitan.y);
  25657. positions.push(p1.z + cx * n.z + cy * bitan.z);
  25658. uvs.push(i / radialSegments);
  25659. uvs.push(j / tubularSegments);
  25660. }
  25661. }
  25662. for (i = 0; i < radialSegments; i++) {
  25663. for (j = 0; j < tubularSegments; j++) {
  25664. var jNext = (j + 1) % tubularSegments;
  25665. var a = i * tubularSegments + j;
  25666. var b = (i + 1) * tubularSegments + j;
  25667. var c = (i + 1) * tubularSegments + jNext;
  25668. var d = i * tubularSegments + jNext;
  25669. indices.push(d);
  25670. indices.push(b);
  25671. indices.push(a);
  25672. indices.push(d);
  25673. indices.push(c);
  25674. indices.push(b);
  25675. }
  25676. }
  25677. // Normals
  25678. VertexData.ComputeNormals(positions, indices, normals);
  25679. // Sides
  25680. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25681. // Result
  25682. var vertexData = new VertexData();
  25683. vertexData.indices = indices;
  25684. vertexData.positions = positions;
  25685. vertexData.normals = normals;
  25686. vertexData.uvs = uvs;
  25687. return vertexData;
  25688. };
  25689. // Tools
  25690. /**
  25691. * @param {any} - positions (number[] or Float32Array)
  25692. * @param {any} - indices (number[] or Uint16Array)
  25693. * @param {any} - normals (number[] or Float32Array)
  25694. */
  25695. VertexData.ComputeNormals = function (positions, indices, normals) {
  25696. var index = 0;
  25697. // temp Vector3
  25698. var p1 = BABYLON.Vector3.Zero();
  25699. var p2 = BABYLON.Vector3.Zero();
  25700. var p3 = BABYLON.Vector3.Zero();
  25701. var p1p2 = BABYLON.Vector3.Zero();
  25702. var p3p2 = BABYLON.Vector3.Zero();
  25703. var faceNormal = BABYLON.Vector3.Zero();
  25704. var vertexNormali1 = BABYLON.Vector3.Zero();
  25705. var vertexNormali2 = BABYLON.Vector3.Zero();
  25706. var vertexNormali3 = BABYLON.Vector3.Zero();
  25707. // indice triplet = 1 face
  25708. var nbFaces = indices.length / 3;
  25709. for (index = 0; index < nbFaces; index++) {
  25710. var i1 = indices[index * 3];
  25711. var i2 = indices[index * 3 + 1];
  25712. var i3 = indices[index * 3 + 2];
  25713. // setting the temp V3
  25714. BABYLON.Vector3.FromFloatsToRef(positions[i1 * 3], positions[i1 * 3 + 1], positions[i1 * 3 + 2], p1);
  25715. BABYLON.Vector3.FromFloatsToRef(positions[i2 * 3], positions[i2 * 3 + 1], positions[i2 * 3 + 2], p2);
  25716. BABYLON.Vector3.FromFloatsToRef(positions[i3 * 3], positions[i3 * 3 + 1], positions[i3 * 3 + 2], p3);
  25717. p1.subtractToRef(p2, p1p2);
  25718. p3.subtractToRef(p2, p3p2);
  25719. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  25720. faceNormal.normalize();
  25721. // All intermediate results are stored in the normals array :
  25722. // get the normals at i1, i2 and i3 indexes
  25723. normals[i1 * 3] = normals[i1 * 3] || 0.0;
  25724. normals[i1 * 3 + 1] = normals[i1 * 3 + 1] || 0.0;
  25725. normals[i1 * 3 + 2] = normals[i1 * 3 + 2] || 0.0;
  25726. normals[i2 * 3] = normals[i2 * 3] || 0.0;
  25727. normals[i2 * 3 + 1] = normals[i2 * 3 + 1] || 0.0;
  25728. normals[i2 * 3 + 2] = normals[i2 * 3 + 2] || 0.0;
  25729. normals[i3 * 3] = normals[i3 * 3] || 0.0;
  25730. normals[i3 * 3 + 1] = normals[i3 * 3 + 1] || 0.0;
  25731. normals[i3 * 3 + 2] = normals[i3 * 3 + 2] || 0.0;
  25732. // make intermediate vectors3 from normals values
  25733. BABYLON.Vector3.FromFloatsToRef(normals[i1 * 3], normals[i1 * 3 + 1], normals[i1 * 3 + 2], vertexNormali1);
  25734. BABYLON.Vector3.FromFloatsToRef(normals[i2 * 3], normals[i2 * 3 + 1], normals[i2 * 3 + 2], vertexNormali2);
  25735. BABYLON.Vector3.FromFloatsToRef(normals[i3 * 3], normals[i3 * 3 + 1], normals[i3 * 3 + 2], vertexNormali3);
  25736. // add the current face normals to these intermediate vectors3
  25737. vertexNormali1 = vertexNormali1.addInPlace(faceNormal);
  25738. vertexNormali2 = vertexNormali2.addInPlace(faceNormal);
  25739. vertexNormali3 = vertexNormali3.addInPlace(faceNormal);
  25740. // store back intermediate vectors3 into the normals array
  25741. normals[i1 * 3] = vertexNormali1.x;
  25742. normals[i1 * 3 + 1] = vertexNormali1.y;
  25743. normals[i1 * 3 + 2] = vertexNormali1.z;
  25744. normals[i2 * 3] = vertexNormali2.x;
  25745. normals[i2 * 3 + 1] = vertexNormali2.y;
  25746. normals[i2 * 3 + 2] = vertexNormali2.z;
  25747. normals[i3 * 3] = vertexNormali3.x;
  25748. normals[i3 * 3 + 1] = vertexNormali3.y;
  25749. normals[i3 * 3 + 2] = vertexNormali3.z;
  25750. }
  25751. // last normalization
  25752. for (index = 0; index < normals.length / 3; index++) {
  25753. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  25754. vertexNormali1.normalize();
  25755. normals[index * 3] = vertexNormali1.x;
  25756. normals[index * 3 + 1] = vertexNormali1.y;
  25757. normals[index * 3 + 2] = vertexNormali1.z;
  25758. }
  25759. };
  25760. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  25761. var li = indices.length;
  25762. var ln = normals.length;
  25763. var i;
  25764. var n;
  25765. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25766. switch (sideOrientation) {
  25767. case BABYLON.Mesh.FRONTSIDE:
  25768. // nothing changed
  25769. break;
  25770. case BABYLON.Mesh.BACKSIDE:
  25771. var tmp;
  25772. // indices
  25773. for (i = 0; i < li; i += 3) {
  25774. tmp = indices[i];
  25775. indices[i] = indices[i + 2];
  25776. indices[i + 2] = tmp;
  25777. }
  25778. // normals
  25779. for (n = 0; n < ln; n++) {
  25780. normals[n] = -normals[n];
  25781. }
  25782. break;
  25783. case BABYLON.Mesh.DOUBLESIDE:
  25784. // positions
  25785. var lp = positions.length;
  25786. var l = lp / 3;
  25787. for (var p = 0; p < lp; p++) {
  25788. positions[lp + p] = positions[p];
  25789. }
  25790. // indices
  25791. for (i = 0; i < li; i += 3) {
  25792. indices[i + li] = indices[i + 2] + l;
  25793. indices[i + 1 + li] = indices[i + 1] + l;
  25794. indices[i + 2 + li] = indices[i] + l;
  25795. }
  25796. // normals
  25797. for (n = 0; n < ln; n++) {
  25798. normals[ln + n] = -normals[n];
  25799. }
  25800. // uvs
  25801. var lu = uvs.length;
  25802. for (var u = 0; u < lu; u++) {
  25803. uvs[u + lu] = uvs[u];
  25804. }
  25805. break;
  25806. }
  25807. };
  25808. return VertexData;
  25809. })();
  25810. BABYLON.VertexData = VertexData;
  25811. })(BABYLON || (BABYLON = {}));
  25812. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  25813. var BABYLON;
  25814. (function (BABYLON) {
  25815. var AnaglyphFreeCamera = (function (_super) {
  25816. __extends(AnaglyphFreeCamera, _super);
  25817. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  25818. _super.call(this, name, position, scene);
  25819. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_ANAGLYPH, eyeSpace);
  25820. }
  25821. return AnaglyphFreeCamera;
  25822. })(BABYLON.FreeCamera);
  25823. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  25824. var AnaglyphArcRotateCamera = (function (_super) {
  25825. __extends(AnaglyphArcRotateCamera, _super);
  25826. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  25827. _super.call(this, name, alpha, beta, radius, target, scene);
  25828. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_ANAGLYPH, eyeSpace);
  25829. }
  25830. return AnaglyphArcRotateCamera;
  25831. })(BABYLON.ArcRotateCamera);
  25832. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  25833. var AnaglyphGamepadCamera = (function (_super) {
  25834. __extends(AnaglyphGamepadCamera, _super);
  25835. function AnaglyphGamepadCamera(name, position, eyeSpace, scene) {
  25836. _super.call(this, name, position, scene);
  25837. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_ANAGLYPH, eyeSpace);
  25838. }
  25839. return AnaglyphGamepadCamera;
  25840. })(BABYLON.GamepadCamera);
  25841. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  25842. })(BABYLON || (BABYLON = {}));
  25843. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  25844. var BABYLON;
  25845. (function (BABYLON) {
  25846. var AnaglyphPostProcess = (function (_super) {
  25847. __extends(AnaglyphPostProcess, _super);
  25848. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  25849. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  25850. }
  25851. return AnaglyphPostProcess;
  25852. })(BABYLON.PostProcess);
  25853. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  25854. })(BABYLON || (BABYLON = {}));
  25855. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  25856. var BABYLON;
  25857. (function (BABYLON) {
  25858. var Tags = (function () {
  25859. function Tags() {
  25860. }
  25861. Tags.EnableFor = function (obj) {
  25862. obj._tags = obj._tags || {};
  25863. obj.hasTags = function () {
  25864. return Tags.HasTags(obj);
  25865. };
  25866. obj.addTags = function (tagsString) {
  25867. return Tags.AddTagsTo(obj, tagsString);
  25868. };
  25869. obj.removeTags = function (tagsString) {
  25870. return Tags.RemoveTagsFrom(obj, tagsString);
  25871. };
  25872. obj.matchesTagsQuery = function (tagsQuery) {
  25873. return Tags.MatchesQuery(obj, tagsQuery);
  25874. };
  25875. };
  25876. Tags.DisableFor = function (obj) {
  25877. delete obj._tags;
  25878. delete obj.hasTags;
  25879. delete obj.addTags;
  25880. delete obj.removeTags;
  25881. delete obj.matchesTagsQuery;
  25882. };
  25883. Tags.HasTags = function (obj) {
  25884. if (!obj._tags) {
  25885. return false;
  25886. }
  25887. return !BABYLON.Tools.IsEmpty(obj._tags);
  25888. };
  25889. Tags.GetTags = function (obj) {
  25890. if (!obj._tags) {
  25891. return null;
  25892. }
  25893. return obj._tags;
  25894. };
  25895. // the tags 'true' and 'false' are reserved and cannot be used as tags
  25896. // a tag cannot start with '||', '&&', and '!'
  25897. // it cannot contain whitespaces
  25898. Tags.AddTagsTo = function (obj, tagsString) {
  25899. if (!tagsString) {
  25900. return;
  25901. }
  25902. var tags = tagsString.split(" ");
  25903. for (var t in tags) {
  25904. Tags._AddTagTo(obj, tags[t]);
  25905. }
  25906. };
  25907. Tags._AddTagTo = function (obj, tag) {
  25908. tag = tag.trim();
  25909. if (tag === "" || tag === "true" || tag === "false") {
  25910. return;
  25911. }
  25912. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  25913. return;
  25914. }
  25915. Tags.EnableFor(obj);
  25916. obj._tags[tag] = true;
  25917. };
  25918. Tags.RemoveTagsFrom = function (obj, tagsString) {
  25919. if (!Tags.HasTags(obj)) {
  25920. return;
  25921. }
  25922. var tags = tagsString.split(" ");
  25923. for (var t in tags) {
  25924. Tags._RemoveTagFrom(obj, tags[t]);
  25925. }
  25926. };
  25927. Tags._RemoveTagFrom = function (obj, tag) {
  25928. delete obj._tags[tag];
  25929. };
  25930. Tags.MatchesQuery = function (obj, tagsQuery) {
  25931. if (tagsQuery === undefined) {
  25932. return true;
  25933. }
  25934. if (tagsQuery === "") {
  25935. return Tags.HasTags(obj);
  25936. }
  25937. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  25938. };
  25939. return Tags;
  25940. })();
  25941. BABYLON.Tags = Tags;
  25942. })(BABYLON || (BABYLON = {}));
  25943. //# sourceMappingURL=babylon.tags.js.map
  25944. var BABYLON;
  25945. (function (BABYLON) {
  25946. var Internals;
  25947. (function (Internals) {
  25948. var AndOrNotEvaluator = (function () {
  25949. function AndOrNotEvaluator() {
  25950. }
  25951. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  25952. if (!query.match(/\([^\(\)]*\)/g)) {
  25953. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  25954. }
  25955. else {
  25956. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  25957. // remove parenthesis
  25958. r = r.slice(1, r.length - 1);
  25959. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  25960. });
  25961. }
  25962. if (query === "true") {
  25963. return true;
  25964. }
  25965. if (query === "false") {
  25966. return false;
  25967. }
  25968. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  25969. };
  25970. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  25971. evaluateCallback = evaluateCallback || (function (r) {
  25972. return r === "true" ? true : false;
  25973. });
  25974. var result;
  25975. var or = parenthesisContent.split("||");
  25976. for (var i in or) {
  25977. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  25978. var and = ori.split("&&");
  25979. if (and.length > 1) {
  25980. for (var j = 0; j < and.length; ++j) {
  25981. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  25982. if (andj !== "true" && andj !== "false") {
  25983. if (andj[0] === "!") {
  25984. result = !evaluateCallback(andj.substring(1));
  25985. }
  25986. else {
  25987. result = evaluateCallback(andj);
  25988. }
  25989. }
  25990. else {
  25991. result = andj === "true" ? true : false;
  25992. }
  25993. if (!result) {
  25994. ori = "false";
  25995. break;
  25996. }
  25997. }
  25998. }
  25999. if (result || ori === "true") {
  26000. result = true;
  26001. break;
  26002. }
  26003. // result equals false (or undefined)
  26004. if (ori !== "true" && ori !== "false") {
  26005. if (ori[0] === "!") {
  26006. result = !evaluateCallback(ori.substring(1));
  26007. }
  26008. else {
  26009. result = evaluateCallback(ori);
  26010. }
  26011. }
  26012. else {
  26013. result = ori === "true" ? true : false;
  26014. }
  26015. }
  26016. // the whole parenthesis scope is replaced by 'true' or 'false'
  26017. return result ? "true" : "false";
  26018. };
  26019. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  26020. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  26021. // remove whitespaces
  26022. r = r.replace(/[\s]/g, function () { return ""; });
  26023. return r.length % 2 ? "!" : "";
  26024. });
  26025. booleanString = booleanString.trim();
  26026. if (booleanString === "!true") {
  26027. booleanString = "false";
  26028. }
  26029. else if (booleanString === "!false") {
  26030. booleanString = "true";
  26031. }
  26032. return booleanString;
  26033. };
  26034. return AndOrNotEvaluator;
  26035. })();
  26036. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  26037. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26038. })(BABYLON || (BABYLON = {}));
  26039. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  26040. var BABYLON;
  26041. (function (BABYLON) {
  26042. var PostProcessRenderPass = (function () {
  26043. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  26044. this._enabled = true;
  26045. this._refCount = 0;
  26046. this._name = name;
  26047. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  26048. this.setRenderList(renderList);
  26049. this._renderTexture.onBeforeRender = beforeRender;
  26050. this._renderTexture.onAfterRender = afterRender;
  26051. this._scene = scene;
  26052. this._renderList = renderList;
  26053. }
  26054. // private
  26055. PostProcessRenderPass.prototype._incRefCount = function () {
  26056. if (this._refCount === 0) {
  26057. this._scene.customRenderTargets.push(this._renderTexture);
  26058. }
  26059. return ++this._refCount;
  26060. };
  26061. PostProcessRenderPass.prototype._decRefCount = function () {
  26062. this._refCount--;
  26063. if (this._refCount <= 0) {
  26064. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  26065. }
  26066. return this._refCount;
  26067. };
  26068. PostProcessRenderPass.prototype._update = function () {
  26069. this.setRenderList(this._renderList);
  26070. };
  26071. // public
  26072. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  26073. this._renderTexture.renderList = renderList;
  26074. };
  26075. PostProcessRenderPass.prototype.getRenderTexture = function () {
  26076. return this._renderTexture;
  26077. };
  26078. return PostProcessRenderPass;
  26079. })();
  26080. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  26081. })(BABYLON || (BABYLON = {}));
  26082. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  26083. var BABYLON;
  26084. (function (BABYLON) {
  26085. var PostProcessRenderEffect = (function () {
  26086. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  26087. this._engine = engine;
  26088. this._name = name;
  26089. this._singleInstance = singleInstance || true;
  26090. this._getPostProcess = getPostProcess;
  26091. this._cameras = [];
  26092. this._indicesForCamera = [];
  26093. this._postProcesses = {};
  26094. this._renderPasses = {};
  26095. this._renderEffectAsPasses = {};
  26096. }
  26097. PostProcessRenderEffect.prototype._update = function () {
  26098. for (var renderPassName in this._renderPasses) {
  26099. this._renderPasses[renderPassName]._update();
  26100. }
  26101. };
  26102. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  26103. this._renderPasses[renderPass._name] = renderPass;
  26104. this._linkParameters();
  26105. };
  26106. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  26107. delete this._renderPasses[renderPass._name];
  26108. this._linkParameters();
  26109. };
  26110. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  26111. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  26112. this._linkParameters();
  26113. };
  26114. PostProcessRenderEffect.prototype.getPass = function (passName) {
  26115. for (var renderPassName in this._renderPasses) {
  26116. if (renderPassName === passName) {
  26117. return this._renderPasses[passName];
  26118. }
  26119. }
  26120. };
  26121. PostProcessRenderEffect.prototype.emptyPasses = function () {
  26122. this._renderPasses = {};
  26123. this._linkParameters();
  26124. };
  26125. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  26126. var cameraKey;
  26127. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26128. for (var i = 0; i < _cam.length; i++) {
  26129. var camera = _cam[i];
  26130. var cameraName = camera.name;
  26131. if (this._singleInstance) {
  26132. cameraKey = 0;
  26133. }
  26134. else {
  26135. cameraKey = cameraName;
  26136. }
  26137. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  26138. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  26139. if (!this._indicesForCamera[cameraName]) {
  26140. this._indicesForCamera[cameraName] = [];
  26141. }
  26142. this._indicesForCamera[cameraName].push(index);
  26143. if (this._cameras.indexOf(camera) === -1) {
  26144. this._cameras[cameraName] = camera;
  26145. }
  26146. for (var passName in this._renderPasses) {
  26147. this._renderPasses[passName]._incRefCount();
  26148. }
  26149. }
  26150. this._linkParameters();
  26151. };
  26152. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  26153. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26154. for (var i = 0; i < _cam.length; i++) {
  26155. var camera = _cam[i];
  26156. var cameraName = camera.name;
  26157. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26158. var index = this._cameras.indexOf(cameraName);
  26159. this._indicesForCamera.splice(index, 1);
  26160. this._cameras.splice(index, 1);
  26161. for (var passName in this._renderPasses) {
  26162. this._renderPasses[passName]._decRefCount();
  26163. }
  26164. }
  26165. };
  26166. PostProcessRenderEffect.prototype._enable = function (cameras) {
  26167. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26168. for (var i = 0; i < _cam.length; i++) {
  26169. var camera = _cam[i];
  26170. var cameraName = camera.name;
  26171. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  26172. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  26173. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  26174. }
  26175. }
  26176. for (var passName in this._renderPasses) {
  26177. this._renderPasses[passName]._incRefCount();
  26178. }
  26179. }
  26180. };
  26181. PostProcessRenderEffect.prototype._disable = function (cameras) {
  26182. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26183. for (var i = 0; i < _cam.length; i++) {
  26184. var camera = _cam[i];
  26185. var cameraName = camera.Name;
  26186. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26187. for (var passName in this._renderPasses) {
  26188. this._renderPasses[passName]._decRefCount();
  26189. }
  26190. }
  26191. };
  26192. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  26193. if (this._singleInstance) {
  26194. return this._postProcesses[0];
  26195. }
  26196. else {
  26197. return this._postProcesses[camera.name];
  26198. }
  26199. };
  26200. PostProcessRenderEffect.prototype._linkParameters = function () {
  26201. var _this = this;
  26202. for (var index in this._postProcesses) {
  26203. if (this.applyParameters) {
  26204. this.applyParameters(this._postProcesses[index]);
  26205. }
  26206. this._postProcesses[index].onBeforeRender = function (effect) {
  26207. _this._linkTextures(effect);
  26208. };
  26209. }
  26210. };
  26211. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  26212. for (var renderPassName in this._renderPasses) {
  26213. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  26214. }
  26215. for (var renderEffectName in this._renderEffectAsPasses) {
  26216. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  26217. }
  26218. };
  26219. return PostProcessRenderEffect;
  26220. })();
  26221. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  26222. })(BABYLON || (BABYLON = {}));
  26223. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  26224. var BABYLON;
  26225. (function (BABYLON) {
  26226. var PostProcessRenderPipeline = (function () {
  26227. function PostProcessRenderPipeline(engine, name) {
  26228. this._engine = engine;
  26229. this._name = name;
  26230. this._renderEffects = {};
  26231. this._renderEffectsForIsolatedPass = {};
  26232. this._cameras = [];
  26233. }
  26234. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  26235. this._renderEffects[renderEffect._name] = renderEffect;
  26236. };
  26237. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  26238. var renderEffects = this._renderEffects[renderEffectName];
  26239. if (!renderEffects) {
  26240. return;
  26241. }
  26242. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26243. };
  26244. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  26245. var renderEffects = this._renderEffects[renderEffectName];
  26246. if (!renderEffects) {
  26247. return;
  26248. }
  26249. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26250. };
  26251. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  26252. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26253. var indicesToDelete = [];
  26254. for (var i = 0; i < _cam.length; i++) {
  26255. var camera = _cam[i];
  26256. var cameraName = camera.name;
  26257. if (this._cameras.indexOf(camera) === -1) {
  26258. this._cameras[cameraName] = camera;
  26259. }
  26260. else if (unique) {
  26261. indicesToDelete.push(i);
  26262. }
  26263. }
  26264. for (var i = 0; i < indicesToDelete.length; i++) {
  26265. cameras.splice(indicesToDelete[i], 1);
  26266. }
  26267. for (var renderEffectName in this._renderEffects) {
  26268. this._renderEffects[renderEffectName]._attachCameras(_cam);
  26269. }
  26270. };
  26271. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  26272. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26273. for (var renderEffectName in this._renderEffects) {
  26274. this._renderEffects[renderEffectName]._detachCameras(_cam);
  26275. }
  26276. for (var i = 0; i < _cam.length; i++) {
  26277. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  26278. }
  26279. };
  26280. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  26281. var _this = this;
  26282. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26283. var pass = null;
  26284. for (var renderEffectName in this._renderEffects) {
  26285. pass = this._renderEffects[renderEffectName].getPass(passName);
  26286. if (pass != null) {
  26287. break;
  26288. }
  26289. }
  26290. if (pass === null) {
  26291. return;
  26292. }
  26293. for (var renderEffectName in this._renderEffects) {
  26294. this._renderEffects[renderEffectName]._disable(_cam);
  26295. }
  26296. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  26297. for (var i = 0; i < _cam.length; i++) {
  26298. var camera = _cam[i];
  26299. var cameraName = camera.name;
  26300. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
  26301. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  26302. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  26303. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  26304. }
  26305. };
  26306. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  26307. var _this = this;
  26308. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26309. for (var i = 0; i < _cam.length; i++) {
  26310. var camera = _cam[i];
  26311. var cameraName = camera.name;
  26312. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () { return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true); });
  26313. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  26314. }
  26315. for (var renderEffectName in this._renderEffects) {
  26316. this._renderEffects[renderEffectName]._enable(_cam);
  26317. }
  26318. };
  26319. PostProcessRenderPipeline.prototype._update = function () {
  26320. for (var renderEffectName in this._renderEffects) {
  26321. this._renderEffects[renderEffectName]._update();
  26322. }
  26323. for (var i = 0; i < this._cameras.length; i++) {
  26324. var cameraName = this._cameras[i].name;
  26325. if (this._renderEffectsForIsolatedPass[cameraName]) {
  26326. this._renderEffectsForIsolatedPass[cameraName]._update();
  26327. }
  26328. }
  26329. };
  26330. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  26331. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  26332. return PostProcessRenderPipeline;
  26333. })();
  26334. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  26335. })(BABYLON || (BABYLON = {}));
  26336. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  26337. var BABYLON;
  26338. (function (BABYLON) {
  26339. var PostProcessRenderPipelineManager = (function () {
  26340. function PostProcessRenderPipelineManager() {
  26341. this._renderPipelines = {};
  26342. }
  26343. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  26344. this._renderPipelines[renderPipeline._name] = renderPipeline;
  26345. };
  26346. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  26347. var renderPipeline = this._renderPipelines[renderPipelineName];
  26348. if (!renderPipeline) {
  26349. return;
  26350. }
  26351. renderPipeline._attachCameras(cameras, unique);
  26352. };
  26353. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  26354. var renderPipeline = this._renderPipelines[renderPipelineName];
  26355. if (!renderPipeline) {
  26356. return;
  26357. }
  26358. renderPipeline._detachCameras(cameras);
  26359. };
  26360. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26361. var renderPipeline = this._renderPipelines[renderPipelineName];
  26362. if (!renderPipeline) {
  26363. return;
  26364. }
  26365. renderPipeline._enableEffect(renderEffectName, cameras);
  26366. };
  26367. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26368. var renderPipeline = this._renderPipelines[renderPipelineName];
  26369. if (!renderPipeline) {
  26370. return;
  26371. }
  26372. renderPipeline._disableEffect(renderEffectName, cameras);
  26373. };
  26374. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  26375. var renderPipeline = this._renderPipelines[renderPipelineName];
  26376. if (!renderPipeline) {
  26377. return;
  26378. }
  26379. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  26380. };
  26381. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  26382. var renderPipeline = this._renderPipelines[renderPipelineName];
  26383. if (!renderPipeline) {
  26384. return;
  26385. }
  26386. renderPipeline._disableDisplayOnlyPass(cameras);
  26387. };
  26388. PostProcessRenderPipelineManager.prototype.update = function () {
  26389. for (var renderPipelineName in this._renderPipelines) {
  26390. this._renderPipelines[renderPipelineName]._update();
  26391. }
  26392. };
  26393. return PostProcessRenderPipelineManager;
  26394. })();
  26395. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  26396. })(BABYLON || (BABYLON = {}));
  26397. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  26398. var BABYLON;
  26399. (function (BABYLON) {
  26400. var DisplayPassPostProcess = (function (_super) {
  26401. __extends(DisplayPassPostProcess, _super);
  26402. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  26403. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  26404. }
  26405. return DisplayPassPostProcess;
  26406. })(BABYLON.PostProcess);
  26407. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  26408. })(BABYLON || (BABYLON = {}));
  26409. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  26410. var BABYLON;
  26411. (function (BABYLON) {
  26412. var BoundingBoxRenderer = (function () {
  26413. function BoundingBoxRenderer(scene) {
  26414. this.frontColor = new BABYLON.Color3(1, 1, 1);
  26415. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  26416. this.showBackLines = true;
  26417. this.renderList = new BABYLON.SmartArray(32);
  26418. this._scene = scene;
  26419. }
  26420. BoundingBoxRenderer.prototype._prepareRessources = function () {
  26421. if (this._colorShader) {
  26422. return;
  26423. }
  26424. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  26425. attributes: ["position"],
  26426. uniforms: ["worldViewProjection", "color"]
  26427. });
  26428. var engine = this._scene.getEngine();
  26429. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  26430. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  26431. 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]);
  26432. };
  26433. BoundingBoxRenderer.prototype.reset = function () {
  26434. this.renderList.reset();
  26435. };
  26436. BoundingBoxRenderer.prototype.render = function () {
  26437. if (this.renderList.length === 0) {
  26438. return;
  26439. }
  26440. this._prepareRessources();
  26441. if (!this._colorShader.isReady()) {
  26442. return;
  26443. }
  26444. var engine = this._scene.getEngine();
  26445. engine.setDepthWrite(false);
  26446. this._colorShader._preBind();
  26447. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  26448. var boundingBox = this.renderList.data[boundingBoxIndex];
  26449. var min = boundingBox.minimum;
  26450. var max = boundingBox.maximum;
  26451. var diff = max.subtract(min);
  26452. var median = min.add(diff.scale(0.5));
  26453. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  26454. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  26455. .multiply(boundingBox.getWorldMatrix());
  26456. // VBOs
  26457. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  26458. if (this.showBackLines) {
  26459. // Back
  26460. engine.setDepthFunctionToGreaterOrEqual();
  26461. this._scene.resetCachedMaterial();
  26462. this._colorShader.setColor4("color", this.backColor.toColor4());
  26463. this._colorShader.bind(worldMatrix);
  26464. // Draw order
  26465. engine.draw(false, 0, 24);
  26466. }
  26467. // Front
  26468. engine.setDepthFunctionToLess();
  26469. this._scene.resetCachedMaterial();
  26470. this._colorShader.setColor4("color", this.frontColor.toColor4());
  26471. this._colorShader.bind(worldMatrix);
  26472. // Draw order
  26473. engine.draw(false, 0, 24);
  26474. }
  26475. this._colorShader.unbind();
  26476. engine.setDepthFunctionToLessOrEqual();
  26477. engine.setDepthWrite(true);
  26478. };
  26479. BoundingBoxRenderer.prototype.dispose = function () {
  26480. if (!this._colorShader) {
  26481. return;
  26482. }
  26483. this._colorShader.dispose();
  26484. this._vb.dispose();
  26485. this._scene.getEngine()._releaseBuffer(this._ib);
  26486. };
  26487. return BoundingBoxRenderer;
  26488. })();
  26489. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  26490. })(BABYLON || (BABYLON = {}));
  26491. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  26492. var BABYLON;
  26493. (function (BABYLON) {
  26494. var Condition = (function () {
  26495. function Condition(actionManager) {
  26496. this._actionManager = actionManager;
  26497. }
  26498. Condition.prototype.isValid = function () {
  26499. return true;
  26500. };
  26501. Condition.prototype._getProperty = function (propertyPath) {
  26502. return this._actionManager._getProperty(propertyPath);
  26503. };
  26504. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  26505. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26506. };
  26507. return Condition;
  26508. })();
  26509. BABYLON.Condition = Condition;
  26510. var ValueCondition = (function (_super) {
  26511. __extends(ValueCondition, _super);
  26512. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  26513. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  26514. _super.call(this, actionManager);
  26515. this.propertyPath = propertyPath;
  26516. this.value = value;
  26517. this.operator = operator;
  26518. this._target = this._getEffectiveTarget(target, this.propertyPath);
  26519. this._property = this._getProperty(this.propertyPath);
  26520. }
  26521. Object.defineProperty(ValueCondition, "IsEqual", {
  26522. get: function () {
  26523. return ValueCondition._IsEqual;
  26524. },
  26525. enumerable: true,
  26526. configurable: true
  26527. });
  26528. Object.defineProperty(ValueCondition, "IsDifferent", {
  26529. get: function () {
  26530. return ValueCondition._IsDifferent;
  26531. },
  26532. enumerable: true,
  26533. configurable: true
  26534. });
  26535. Object.defineProperty(ValueCondition, "IsGreater", {
  26536. get: function () {
  26537. return ValueCondition._IsGreater;
  26538. },
  26539. enumerable: true,
  26540. configurable: true
  26541. });
  26542. Object.defineProperty(ValueCondition, "IsLesser", {
  26543. get: function () {
  26544. return ValueCondition._IsLesser;
  26545. },
  26546. enumerable: true,
  26547. configurable: true
  26548. });
  26549. // Methods
  26550. ValueCondition.prototype.isValid = function () {
  26551. switch (this.operator) {
  26552. case ValueCondition.IsGreater:
  26553. return this._target[this._property] > this.value;
  26554. case ValueCondition.IsLesser:
  26555. return this._target[this._property] < this.value;
  26556. case ValueCondition.IsEqual:
  26557. case ValueCondition.IsDifferent:
  26558. var check;
  26559. if (this.value.equals) {
  26560. check = this.value.equals(this._target[this._property]);
  26561. }
  26562. else {
  26563. check = this.value === this._target[this._property];
  26564. }
  26565. return this.operator === ValueCondition.IsEqual ? check : !check;
  26566. }
  26567. return false;
  26568. };
  26569. // Statics
  26570. ValueCondition._IsEqual = 0;
  26571. ValueCondition._IsDifferent = 1;
  26572. ValueCondition._IsGreater = 2;
  26573. ValueCondition._IsLesser = 3;
  26574. return ValueCondition;
  26575. })(Condition);
  26576. BABYLON.ValueCondition = ValueCondition;
  26577. var PredicateCondition = (function (_super) {
  26578. __extends(PredicateCondition, _super);
  26579. function PredicateCondition(actionManager, predicate) {
  26580. _super.call(this, actionManager);
  26581. this.predicate = predicate;
  26582. }
  26583. PredicateCondition.prototype.isValid = function () {
  26584. return this.predicate();
  26585. };
  26586. return PredicateCondition;
  26587. })(Condition);
  26588. BABYLON.PredicateCondition = PredicateCondition;
  26589. var StateCondition = (function (_super) {
  26590. __extends(StateCondition, _super);
  26591. function StateCondition(actionManager, target, value) {
  26592. _super.call(this, actionManager);
  26593. this.value = value;
  26594. this._target = target;
  26595. }
  26596. // Methods
  26597. StateCondition.prototype.isValid = function () {
  26598. return this._target.state === this.value;
  26599. };
  26600. return StateCondition;
  26601. })(Condition);
  26602. BABYLON.StateCondition = StateCondition;
  26603. })(BABYLON || (BABYLON = {}));
  26604. //# sourceMappingURL=babylon.condition.js.map
  26605. var BABYLON;
  26606. (function (BABYLON) {
  26607. var Action = (function () {
  26608. function Action(triggerOptions, condition) {
  26609. this.triggerOptions = triggerOptions;
  26610. if (triggerOptions.parameter) {
  26611. this.trigger = triggerOptions.trigger;
  26612. this._triggerParameter = triggerOptions.parameter;
  26613. }
  26614. else {
  26615. this.trigger = triggerOptions;
  26616. }
  26617. this._nextActiveAction = this;
  26618. this._condition = condition;
  26619. }
  26620. // Methods
  26621. Action.prototype._prepare = function () {
  26622. };
  26623. Action.prototype.getTriggerParameter = function () {
  26624. return this._triggerParameter;
  26625. };
  26626. Action.prototype._executeCurrent = function (evt) {
  26627. if (this._nextActiveAction._condition) {
  26628. var condition = this._nextActiveAction._condition;
  26629. var currentRenderId = this._actionManager.getScene().getRenderId();
  26630. // We cache the current evaluation for the current frame
  26631. if (condition._evaluationId === currentRenderId) {
  26632. if (!condition._currentResult) {
  26633. return;
  26634. }
  26635. }
  26636. else {
  26637. condition._evaluationId = currentRenderId;
  26638. if (!condition.isValid()) {
  26639. condition._currentResult = false;
  26640. return;
  26641. }
  26642. condition._currentResult = true;
  26643. }
  26644. }
  26645. this._nextActiveAction.execute(evt);
  26646. if (this._nextActiveAction._child) {
  26647. if (!this._nextActiveAction._child._actionManager) {
  26648. this._nextActiveAction._child._actionManager = this._actionManager;
  26649. }
  26650. this._nextActiveAction = this._nextActiveAction._child;
  26651. }
  26652. else {
  26653. this._nextActiveAction = this;
  26654. }
  26655. };
  26656. Action.prototype.execute = function (evt) {
  26657. };
  26658. Action.prototype.then = function (action) {
  26659. this._child = action;
  26660. action._actionManager = this._actionManager;
  26661. action._prepare();
  26662. return action;
  26663. };
  26664. Action.prototype._getProperty = function (propertyPath) {
  26665. return this._actionManager._getProperty(propertyPath);
  26666. };
  26667. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  26668. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26669. };
  26670. return Action;
  26671. })();
  26672. BABYLON.Action = Action;
  26673. })(BABYLON || (BABYLON = {}));
  26674. //# sourceMappingURL=babylon.action.js.map
  26675. var BABYLON;
  26676. (function (BABYLON) {
  26677. /**
  26678. * ActionEvent is the event beint sent when an action is triggered.
  26679. */
  26680. var ActionEvent = (function () {
  26681. /**
  26682. * @constructor
  26683. * @param source The mesh that triggered the action.
  26684. * @param pointerX the X mouse cursor position at the time of the event
  26685. * @param pointerY the Y mouse cursor position at the time of the event
  26686. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  26687. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  26688. */
  26689. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  26690. this.source = source;
  26691. this.pointerX = pointerX;
  26692. this.pointerY = pointerY;
  26693. this.meshUnderPointer = meshUnderPointer;
  26694. this.sourceEvent = sourceEvent;
  26695. }
  26696. /**
  26697. * Helper function to auto-create an ActionEvent from a source mesh.
  26698. * @param source the source mesh that triggered the event
  26699. * @param evt {Event} The original (browser) event
  26700. */
  26701. ActionEvent.CreateNew = function (source, evt) {
  26702. var scene = source.getScene();
  26703. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  26704. };
  26705. /**
  26706. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  26707. * @param scene the scene where the event occurred
  26708. * @param evt {Event} The original (browser) event
  26709. */
  26710. ActionEvent.CreateNewFromScene = function (scene, evt) {
  26711. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  26712. };
  26713. return ActionEvent;
  26714. })();
  26715. BABYLON.ActionEvent = ActionEvent;
  26716. /**
  26717. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  26718. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  26719. */
  26720. var ActionManager = (function () {
  26721. function ActionManager(scene) {
  26722. // Members
  26723. this.actions = new Array();
  26724. this._scene = scene;
  26725. scene._actionManagers.push(this);
  26726. }
  26727. Object.defineProperty(ActionManager, "NothingTrigger", {
  26728. get: function () {
  26729. return ActionManager._NothingTrigger;
  26730. },
  26731. enumerable: true,
  26732. configurable: true
  26733. });
  26734. Object.defineProperty(ActionManager, "OnPickTrigger", {
  26735. get: function () {
  26736. return ActionManager._OnPickTrigger;
  26737. },
  26738. enumerable: true,
  26739. configurable: true
  26740. });
  26741. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  26742. get: function () {
  26743. return ActionManager._OnLeftPickTrigger;
  26744. },
  26745. enumerable: true,
  26746. configurable: true
  26747. });
  26748. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  26749. get: function () {
  26750. return ActionManager._OnRightPickTrigger;
  26751. },
  26752. enumerable: true,
  26753. configurable: true
  26754. });
  26755. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  26756. get: function () {
  26757. return ActionManager._OnCenterPickTrigger;
  26758. },
  26759. enumerable: true,
  26760. configurable: true
  26761. });
  26762. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  26763. get: function () {
  26764. return ActionManager._OnPointerOverTrigger;
  26765. },
  26766. enumerable: true,
  26767. configurable: true
  26768. });
  26769. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  26770. get: function () {
  26771. return ActionManager._OnPointerOutTrigger;
  26772. },
  26773. enumerable: true,
  26774. configurable: true
  26775. });
  26776. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  26777. get: function () {
  26778. return ActionManager._OnEveryFrameTrigger;
  26779. },
  26780. enumerable: true,
  26781. configurable: true
  26782. });
  26783. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  26784. get: function () {
  26785. return ActionManager._OnIntersectionEnterTrigger;
  26786. },
  26787. enumerable: true,
  26788. configurable: true
  26789. });
  26790. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  26791. get: function () {
  26792. return ActionManager._OnIntersectionExitTrigger;
  26793. },
  26794. enumerable: true,
  26795. configurable: true
  26796. });
  26797. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  26798. get: function () {
  26799. return ActionManager._OnKeyDownTrigger;
  26800. },
  26801. enumerable: true,
  26802. configurable: true
  26803. });
  26804. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  26805. get: function () {
  26806. return ActionManager._OnKeyUpTrigger;
  26807. },
  26808. enumerable: true,
  26809. configurable: true
  26810. });
  26811. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  26812. get: function () {
  26813. return ActionManager._OnPickUpTrigger;
  26814. },
  26815. enumerable: true,
  26816. configurable: true
  26817. });
  26818. // Methods
  26819. ActionManager.prototype.dispose = function () {
  26820. var index = this._scene._actionManagers.indexOf(this);
  26821. if (index > -1) {
  26822. this._scene._actionManagers.splice(index, 1);
  26823. }
  26824. };
  26825. ActionManager.prototype.getScene = function () {
  26826. return this._scene;
  26827. };
  26828. /**
  26829. * Does this action manager handles actions of any of the given triggers
  26830. * @param {number[]} triggers - the triggers to be tested
  26831. * @return {boolean} whether one (or more) of the triggers is handeled
  26832. */
  26833. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  26834. for (var index = 0; index < this.actions.length; index++) {
  26835. var action = this.actions[index];
  26836. if (triggers.indexOf(action.trigger) > -1) {
  26837. return true;
  26838. }
  26839. }
  26840. return false;
  26841. };
  26842. /**
  26843. * Does this action manager handles actions of a given trigger
  26844. * @param {number} trigger - the trigger to be tested
  26845. * @return {boolean} whether the trigger is handeled
  26846. */
  26847. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  26848. for (var index = 0; index < this.actions.length; index++) {
  26849. var action = this.actions[index];
  26850. if (action.trigger === trigger) {
  26851. return true;
  26852. }
  26853. }
  26854. return false;
  26855. };
  26856. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  26857. /**
  26858. * Does this action manager has pointer triggers
  26859. * @return {boolean} whether or not it has pointer triggers
  26860. */
  26861. get: function () {
  26862. for (var index = 0; index < this.actions.length; index++) {
  26863. var action = this.actions[index];
  26864. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  26865. return true;
  26866. }
  26867. if (action.trigger == ActionManager._OnPickUpTrigger) {
  26868. return true;
  26869. }
  26870. }
  26871. return false;
  26872. },
  26873. enumerable: true,
  26874. configurable: true
  26875. });
  26876. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  26877. /**
  26878. * Does this action manager has pick triggers
  26879. * @return {boolean} whether or not it has pick triggers
  26880. */
  26881. get: function () {
  26882. for (var index = 0; index < this.actions.length; index++) {
  26883. var action = this.actions[index];
  26884. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  26885. return true;
  26886. }
  26887. }
  26888. return false;
  26889. },
  26890. enumerable: true,
  26891. configurable: true
  26892. });
  26893. /**
  26894. * Registers an action to this action manager
  26895. * @param {BABYLON.Action} action - the action to be registered
  26896. * @return {BABYLON.Action} the action amended (prepared) after registration
  26897. */
  26898. ActionManager.prototype.registerAction = function (action) {
  26899. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  26900. if (this.getScene().actionManager !== this) {
  26901. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  26902. return null;
  26903. }
  26904. }
  26905. this.actions.push(action);
  26906. action._actionManager = this;
  26907. action._prepare();
  26908. return action;
  26909. };
  26910. /**
  26911. * Process a specific trigger
  26912. * @param {number} trigger - the trigger to process
  26913. * @param evt {BABYLON.ActionEvent} the event details to be processed
  26914. */
  26915. ActionManager.prototype.processTrigger = function (trigger, evt) {
  26916. for (var index = 0; index < this.actions.length; index++) {
  26917. var action = this.actions[index];
  26918. if (action.trigger === trigger) {
  26919. if (trigger === ActionManager.OnKeyUpTrigger
  26920. || trigger === ActionManager.OnKeyDownTrigger) {
  26921. var parameter = action.getTriggerParameter();
  26922. if (parameter) {
  26923. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  26924. var actualkey = String.fromCharCode(unicode).toLowerCase();
  26925. if (actualkey !== parameter.toLowerCase()) {
  26926. continue;
  26927. }
  26928. }
  26929. }
  26930. action._executeCurrent(evt);
  26931. }
  26932. }
  26933. };
  26934. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  26935. var properties = propertyPath.split(".");
  26936. for (var index = 0; index < properties.length - 1; index++) {
  26937. target = target[properties[index]];
  26938. }
  26939. return target;
  26940. };
  26941. ActionManager.prototype._getProperty = function (propertyPath) {
  26942. var properties = propertyPath.split(".");
  26943. return properties[properties.length - 1];
  26944. };
  26945. // Statics
  26946. ActionManager._NothingTrigger = 0;
  26947. ActionManager._OnPickTrigger = 1;
  26948. ActionManager._OnLeftPickTrigger = 2;
  26949. ActionManager._OnRightPickTrigger = 3;
  26950. ActionManager._OnCenterPickTrigger = 4;
  26951. ActionManager._OnPointerOverTrigger = 5;
  26952. ActionManager._OnPointerOutTrigger = 6;
  26953. ActionManager._OnEveryFrameTrigger = 7;
  26954. ActionManager._OnIntersectionEnterTrigger = 8;
  26955. ActionManager._OnIntersectionExitTrigger = 9;
  26956. ActionManager._OnKeyDownTrigger = 10;
  26957. ActionManager._OnKeyUpTrigger = 11;
  26958. ActionManager._OnPickUpTrigger = 12;
  26959. return ActionManager;
  26960. })();
  26961. BABYLON.ActionManager = ActionManager;
  26962. })(BABYLON || (BABYLON = {}));
  26963. //# sourceMappingURL=babylon.actionManager.js.map
  26964. var BABYLON;
  26965. (function (BABYLON) {
  26966. var InterpolateValueAction = (function (_super) {
  26967. __extends(InterpolateValueAction, _super);
  26968. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  26969. if (duration === void 0) { duration = 1000; }
  26970. _super.call(this, triggerOptions, condition);
  26971. this.propertyPath = propertyPath;
  26972. this.value = value;
  26973. this.duration = duration;
  26974. this.stopOtherAnimations = stopOtherAnimations;
  26975. this._target = target;
  26976. }
  26977. InterpolateValueAction.prototype._prepare = function () {
  26978. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26979. this._property = this._getProperty(this.propertyPath);
  26980. };
  26981. InterpolateValueAction.prototype.execute = function () {
  26982. var scene = this._actionManager.getScene();
  26983. var keys = [
  26984. {
  26985. frame: 0,
  26986. value: this._target[this._property]
  26987. }, {
  26988. frame: 100,
  26989. value: this.value
  26990. }
  26991. ];
  26992. var dataType;
  26993. if (typeof this.value === "number") {
  26994. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  26995. }
  26996. else if (this.value instanceof BABYLON.Color3) {
  26997. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  26998. }
  26999. else if (this.value instanceof BABYLON.Vector3) {
  27000. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  27001. }
  27002. else if (this.value instanceof BABYLON.Matrix) {
  27003. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  27004. }
  27005. else if (this.value instanceof BABYLON.Quaternion) {
  27006. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  27007. }
  27008. else {
  27009. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  27010. return;
  27011. }
  27012. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  27013. animation.setKeys(keys);
  27014. if (this.stopOtherAnimations) {
  27015. scene.stopAnimation(this._target);
  27016. }
  27017. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  27018. };
  27019. return InterpolateValueAction;
  27020. })(BABYLON.Action);
  27021. BABYLON.InterpolateValueAction = InterpolateValueAction;
  27022. })(BABYLON || (BABYLON = {}));
  27023. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  27024. var BABYLON;
  27025. (function (BABYLON) {
  27026. var SwitchBooleanAction = (function (_super) {
  27027. __extends(SwitchBooleanAction, _super);
  27028. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  27029. _super.call(this, triggerOptions, condition);
  27030. this.propertyPath = propertyPath;
  27031. this._target = target;
  27032. }
  27033. SwitchBooleanAction.prototype._prepare = function () {
  27034. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27035. this._property = this._getProperty(this.propertyPath);
  27036. };
  27037. SwitchBooleanAction.prototype.execute = function () {
  27038. this._target[this._property] = !this._target[this._property];
  27039. };
  27040. return SwitchBooleanAction;
  27041. })(BABYLON.Action);
  27042. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  27043. var SetStateAction = (function (_super) {
  27044. __extends(SetStateAction, _super);
  27045. function SetStateAction(triggerOptions, target, value, condition) {
  27046. _super.call(this, triggerOptions, condition);
  27047. this.value = value;
  27048. this._target = target;
  27049. }
  27050. SetStateAction.prototype.execute = function () {
  27051. this._target.state = this.value;
  27052. };
  27053. return SetStateAction;
  27054. })(BABYLON.Action);
  27055. BABYLON.SetStateAction = SetStateAction;
  27056. var SetValueAction = (function (_super) {
  27057. __extends(SetValueAction, _super);
  27058. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  27059. _super.call(this, triggerOptions, condition);
  27060. this.propertyPath = propertyPath;
  27061. this.value = value;
  27062. this._target = target;
  27063. }
  27064. SetValueAction.prototype._prepare = function () {
  27065. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27066. this._property = this._getProperty(this.propertyPath);
  27067. };
  27068. SetValueAction.prototype.execute = function () {
  27069. this._target[this._property] = this.value;
  27070. };
  27071. return SetValueAction;
  27072. })(BABYLON.Action);
  27073. BABYLON.SetValueAction = SetValueAction;
  27074. var IncrementValueAction = (function (_super) {
  27075. __extends(IncrementValueAction, _super);
  27076. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  27077. _super.call(this, triggerOptions, condition);
  27078. this.propertyPath = propertyPath;
  27079. this.value = value;
  27080. this._target = target;
  27081. }
  27082. IncrementValueAction.prototype._prepare = function () {
  27083. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27084. this._property = this._getProperty(this.propertyPath);
  27085. if (typeof this._target[this._property] !== "number") {
  27086. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  27087. }
  27088. };
  27089. IncrementValueAction.prototype.execute = function () {
  27090. this._target[this._property] += this.value;
  27091. };
  27092. return IncrementValueAction;
  27093. })(BABYLON.Action);
  27094. BABYLON.IncrementValueAction = IncrementValueAction;
  27095. var PlayAnimationAction = (function (_super) {
  27096. __extends(PlayAnimationAction, _super);
  27097. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  27098. _super.call(this, triggerOptions, condition);
  27099. this.from = from;
  27100. this.to = to;
  27101. this.loop = loop;
  27102. this._target = target;
  27103. }
  27104. PlayAnimationAction.prototype._prepare = function () {
  27105. };
  27106. PlayAnimationAction.prototype.execute = function () {
  27107. var scene = this._actionManager.getScene();
  27108. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  27109. };
  27110. return PlayAnimationAction;
  27111. })(BABYLON.Action);
  27112. BABYLON.PlayAnimationAction = PlayAnimationAction;
  27113. var StopAnimationAction = (function (_super) {
  27114. __extends(StopAnimationAction, _super);
  27115. function StopAnimationAction(triggerOptions, target, condition) {
  27116. _super.call(this, triggerOptions, condition);
  27117. this._target = target;
  27118. }
  27119. StopAnimationAction.prototype._prepare = function () {
  27120. };
  27121. StopAnimationAction.prototype.execute = function () {
  27122. var scene = this._actionManager.getScene();
  27123. scene.stopAnimation(this._target);
  27124. };
  27125. return StopAnimationAction;
  27126. })(BABYLON.Action);
  27127. BABYLON.StopAnimationAction = StopAnimationAction;
  27128. var DoNothingAction = (function (_super) {
  27129. __extends(DoNothingAction, _super);
  27130. function DoNothingAction(triggerOptions, condition) {
  27131. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  27132. _super.call(this, triggerOptions, condition);
  27133. }
  27134. DoNothingAction.prototype.execute = function () {
  27135. };
  27136. return DoNothingAction;
  27137. })(BABYLON.Action);
  27138. BABYLON.DoNothingAction = DoNothingAction;
  27139. var CombineAction = (function (_super) {
  27140. __extends(CombineAction, _super);
  27141. function CombineAction(triggerOptions, children, condition) {
  27142. _super.call(this, triggerOptions, condition);
  27143. this.children = children;
  27144. }
  27145. CombineAction.prototype._prepare = function () {
  27146. for (var index = 0; index < this.children.length; index++) {
  27147. this.children[index]._actionManager = this._actionManager;
  27148. this.children[index]._prepare();
  27149. }
  27150. };
  27151. CombineAction.prototype.execute = function (evt) {
  27152. for (var index = 0; index < this.children.length; index++) {
  27153. this.children[index].execute(evt);
  27154. }
  27155. };
  27156. return CombineAction;
  27157. })(BABYLON.Action);
  27158. BABYLON.CombineAction = CombineAction;
  27159. var ExecuteCodeAction = (function (_super) {
  27160. __extends(ExecuteCodeAction, _super);
  27161. function ExecuteCodeAction(triggerOptions, func, condition) {
  27162. _super.call(this, triggerOptions, condition);
  27163. this.func = func;
  27164. }
  27165. ExecuteCodeAction.prototype.execute = function (evt) {
  27166. this.func(evt);
  27167. };
  27168. return ExecuteCodeAction;
  27169. })(BABYLON.Action);
  27170. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  27171. var SetParentAction = (function (_super) {
  27172. __extends(SetParentAction, _super);
  27173. function SetParentAction(triggerOptions, target, parent, condition) {
  27174. _super.call(this, triggerOptions, condition);
  27175. this._target = target;
  27176. this._parent = parent;
  27177. }
  27178. SetParentAction.prototype._prepare = function () {
  27179. };
  27180. SetParentAction.prototype.execute = function () {
  27181. if (this._target.parent === this._parent) {
  27182. return;
  27183. }
  27184. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  27185. invertParentWorldMatrix.invert();
  27186. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  27187. this._target.parent = this._parent;
  27188. };
  27189. return SetParentAction;
  27190. })(BABYLON.Action);
  27191. BABYLON.SetParentAction = SetParentAction;
  27192. var PlaySoundAction = (function (_super) {
  27193. __extends(PlaySoundAction, _super);
  27194. function PlaySoundAction(triggerOptions, sound, condition) {
  27195. _super.call(this, triggerOptions, condition);
  27196. this._sound = sound;
  27197. }
  27198. PlaySoundAction.prototype._prepare = function () {
  27199. };
  27200. PlaySoundAction.prototype.execute = function () {
  27201. if (this._sound !== undefined)
  27202. this._sound.play();
  27203. };
  27204. return PlaySoundAction;
  27205. })(BABYLON.Action);
  27206. BABYLON.PlaySoundAction = PlaySoundAction;
  27207. var StopSoundAction = (function (_super) {
  27208. __extends(StopSoundAction, _super);
  27209. function StopSoundAction(triggerOptions, sound, condition) {
  27210. _super.call(this, triggerOptions, condition);
  27211. this._sound = sound;
  27212. }
  27213. StopSoundAction.prototype._prepare = function () {
  27214. };
  27215. StopSoundAction.prototype.execute = function () {
  27216. if (this._sound !== undefined)
  27217. this._sound.stop();
  27218. };
  27219. return StopSoundAction;
  27220. })(BABYLON.Action);
  27221. BABYLON.StopSoundAction = StopSoundAction;
  27222. })(BABYLON || (BABYLON = {}));
  27223. //# sourceMappingURL=babylon.directActions.js.map
  27224. var BABYLON;
  27225. (function (BABYLON) {
  27226. var Geometry = (function () {
  27227. function Geometry(id, scene, vertexData, updatable, mesh) {
  27228. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27229. this._totalVertices = 0;
  27230. this._indices = [];
  27231. this._isDisposed = false;
  27232. this.id = id;
  27233. this._engine = scene.getEngine();
  27234. this._meshes = [];
  27235. this._scene = scene;
  27236. // vertexData
  27237. if (vertexData) {
  27238. this.setAllVerticesData(vertexData, updatable);
  27239. }
  27240. else {
  27241. this._totalVertices = 0;
  27242. this._indices = [];
  27243. }
  27244. // applyToMesh
  27245. if (mesh) {
  27246. this.applyToMesh(mesh);
  27247. mesh.computeWorldMatrix(true);
  27248. }
  27249. }
  27250. Geometry.prototype.getScene = function () {
  27251. return this._scene;
  27252. };
  27253. Geometry.prototype.getEngine = function () {
  27254. return this._engine;
  27255. };
  27256. Geometry.prototype.isReady = function () {
  27257. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  27258. };
  27259. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  27260. vertexData.applyToGeometry(this, updatable);
  27261. this.notifyUpdate();
  27262. };
  27263. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27264. this._vertexBuffers = this._vertexBuffers || {};
  27265. if (this._vertexBuffers[kind]) {
  27266. this._vertexBuffers[kind].dispose();
  27267. }
  27268. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  27269. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27270. stride = this._vertexBuffers[kind].getStrideSize();
  27271. this._totalVertices = data.length / stride;
  27272. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27273. var meshes = this._meshes;
  27274. var numOfMeshes = meshes.length;
  27275. for (var index = 0; index < numOfMeshes; index++) {
  27276. var mesh = meshes[index];
  27277. mesh._resetPointsArrayCache();
  27278. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27279. mesh._createGlobalSubMesh();
  27280. mesh.computeWorldMatrix(true);
  27281. }
  27282. }
  27283. this.notifyUpdate(kind);
  27284. };
  27285. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  27286. var vertexBuffer = this.getVertexBuffer(kind);
  27287. if (!vertexBuffer) {
  27288. return;
  27289. }
  27290. vertexBuffer.updateDirectly(data, offset);
  27291. this.notifyUpdate(kind);
  27292. };
  27293. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  27294. var vertexBuffer = this.getVertexBuffer(kind);
  27295. if (!vertexBuffer) {
  27296. return;
  27297. }
  27298. vertexBuffer.update(data);
  27299. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27300. var extend;
  27301. var stride = vertexBuffer.getStrideSize();
  27302. this._totalVertices = data.length / stride;
  27303. if (updateExtends) {
  27304. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27305. }
  27306. var meshes = this._meshes;
  27307. var numOfMeshes = meshes.length;
  27308. for (var index = 0; index < numOfMeshes; index++) {
  27309. var mesh = meshes[index];
  27310. mesh._resetPointsArrayCache();
  27311. if (updateExtends) {
  27312. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27313. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27314. var subMesh = mesh.subMeshes[subIndex];
  27315. subMesh.refreshBoundingInfo();
  27316. }
  27317. }
  27318. }
  27319. }
  27320. this.notifyUpdate(kind);
  27321. };
  27322. Geometry.prototype.getTotalVertices = function () {
  27323. if (!this.isReady()) {
  27324. return 0;
  27325. }
  27326. return this._totalVertices;
  27327. };
  27328. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  27329. var vertexBuffer = this.getVertexBuffer(kind);
  27330. if (!vertexBuffer) {
  27331. return null;
  27332. }
  27333. var orig = vertexBuffer.getData();
  27334. if (!copyWhenShared || this._meshes.length === 1) {
  27335. return orig;
  27336. }
  27337. else {
  27338. var len = orig.length;
  27339. var copy = [];
  27340. for (var i = 0; i < len; i++) {
  27341. copy.push(orig[i]);
  27342. }
  27343. return copy;
  27344. }
  27345. };
  27346. Geometry.prototype.getVertexBuffer = function (kind) {
  27347. if (!this.isReady()) {
  27348. return null;
  27349. }
  27350. return this._vertexBuffers[kind];
  27351. };
  27352. Geometry.prototype.getVertexBuffers = function () {
  27353. if (!this.isReady()) {
  27354. return null;
  27355. }
  27356. return this._vertexBuffers;
  27357. };
  27358. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27359. if (!this._vertexBuffers) {
  27360. if (this._delayInfo) {
  27361. return this._delayInfo.indexOf(kind) !== -1;
  27362. }
  27363. return false;
  27364. }
  27365. return this._vertexBuffers[kind] !== undefined;
  27366. };
  27367. Geometry.prototype.getVerticesDataKinds = function () {
  27368. var result = [];
  27369. if (!this._vertexBuffers && this._delayInfo) {
  27370. for (var kind in this._delayInfo) {
  27371. result.push(kind);
  27372. }
  27373. }
  27374. else {
  27375. for (kind in this._vertexBuffers) {
  27376. result.push(kind);
  27377. }
  27378. }
  27379. return result;
  27380. };
  27381. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27382. if (this._indexBuffer) {
  27383. this._engine._releaseBuffer(this._indexBuffer);
  27384. }
  27385. this._indices = indices;
  27386. if (this._meshes.length !== 0 && this._indices) {
  27387. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27388. }
  27389. if (totalVertices !== undefined) {
  27390. this._totalVertices = totalVertices;
  27391. }
  27392. var meshes = this._meshes;
  27393. var numOfMeshes = meshes.length;
  27394. for (var index = 0; index < numOfMeshes; index++) {
  27395. meshes[index]._createGlobalSubMesh();
  27396. }
  27397. this.notifyUpdate();
  27398. };
  27399. Geometry.prototype.getTotalIndices = function () {
  27400. if (!this.isReady()) {
  27401. return 0;
  27402. }
  27403. return this._indices.length;
  27404. };
  27405. Geometry.prototype.getIndices = function (copyWhenShared) {
  27406. if (!this.isReady()) {
  27407. return null;
  27408. }
  27409. var orig = this._indices;
  27410. if (!copyWhenShared || this._meshes.length === 1) {
  27411. return orig;
  27412. }
  27413. else {
  27414. var len = orig.length;
  27415. var copy = [];
  27416. for (var i = 0; i < len; i++) {
  27417. copy.push(orig[i]);
  27418. }
  27419. return copy;
  27420. }
  27421. };
  27422. Geometry.prototype.getIndexBuffer = function () {
  27423. if (!this.isReady()) {
  27424. return null;
  27425. }
  27426. return this._indexBuffer;
  27427. };
  27428. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27429. var meshes = this._meshes;
  27430. var index = meshes.indexOf(mesh);
  27431. if (index === -1) {
  27432. return;
  27433. }
  27434. for (var kind in this._vertexBuffers) {
  27435. this._vertexBuffers[kind].dispose();
  27436. }
  27437. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  27438. this._indexBuffer = null;
  27439. }
  27440. meshes.splice(index, 1);
  27441. mesh._geometry = null;
  27442. if (meshes.length === 0 && shouldDispose) {
  27443. this.dispose();
  27444. }
  27445. };
  27446. Geometry.prototype.applyToMesh = function (mesh) {
  27447. if (mesh._geometry === this) {
  27448. return;
  27449. }
  27450. var previousGeometry = mesh._geometry;
  27451. if (previousGeometry) {
  27452. previousGeometry.releaseForMesh(mesh);
  27453. }
  27454. var meshes = this._meshes;
  27455. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27456. mesh._geometry = this;
  27457. this._scene.pushGeometry(this);
  27458. meshes.push(mesh);
  27459. if (this.isReady()) {
  27460. this._applyToMesh(mesh);
  27461. }
  27462. else {
  27463. mesh._boundingInfo = this._boundingInfo;
  27464. }
  27465. };
  27466. Geometry.prototype._applyToMesh = function (mesh) {
  27467. var numOfMeshes = this._meshes.length;
  27468. // vertexBuffers
  27469. for (var kind in this._vertexBuffers) {
  27470. if (numOfMeshes === 1) {
  27471. this._vertexBuffers[kind].create();
  27472. }
  27473. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  27474. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27475. mesh._resetPointsArrayCache();
  27476. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  27477. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27478. mesh._createGlobalSubMesh();
  27479. //bounding info was just created again, world matrix should be applied again.
  27480. mesh._updateBoundingInfo();
  27481. }
  27482. }
  27483. // indexBuffer
  27484. if (numOfMeshes === 1 && this._indices) {
  27485. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27486. }
  27487. if (this._indexBuffer) {
  27488. this._indexBuffer.references = numOfMeshes;
  27489. }
  27490. };
  27491. Geometry.prototype.notifyUpdate = function (kind) {
  27492. if (this.onGeometryUpdated) {
  27493. this.onGeometryUpdated(this, kind);
  27494. }
  27495. };
  27496. Geometry.prototype.load = function (scene, onLoaded) {
  27497. var _this = this;
  27498. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27499. return;
  27500. }
  27501. if (this.isReady()) {
  27502. if (onLoaded) {
  27503. onLoaded();
  27504. }
  27505. return;
  27506. }
  27507. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27508. scene._addPendingData(this);
  27509. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27510. _this._delayLoadingFunction(JSON.parse(data), _this);
  27511. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27512. _this._delayInfo = [];
  27513. scene._removePendingData(_this);
  27514. var meshes = _this._meshes;
  27515. var numOfMeshes = meshes.length;
  27516. for (var index = 0; index < numOfMeshes; index++) {
  27517. _this._applyToMesh(meshes[index]);
  27518. }
  27519. if (onLoaded) {
  27520. onLoaded();
  27521. }
  27522. }, function () { }, scene.database);
  27523. };
  27524. Geometry.prototype.isDisposed = function () {
  27525. return this._isDisposed;
  27526. };
  27527. Geometry.prototype.dispose = function () {
  27528. var meshes = this._meshes;
  27529. var numOfMeshes = meshes.length;
  27530. var index;
  27531. for (index = 0; index < numOfMeshes; index++) {
  27532. this.releaseForMesh(meshes[index]);
  27533. }
  27534. this._meshes = [];
  27535. for (var kind in this._vertexBuffers) {
  27536. this._vertexBuffers[kind].dispose();
  27537. }
  27538. this._vertexBuffers = [];
  27539. this._totalVertices = 0;
  27540. if (this._indexBuffer) {
  27541. this._engine._releaseBuffer(this._indexBuffer);
  27542. }
  27543. this._indexBuffer = null;
  27544. this._indices = [];
  27545. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27546. this.delayLoadingFile = null;
  27547. this._delayLoadingFunction = null;
  27548. this._delayInfo = [];
  27549. this._boundingInfo = null; // todo: .dispose()
  27550. this._scene.removeGeometry(this);
  27551. this._isDisposed = true;
  27552. };
  27553. Geometry.prototype.copy = function (id) {
  27554. var vertexData = new BABYLON.VertexData();
  27555. vertexData.indices = [];
  27556. var indices = this.getIndices();
  27557. for (var index = 0; index < indices.length; index++) {
  27558. vertexData.indices.push(indices[index]);
  27559. }
  27560. var updatable = false;
  27561. var stopChecking = false;
  27562. for (var kind in this._vertexBuffers) {
  27563. // using slice() to make a copy of the array and not just reference it
  27564. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  27565. if (!stopChecking) {
  27566. updatable = this.getVertexBuffer(kind).isUpdatable();
  27567. stopChecking = !updatable;
  27568. }
  27569. }
  27570. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27571. geometry.delayLoadState = this.delayLoadState;
  27572. geometry.delayLoadingFile = this.delayLoadingFile;
  27573. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27574. for (kind in this._delayInfo) {
  27575. geometry._delayInfo = geometry._delayInfo || [];
  27576. geometry._delayInfo.push(kind);
  27577. }
  27578. // Bounding info
  27579. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  27580. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27581. return geometry;
  27582. };
  27583. // Statics
  27584. Geometry.ExtractFromMesh = function (mesh, id) {
  27585. var geometry = mesh._geometry;
  27586. if (!geometry) {
  27587. return null;
  27588. }
  27589. return geometry.copy(id);
  27590. };
  27591. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27592. // be aware Math.random() could cause collisions
  27593. Geometry.RandomId = function () {
  27594. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  27595. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  27596. return v.toString(16);
  27597. });
  27598. };
  27599. return Geometry;
  27600. })();
  27601. BABYLON.Geometry = Geometry;
  27602. /////// Primitives //////////////////////////////////////////////
  27603. var Geometry;
  27604. (function (Geometry) {
  27605. var Primitives;
  27606. (function (Primitives) {
  27607. /// Abstract class
  27608. var _Primitive = (function (_super) {
  27609. __extends(_Primitive, _super);
  27610. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  27611. this._beingRegenerated = true;
  27612. this._canBeRegenerated = canBeRegenerated;
  27613. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  27614. this._beingRegenerated = false;
  27615. }
  27616. _Primitive.prototype.canBeRegenerated = function () {
  27617. return this._canBeRegenerated;
  27618. };
  27619. _Primitive.prototype.regenerate = function () {
  27620. if (!this._canBeRegenerated) {
  27621. return;
  27622. }
  27623. this._beingRegenerated = true;
  27624. this.setAllVerticesData(this._regenerateVertexData(), false);
  27625. this._beingRegenerated = false;
  27626. };
  27627. _Primitive.prototype.asNewGeometry = function (id) {
  27628. return _super.prototype.copy.call(this, id);
  27629. };
  27630. // overrides
  27631. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27632. if (!this._beingRegenerated) {
  27633. return;
  27634. }
  27635. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27636. };
  27637. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27638. if (!this._beingRegenerated) {
  27639. return;
  27640. }
  27641. _super.prototype.setVerticesData.call(this, kind, data, false);
  27642. };
  27643. // to override
  27644. // protected
  27645. _Primitive.prototype._regenerateVertexData = function () {
  27646. throw new Error("Abstract method");
  27647. };
  27648. _Primitive.prototype.copy = function (id) {
  27649. throw new Error("Must be overriden in sub-classes.");
  27650. };
  27651. return _Primitive;
  27652. })(Geometry);
  27653. Primitives._Primitive = _Primitive;
  27654. var Ribbon = (function (_super) {
  27655. __extends(Ribbon, _super);
  27656. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27657. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27658. this.pathArray = pathArray;
  27659. this.closeArray = closeArray;
  27660. this.closePath = closePath;
  27661. this.offset = offset;
  27662. this.side = side;
  27663. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27664. }
  27665. Ribbon.prototype._regenerateVertexData = function () {
  27666. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  27667. };
  27668. Ribbon.prototype.copy = function (id) {
  27669. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  27670. };
  27671. return Ribbon;
  27672. })(_Primitive);
  27673. Primitives.Ribbon = Ribbon;
  27674. var Box = (function (_super) {
  27675. __extends(Box, _super);
  27676. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  27677. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27678. this.size = size;
  27679. this.side = side;
  27680. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27681. }
  27682. Box.prototype._regenerateVertexData = function () {
  27683. return BABYLON.VertexData.CreateBox(this.size, this.side);
  27684. };
  27685. Box.prototype.copy = function (id) {
  27686. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27687. };
  27688. return Box;
  27689. })(_Primitive);
  27690. Primitives.Box = Box;
  27691. var Sphere = (function (_super) {
  27692. __extends(Sphere, _super);
  27693. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  27694. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27695. this.segments = segments;
  27696. this.diameter = diameter;
  27697. this.side = side;
  27698. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27699. }
  27700. Sphere.prototype._regenerateVertexData = function () {
  27701. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  27702. };
  27703. Sphere.prototype.copy = function (id) {
  27704. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  27705. };
  27706. return Sphere;
  27707. })(_Primitive);
  27708. Primitives.Sphere = Sphere;
  27709. var Cylinder = (function (_super) {
  27710. __extends(Cylinder, _super);
  27711. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  27712. if (subdivisions === void 0) { subdivisions = 1; }
  27713. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27714. this.height = height;
  27715. this.diameterTop = diameterTop;
  27716. this.diameterBottom = diameterBottom;
  27717. this.tessellation = tessellation;
  27718. this.subdivisions = subdivisions;
  27719. this.side = side;
  27720. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27721. }
  27722. Cylinder.prototype._regenerateVertexData = function () {
  27723. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  27724. };
  27725. Cylinder.prototype.copy = function (id) {
  27726. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  27727. };
  27728. return Cylinder;
  27729. })(_Primitive);
  27730. Primitives.Cylinder = Cylinder;
  27731. var Torus = (function (_super) {
  27732. __extends(Torus, _super);
  27733. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  27734. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27735. this.diameter = diameter;
  27736. this.thickness = thickness;
  27737. this.tessellation = tessellation;
  27738. this.side = side;
  27739. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27740. }
  27741. Torus.prototype._regenerateVertexData = function () {
  27742. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  27743. };
  27744. Torus.prototype.copy = function (id) {
  27745. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  27746. };
  27747. return Torus;
  27748. })(_Primitive);
  27749. Primitives.Torus = Torus;
  27750. var Ground = (function (_super) {
  27751. __extends(Ground, _super);
  27752. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  27753. this.width = width;
  27754. this.height = height;
  27755. this.subdivisions = subdivisions;
  27756. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27757. }
  27758. Ground.prototype._regenerateVertexData = function () {
  27759. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  27760. };
  27761. Ground.prototype.copy = function (id) {
  27762. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  27763. };
  27764. return Ground;
  27765. })(_Primitive);
  27766. Primitives.Ground = Ground;
  27767. var TiledGround = (function (_super) {
  27768. __extends(TiledGround, _super);
  27769. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  27770. this.xmin = xmin;
  27771. this.zmin = zmin;
  27772. this.xmax = xmax;
  27773. this.zmax = zmax;
  27774. this.subdivisions = subdivisions;
  27775. this.precision = precision;
  27776. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27777. }
  27778. TiledGround.prototype._regenerateVertexData = function () {
  27779. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  27780. };
  27781. TiledGround.prototype.copy = function (id) {
  27782. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  27783. };
  27784. return TiledGround;
  27785. })(_Primitive);
  27786. Primitives.TiledGround = TiledGround;
  27787. var Plane = (function (_super) {
  27788. __extends(Plane, _super);
  27789. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  27790. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27791. this.size = size;
  27792. this.side = side;
  27793. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27794. }
  27795. Plane.prototype._regenerateVertexData = function () {
  27796. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  27797. };
  27798. Plane.prototype.copy = function (id) {
  27799. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27800. };
  27801. return Plane;
  27802. })(_Primitive);
  27803. Primitives.Plane = Plane;
  27804. var TorusKnot = (function (_super) {
  27805. __extends(TorusKnot, _super);
  27806. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  27807. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27808. this.radius = radius;
  27809. this.tube = tube;
  27810. this.radialSegments = radialSegments;
  27811. this.tubularSegments = tubularSegments;
  27812. this.p = p;
  27813. this.q = q;
  27814. this.side = side;
  27815. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27816. }
  27817. TorusKnot.prototype._regenerateVertexData = function () {
  27818. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  27819. };
  27820. TorusKnot.prototype.copy = function (id) {
  27821. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  27822. };
  27823. return TorusKnot;
  27824. })(_Primitive);
  27825. Primitives.TorusKnot = TorusKnot;
  27826. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  27827. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  27828. })(BABYLON || (BABYLON = {}));
  27829. //# sourceMappingURL=babylon.geometry.js.map
  27830. var BABYLON;
  27831. (function (BABYLON) {
  27832. var GroundMesh = (function (_super) {
  27833. __extends(GroundMesh, _super);
  27834. function GroundMesh(name, scene) {
  27835. _super.call(this, name, scene);
  27836. this.generateOctree = false;
  27837. this._worldInverse = new BABYLON.Matrix();
  27838. }
  27839. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  27840. get: function () {
  27841. return this._subdivisions;
  27842. },
  27843. enumerable: true,
  27844. configurable: true
  27845. });
  27846. GroundMesh.prototype.optimize = function (chunksCount) {
  27847. this.subdivide(this._subdivisions);
  27848. this.createOrUpdateSubmeshesOctree(32);
  27849. };
  27850. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  27851. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  27852. this.getWorldMatrix().invertToRef(this._worldInverse);
  27853. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  27854. var pickInfo = this.intersects(ray);
  27855. if (pickInfo.hit) {
  27856. return pickInfo.pickedPoint.y;
  27857. }
  27858. return 0;
  27859. };
  27860. return GroundMesh;
  27861. })(BABYLON.Mesh);
  27862. BABYLON.GroundMesh = GroundMesh;
  27863. })(BABYLON || (BABYLON = {}));
  27864. //# sourceMappingURL=babylon.groundMesh.js.map
  27865. var BABYLON;
  27866. (function (BABYLON) {
  27867. var LinesMesh = (function (_super) {
  27868. __extends(LinesMesh, _super);
  27869. function LinesMesh(name, scene, updatable) {
  27870. if (updatable === void 0) { updatable = false; }
  27871. _super.call(this, name, scene);
  27872. this.color = new BABYLON.Color3(1, 1, 1);
  27873. this.alpha = 1;
  27874. this._indices = new Array();
  27875. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  27876. attributes: ["position"],
  27877. uniforms: ["worldViewProjection", "color"],
  27878. needAlphaBlending: true
  27879. });
  27880. }
  27881. Object.defineProperty(LinesMesh.prototype, "material", {
  27882. get: function () {
  27883. return this._colorShader;
  27884. },
  27885. enumerable: true,
  27886. configurable: true
  27887. });
  27888. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  27889. get: function () {
  27890. return false;
  27891. },
  27892. enumerable: true,
  27893. configurable: true
  27894. });
  27895. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  27896. get: function () {
  27897. return false;
  27898. },
  27899. enumerable: true,
  27900. configurable: true
  27901. });
  27902. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  27903. var engine = this.getScene().getEngine();
  27904. var indexToBind = this._geometry.getIndexBuffer();
  27905. // VBOs
  27906. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  27907. // Color
  27908. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  27909. };
  27910. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  27911. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27912. return;
  27913. }
  27914. var engine = this.getScene().getEngine();
  27915. // Draw order
  27916. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  27917. };
  27918. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  27919. return null;
  27920. };
  27921. LinesMesh.prototype.dispose = function (doNotRecurse) {
  27922. this._colorShader.dispose();
  27923. _super.prototype.dispose.call(this, doNotRecurse);
  27924. };
  27925. return LinesMesh;
  27926. })(BABYLON.Mesh);
  27927. BABYLON.LinesMesh = LinesMesh;
  27928. })(BABYLON || (BABYLON = {}));
  27929. //# sourceMappingURL=babylon.linesMesh.js.map
  27930. var BABYLON;
  27931. (function (BABYLON) {
  27932. var OutlineRenderer = (function () {
  27933. function OutlineRenderer(scene) {
  27934. this._scene = scene;
  27935. }
  27936. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  27937. var _this = this;
  27938. if (useOverlay === void 0) { useOverlay = false; }
  27939. var scene = this._scene;
  27940. var engine = this._scene.getEngine();
  27941. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  27942. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  27943. return;
  27944. }
  27945. var mesh = subMesh.getRenderingMesh();
  27946. var material = subMesh.getMaterial();
  27947. engine.enableEffect(this._effect);
  27948. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  27949. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  27950. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  27951. // Bones
  27952. if (mesh.useBones) {
  27953. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27954. }
  27955. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  27956. // Alpha test
  27957. if (material && material.needAlphaTesting()) {
  27958. var alphaTexture = material.getAlphaTestTexture();
  27959. this._effect.setTexture("diffuseSampler", alphaTexture);
  27960. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  27961. }
  27962. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  27963. };
  27964. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  27965. var defines = [];
  27966. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  27967. var mesh = subMesh.getMesh();
  27968. var material = subMesh.getMaterial();
  27969. // Alpha test
  27970. if (material && material.needAlphaTesting()) {
  27971. defines.push("#define ALPHATEST");
  27972. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27973. attribs.push(BABYLON.VertexBuffer.UVKind);
  27974. defines.push("#define UV1");
  27975. }
  27976. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27977. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27978. defines.push("#define UV2");
  27979. }
  27980. }
  27981. // Bones
  27982. if (mesh.useBones) {
  27983. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27984. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27985. defines.push("#define BONES");
  27986. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27987. }
  27988. // Instances
  27989. if (useInstances) {
  27990. defines.push("#define INSTANCES");
  27991. attribs.push("world0");
  27992. attribs.push("world1");
  27993. attribs.push("world2");
  27994. attribs.push("world3");
  27995. }
  27996. // Get correct effect
  27997. var join = defines.join("\n");
  27998. if (this._cachedDefines !== join) {
  27999. this._cachedDefines = join;
  28000. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  28001. }
  28002. return this._effect.isReady();
  28003. };
  28004. return OutlineRenderer;
  28005. })();
  28006. BABYLON.OutlineRenderer = OutlineRenderer;
  28007. })(BABYLON || (BABYLON = {}));
  28008. //# sourceMappingURL=babylon.outlineRenderer.js.map
  28009. var BABYLON;
  28010. (function (BABYLON) {
  28011. var MeshAssetTask = (function () {
  28012. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  28013. this.name = name;
  28014. this.meshesNames = meshesNames;
  28015. this.rootUrl = rootUrl;
  28016. this.sceneFilename = sceneFilename;
  28017. this.isCompleted = false;
  28018. }
  28019. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28020. var _this = this;
  28021. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  28022. _this.loadedMeshes = meshes;
  28023. _this.loadedParticleSystems = particleSystems;
  28024. _this.loadedSkeletons = skeletons;
  28025. _this.isCompleted = true;
  28026. if (_this.onSuccess) {
  28027. _this.onSuccess(_this);
  28028. }
  28029. onSuccess();
  28030. }, null, function () {
  28031. if (_this.onError) {
  28032. _this.onError(_this);
  28033. }
  28034. onError();
  28035. });
  28036. };
  28037. return MeshAssetTask;
  28038. })();
  28039. BABYLON.MeshAssetTask = MeshAssetTask;
  28040. var TextFileAssetTask = (function () {
  28041. function TextFileAssetTask(name, url) {
  28042. this.name = name;
  28043. this.url = url;
  28044. this.isCompleted = false;
  28045. }
  28046. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28047. var _this = this;
  28048. BABYLON.Tools.LoadFile(this.url, function (data) {
  28049. _this.text = data;
  28050. _this.isCompleted = true;
  28051. if (_this.onSuccess) {
  28052. _this.onSuccess(_this);
  28053. }
  28054. onSuccess();
  28055. }, null, scene.database, false, function () {
  28056. if (_this.onError) {
  28057. _this.onError(_this);
  28058. }
  28059. onError();
  28060. });
  28061. };
  28062. return TextFileAssetTask;
  28063. })();
  28064. BABYLON.TextFileAssetTask = TextFileAssetTask;
  28065. var BinaryFileAssetTask = (function () {
  28066. function BinaryFileAssetTask(name, url) {
  28067. this.name = name;
  28068. this.url = url;
  28069. this.isCompleted = false;
  28070. }
  28071. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28072. var _this = this;
  28073. BABYLON.Tools.LoadFile(this.url, function (data) {
  28074. _this.data = data;
  28075. _this.isCompleted = true;
  28076. if (_this.onSuccess) {
  28077. _this.onSuccess(_this);
  28078. }
  28079. onSuccess();
  28080. }, null, scene.database, true, function () {
  28081. if (_this.onError) {
  28082. _this.onError(_this);
  28083. }
  28084. onError();
  28085. });
  28086. };
  28087. return BinaryFileAssetTask;
  28088. })();
  28089. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  28090. var ImageAssetTask = (function () {
  28091. function ImageAssetTask(name, url) {
  28092. this.name = name;
  28093. this.url = url;
  28094. this.isCompleted = false;
  28095. }
  28096. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28097. var _this = this;
  28098. var img = new Image();
  28099. img.onload = function () {
  28100. _this.image = img;
  28101. _this.isCompleted = true;
  28102. if (_this.onSuccess) {
  28103. _this.onSuccess(_this);
  28104. }
  28105. onSuccess();
  28106. };
  28107. img.onerror = function () {
  28108. if (_this.onError) {
  28109. _this.onError(_this);
  28110. }
  28111. onError();
  28112. };
  28113. img.src = this.url;
  28114. };
  28115. return ImageAssetTask;
  28116. })();
  28117. BABYLON.ImageAssetTask = ImageAssetTask;
  28118. var TextureAssetTask = (function () {
  28119. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  28120. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28121. this.name = name;
  28122. this.url = url;
  28123. this.noMipmap = noMipmap;
  28124. this.invertY = invertY;
  28125. this.samplingMode = samplingMode;
  28126. this.isCompleted = false;
  28127. }
  28128. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28129. var _this = this;
  28130. var onload = function () {
  28131. _this.isCompleted = true;
  28132. if (_this.onSuccess) {
  28133. _this.onSuccess(_this);
  28134. }
  28135. onSuccess();
  28136. };
  28137. var onerror = function () {
  28138. if (_this.onError) {
  28139. _this.onError(_this);
  28140. }
  28141. onError();
  28142. };
  28143. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  28144. };
  28145. return TextureAssetTask;
  28146. })();
  28147. BABYLON.TextureAssetTask = TextureAssetTask;
  28148. var AssetsManager = (function () {
  28149. function AssetsManager(scene) {
  28150. this._tasks = new Array();
  28151. this._waitingTasksCount = 0;
  28152. this.useDefaultLoadingScreen = true;
  28153. this._scene = scene;
  28154. }
  28155. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  28156. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  28157. this._tasks.push(task);
  28158. return task;
  28159. };
  28160. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  28161. var task = new TextFileAssetTask(taskName, url);
  28162. this._tasks.push(task);
  28163. return task;
  28164. };
  28165. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  28166. var task = new BinaryFileAssetTask(taskName, url);
  28167. this._tasks.push(task);
  28168. return task;
  28169. };
  28170. AssetsManager.prototype.addImageTask = function (taskName, url) {
  28171. var task = new ImageAssetTask(taskName, url);
  28172. this._tasks.push(task);
  28173. return task;
  28174. };
  28175. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  28176. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28177. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  28178. this._tasks.push(task);
  28179. return task;
  28180. };
  28181. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  28182. this._waitingTasksCount--;
  28183. if (this._waitingTasksCount === 0) {
  28184. if (this.onFinish) {
  28185. this.onFinish(this._tasks);
  28186. }
  28187. this._scene.getEngine().hideLoadingUI();
  28188. }
  28189. };
  28190. AssetsManager.prototype._runTask = function (task) {
  28191. var _this = this;
  28192. task.run(this._scene, function () {
  28193. if (_this.onTaskSuccess) {
  28194. _this.onTaskSuccess(task);
  28195. }
  28196. _this._decreaseWaitingTasksCount();
  28197. }, function () {
  28198. if (_this.onTaskError) {
  28199. _this.onTaskError(task);
  28200. }
  28201. _this._decreaseWaitingTasksCount();
  28202. });
  28203. };
  28204. AssetsManager.prototype.reset = function () {
  28205. this._tasks = new Array();
  28206. return this;
  28207. };
  28208. AssetsManager.prototype.load = function () {
  28209. this._waitingTasksCount = this._tasks.length;
  28210. if (this._waitingTasksCount === 0) {
  28211. if (this.onFinish) {
  28212. this.onFinish(this._tasks);
  28213. }
  28214. return this;
  28215. }
  28216. if (this.useDefaultLoadingScreen) {
  28217. this._scene.getEngine().displayLoadingUI();
  28218. }
  28219. for (var index = 0; index < this._tasks.length; index++) {
  28220. var task = this._tasks[index];
  28221. this._runTask(task);
  28222. }
  28223. return this;
  28224. };
  28225. return AssetsManager;
  28226. })();
  28227. BABYLON.AssetsManager = AssetsManager;
  28228. })(BABYLON || (BABYLON = {}));
  28229. //# sourceMappingURL=babylon.assetsManager.js.map
  28230. var BABYLON;
  28231. (function (BABYLON) {
  28232. var VRDeviceOrientationFreeCamera = (function (_super) {
  28233. __extends(VRDeviceOrientationFreeCamera, _super);
  28234. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistorsion) {
  28235. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  28236. _super.call(this, name, position, scene);
  28237. this._alpha = 0;
  28238. this._beta = 0;
  28239. this._gamma = 0;
  28240. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  28241. metrics.compensateDistorsion = compensateDistorsion;
  28242. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_VR, 0, metrics);
  28243. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  28244. }
  28245. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  28246. this._alpha = +evt.alpha | 0;
  28247. this._beta = +evt.beta | 0;
  28248. this._gamma = +evt.gamma | 0;
  28249. if (this._gamma < 0) {
  28250. this._gamma = 90 + this._gamma;
  28251. }
  28252. else {
  28253. // Incline it in the correct angle.
  28254. this._gamma = 270 - this._gamma;
  28255. }
  28256. this.rotation.x = this._gamma / 180.0 * Math.PI;
  28257. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  28258. this.rotation.z = this._beta / 180.0 * Math.PI;
  28259. };
  28260. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  28261. _super.prototype.attachControl.call(this, element, noPreventDefault);
  28262. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  28263. };
  28264. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  28265. _super.prototype.detachControl.call(this, element);
  28266. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  28267. };
  28268. return VRDeviceOrientationFreeCamera;
  28269. })(BABYLON.FreeCamera);
  28270. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  28271. })(BABYLON || (BABYLON = {}));
  28272. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  28273. var BABYLON;
  28274. (function (BABYLON) {
  28275. var WebVRFreeCamera = (function (_super) {
  28276. __extends(WebVRFreeCamera, _super);
  28277. function WebVRFreeCamera(name, position, scene, compensateDistorsion) {
  28278. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  28279. _super.call(this, name, position, scene);
  28280. this._hmdDevice = null;
  28281. this._sensorDevice = null;
  28282. this._cacheState = null;
  28283. this._cacheQuaternion = new BABYLON.Quaternion();
  28284. this._cacheRotation = BABYLON.Vector3.Zero();
  28285. this._vrEnabled = false;
  28286. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  28287. metrics.compensateDistorsion = compensateDistorsion;
  28288. this.setSubCameraMode(BABYLON.Camera.SUB_CAMERA_MODE_VR, 0, metrics);
  28289. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  28290. }
  28291. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  28292. var size = devices.length;
  28293. var i = 0;
  28294. // Reset devices.
  28295. this._sensorDevice = null;
  28296. this._hmdDevice = null;
  28297. // Search for a HmdDevice.
  28298. while (i < size && this._hmdDevice === null) {
  28299. if (devices[i] instanceof HMDVRDevice) {
  28300. this._hmdDevice = devices[i];
  28301. }
  28302. i++;
  28303. }
  28304. i = 0;
  28305. while (i < size && this._sensorDevice === null) {
  28306. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  28307. this._sensorDevice = devices[i];
  28308. }
  28309. i++;
  28310. }
  28311. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  28312. };
  28313. WebVRFreeCamera.prototype._checkInputs = function () {
  28314. if (this._vrEnabled) {
  28315. this._cacheState = this._sensorDevice.getState();
  28316. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  28317. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  28318. this.rotation.x = -this._cacheRotation.z;
  28319. this.rotation.y = -this._cacheRotation.y;
  28320. this.rotation.z = this._cacheRotation.x;
  28321. }
  28322. _super.prototype._checkInputs.call(this);
  28323. };
  28324. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  28325. _super.prototype.attachControl.call(this, element, noPreventDefault);
  28326. if (navigator.getVRDevices) {
  28327. navigator.getVRDevices().then(this._getWebVRDevices);
  28328. }
  28329. else if (navigator.mozGetVRDevices) {
  28330. navigator.mozGetVRDevices(this._getWebVRDevices);
  28331. }
  28332. };
  28333. WebVRFreeCamera.prototype.detachControl = function (element) {
  28334. _super.prototype.detachControl.call(this, element);
  28335. this._vrEnabled = false;
  28336. };
  28337. return WebVRFreeCamera;
  28338. })(BABYLON.FreeCamera);
  28339. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  28340. })(BABYLON || (BABYLON = {}));
  28341. //# sourceMappingURL=babylon.webVRCamera.js.map
  28342. var BABYLON;
  28343. (function (BABYLON) {
  28344. // Standard optimizations
  28345. var SceneOptimization = (function () {
  28346. function SceneOptimization(priority) {
  28347. if (priority === void 0) { priority = 0; }
  28348. this.priority = priority;
  28349. this.apply = function (scene) {
  28350. return true; // Return true if everything that can be done was applied
  28351. };
  28352. }
  28353. return SceneOptimization;
  28354. })();
  28355. BABYLON.SceneOptimization = SceneOptimization;
  28356. var TextureOptimization = (function (_super) {
  28357. __extends(TextureOptimization, _super);
  28358. function TextureOptimization(priority, maximumSize) {
  28359. var _this = this;
  28360. if (priority === void 0) { priority = 0; }
  28361. if (maximumSize === void 0) { maximumSize = 1024; }
  28362. _super.call(this, priority);
  28363. this.priority = priority;
  28364. this.maximumSize = maximumSize;
  28365. this.apply = function (scene) {
  28366. var allDone = true;
  28367. for (var index = 0; index < scene.textures.length; index++) {
  28368. var texture = scene.textures[index];
  28369. if (!texture.canRescale) {
  28370. continue;
  28371. }
  28372. var currentSize = texture.getSize();
  28373. var maxDimension = Math.max(currentSize.width, currentSize.height);
  28374. if (maxDimension > _this.maximumSize) {
  28375. texture.scale(0.5);
  28376. allDone = false;
  28377. }
  28378. }
  28379. return allDone;
  28380. };
  28381. }
  28382. return TextureOptimization;
  28383. })(SceneOptimization);
  28384. BABYLON.TextureOptimization = TextureOptimization;
  28385. var HardwareScalingOptimization = (function (_super) {
  28386. __extends(HardwareScalingOptimization, _super);
  28387. function HardwareScalingOptimization(priority, maximumScale) {
  28388. var _this = this;
  28389. if (priority === void 0) { priority = 0; }
  28390. if (maximumScale === void 0) { maximumScale = 2; }
  28391. _super.call(this, priority);
  28392. this.priority = priority;
  28393. this.maximumScale = maximumScale;
  28394. this._currentScale = 1;
  28395. this.apply = function (scene) {
  28396. _this._currentScale++;
  28397. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  28398. return _this._currentScale >= _this.maximumScale;
  28399. };
  28400. }
  28401. return HardwareScalingOptimization;
  28402. })(SceneOptimization);
  28403. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  28404. var ShadowsOptimization = (function (_super) {
  28405. __extends(ShadowsOptimization, _super);
  28406. function ShadowsOptimization() {
  28407. _super.apply(this, arguments);
  28408. this.apply = function (scene) {
  28409. scene.shadowsEnabled = false;
  28410. return true;
  28411. };
  28412. }
  28413. return ShadowsOptimization;
  28414. })(SceneOptimization);
  28415. BABYLON.ShadowsOptimization = ShadowsOptimization;
  28416. var PostProcessesOptimization = (function (_super) {
  28417. __extends(PostProcessesOptimization, _super);
  28418. function PostProcessesOptimization() {
  28419. _super.apply(this, arguments);
  28420. this.apply = function (scene) {
  28421. scene.postProcessesEnabled = false;
  28422. return true;
  28423. };
  28424. }
  28425. return PostProcessesOptimization;
  28426. })(SceneOptimization);
  28427. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  28428. var LensFlaresOptimization = (function (_super) {
  28429. __extends(LensFlaresOptimization, _super);
  28430. function LensFlaresOptimization() {
  28431. _super.apply(this, arguments);
  28432. this.apply = function (scene) {
  28433. scene.lensFlaresEnabled = false;
  28434. return true;
  28435. };
  28436. }
  28437. return LensFlaresOptimization;
  28438. })(SceneOptimization);
  28439. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  28440. var ParticlesOptimization = (function (_super) {
  28441. __extends(ParticlesOptimization, _super);
  28442. function ParticlesOptimization() {
  28443. _super.apply(this, arguments);
  28444. this.apply = function (scene) {
  28445. scene.particlesEnabled = false;
  28446. return true;
  28447. };
  28448. }
  28449. return ParticlesOptimization;
  28450. })(SceneOptimization);
  28451. BABYLON.ParticlesOptimization = ParticlesOptimization;
  28452. var RenderTargetsOptimization = (function (_super) {
  28453. __extends(RenderTargetsOptimization, _super);
  28454. function RenderTargetsOptimization() {
  28455. _super.apply(this, arguments);
  28456. this.apply = function (scene) {
  28457. scene.renderTargetsEnabled = false;
  28458. return true;
  28459. };
  28460. }
  28461. return RenderTargetsOptimization;
  28462. })(SceneOptimization);
  28463. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  28464. var MergeMeshesOptimization = (function (_super) {
  28465. __extends(MergeMeshesOptimization, _super);
  28466. function MergeMeshesOptimization() {
  28467. var _this = this;
  28468. _super.apply(this, arguments);
  28469. this._canBeMerged = function (abstractMesh) {
  28470. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  28471. return false;
  28472. }
  28473. var mesh = abstractMesh;
  28474. if (!mesh.isVisible || !mesh.isEnabled()) {
  28475. return false;
  28476. }
  28477. if (mesh.instances.length > 0) {
  28478. return false;
  28479. }
  28480. if (mesh.skeleton || mesh.hasLODLevels) {
  28481. return false;
  28482. }
  28483. return true;
  28484. };
  28485. this.apply = function (scene) {
  28486. var globalPool = scene.meshes.slice(0);
  28487. var globalLength = globalPool.length;
  28488. for (var index = 0; index < globalLength; index++) {
  28489. var currentPool = new Array();
  28490. var current = globalPool[index];
  28491. // Checks
  28492. if (!_this._canBeMerged(current)) {
  28493. continue;
  28494. }
  28495. currentPool.push(current);
  28496. // Find compatible meshes
  28497. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  28498. var otherMesh = globalPool[subIndex];
  28499. if (!_this._canBeMerged(otherMesh)) {
  28500. continue;
  28501. }
  28502. if (otherMesh.material !== current.material) {
  28503. continue;
  28504. }
  28505. if (otherMesh.checkCollisions !== current.checkCollisions) {
  28506. continue;
  28507. }
  28508. currentPool.push(otherMesh);
  28509. globalLength--;
  28510. globalPool.splice(subIndex, 1);
  28511. subIndex--;
  28512. }
  28513. if (currentPool.length < 2) {
  28514. continue;
  28515. }
  28516. // Merge meshes
  28517. BABYLON.Mesh.MergeMeshes(currentPool);
  28518. }
  28519. return true;
  28520. };
  28521. }
  28522. return MergeMeshesOptimization;
  28523. })(SceneOptimization);
  28524. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  28525. // Options
  28526. var SceneOptimizerOptions = (function () {
  28527. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  28528. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  28529. if (trackerDuration === void 0) { trackerDuration = 2000; }
  28530. this.targetFrameRate = targetFrameRate;
  28531. this.trackerDuration = trackerDuration;
  28532. this.optimizations = new Array();
  28533. }
  28534. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  28535. var result = new SceneOptimizerOptions(targetFrameRate);
  28536. var priority = 0;
  28537. result.optimizations.push(new MergeMeshesOptimization(priority));
  28538. result.optimizations.push(new ShadowsOptimization(priority));
  28539. result.optimizations.push(new LensFlaresOptimization(priority));
  28540. // Next priority
  28541. priority++;
  28542. result.optimizations.push(new PostProcessesOptimization(priority));
  28543. result.optimizations.push(new ParticlesOptimization(priority));
  28544. // Next priority
  28545. priority++;
  28546. result.optimizations.push(new TextureOptimization(priority, 1024));
  28547. return result;
  28548. };
  28549. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  28550. var result = new SceneOptimizerOptions(targetFrameRate);
  28551. var priority = 0;
  28552. result.optimizations.push(new MergeMeshesOptimization(priority));
  28553. result.optimizations.push(new ShadowsOptimization(priority));
  28554. result.optimizations.push(new LensFlaresOptimization(priority));
  28555. // Next priority
  28556. priority++;
  28557. result.optimizations.push(new PostProcessesOptimization(priority));
  28558. result.optimizations.push(new ParticlesOptimization(priority));
  28559. // Next priority
  28560. priority++;
  28561. result.optimizations.push(new TextureOptimization(priority, 512));
  28562. // Next priority
  28563. priority++;
  28564. result.optimizations.push(new RenderTargetsOptimization(priority));
  28565. // Next priority
  28566. priority++;
  28567. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  28568. return result;
  28569. };
  28570. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  28571. var result = new SceneOptimizerOptions(targetFrameRate);
  28572. var priority = 0;
  28573. result.optimizations.push(new MergeMeshesOptimization(priority));
  28574. result.optimizations.push(new ShadowsOptimization(priority));
  28575. result.optimizations.push(new LensFlaresOptimization(priority));
  28576. // Next priority
  28577. priority++;
  28578. result.optimizations.push(new PostProcessesOptimization(priority));
  28579. result.optimizations.push(new ParticlesOptimization(priority));
  28580. // Next priority
  28581. priority++;
  28582. result.optimizations.push(new TextureOptimization(priority, 256));
  28583. // Next priority
  28584. priority++;
  28585. result.optimizations.push(new RenderTargetsOptimization(priority));
  28586. // Next priority
  28587. priority++;
  28588. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  28589. return result;
  28590. };
  28591. return SceneOptimizerOptions;
  28592. })();
  28593. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  28594. // Scene optimizer tool
  28595. var SceneOptimizer = (function () {
  28596. function SceneOptimizer() {
  28597. }
  28598. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  28599. // TODO: add an epsilon
  28600. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  28601. if (onSuccess) {
  28602. onSuccess();
  28603. }
  28604. return;
  28605. }
  28606. // Apply current level of optimizations
  28607. var allDone = true;
  28608. var noOptimizationApplied = true;
  28609. for (var index = 0; index < options.optimizations.length; index++) {
  28610. var optimization = options.optimizations[index];
  28611. if (optimization.priority === currentPriorityLevel) {
  28612. noOptimizationApplied = false;
  28613. allDone = allDone && optimization.apply(scene);
  28614. }
  28615. }
  28616. // If no optimization was applied, this is a failure :(
  28617. if (noOptimizationApplied) {
  28618. if (onFailure) {
  28619. onFailure();
  28620. }
  28621. return;
  28622. }
  28623. // If all optimizations were done, move to next level
  28624. if (allDone) {
  28625. currentPriorityLevel++;
  28626. }
  28627. // Let's the system running for a specific amount of time before checking FPS
  28628. scene.executeWhenReady(function () {
  28629. setTimeout(function () {
  28630. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  28631. }, options.trackerDuration);
  28632. });
  28633. };
  28634. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  28635. if (!options) {
  28636. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  28637. }
  28638. // Let's the system running for a specific amount of time before checking FPS
  28639. scene.executeWhenReady(function () {
  28640. setTimeout(function () {
  28641. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  28642. }, options.trackerDuration);
  28643. });
  28644. };
  28645. return SceneOptimizer;
  28646. })();
  28647. BABYLON.SceneOptimizer = SceneOptimizer;
  28648. })(BABYLON || (BABYLON = {}));
  28649. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  28650. var BABYLON;
  28651. (function (BABYLON) {
  28652. var Internals;
  28653. (function (Internals) {
  28654. var MeshLODLevel = (function () {
  28655. function MeshLODLevel(distance, mesh) {
  28656. this.distance = distance;
  28657. this.mesh = mesh;
  28658. }
  28659. return MeshLODLevel;
  28660. })();
  28661. Internals.MeshLODLevel = MeshLODLevel;
  28662. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28663. })(BABYLON || (BABYLON = {}));
  28664. //# sourceMappingURL=babylon.meshLODLevel.js.map
  28665. var BABYLON;
  28666. (function (BABYLON) {
  28667. var AudioEngine = (function () {
  28668. function AudioEngine() {
  28669. this._audioContext = null;
  28670. this._audioContextInitialized = false;
  28671. this.canUseWebAudio = false;
  28672. this.WarnedWebAudioUnsupported = false;
  28673. if (typeof AudioContext !== 'undefined' || typeof webkitAudioContext !== 'undefined') {
  28674. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  28675. this.canUseWebAudio = true;
  28676. }
  28677. }
  28678. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  28679. get: function () {
  28680. if (!this._audioContextInitialized) {
  28681. this._initializeAudioContext();
  28682. }
  28683. return this._audioContext;
  28684. },
  28685. enumerable: true,
  28686. configurable: true
  28687. });
  28688. AudioEngine.prototype._initializeAudioContext = function () {
  28689. try {
  28690. if (this.canUseWebAudio) {
  28691. this._audioContext = new AudioContext();
  28692. // create a global volume gain node
  28693. this.masterGain = this._audioContext.createGain();
  28694. this.masterGain.gain.value = 1;
  28695. this.masterGain.connect(this._audioContext.destination);
  28696. this._audioContextInitialized = true;
  28697. }
  28698. }
  28699. catch (e) {
  28700. this.canUseWebAudio = false;
  28701. BABYLON.Tools.Error("Web Audio: " + e.message);
  28702. }
  28703. };
  28704. AudioEngine.prototype.dispose = function () {
  28705. if (this.canUseWebAudio && this._audioContextInitialized) {
  28706. if (this._connectedAnalyser) {
  28707. this._connectedAnalyser.stopDebugCanvas();
  28708. this._connectedAnalyser.dispose();
  28709. this.masterGain.disconnect();
  28710. this.masterGain.connect(this._audioContext.destination);
  28711. this._connectedAnalyser = null;
  28712. }
  28713. this.masterGain.gain.value = 1;
  28714. }
  28715. this.WarnedWebAudioUnsupported = false;
  28716. };
  28717. AudioEngine.prototype.getGlobalVolume = function () {
  28718. if (this.canUseWebAudio && this._audioContextInitialized) {
  28719. return this.masterGain.gain.value;
  28720. }
  28721. else {
  28722. return -1;
  28723. }
  28724. };
  28725. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  28726. if (this.canUseWebAudio && this._audioContextInitialized) {
  28727. this.masterGain.gain.value = newVolume;
  28728. }
  28729. };
  28730. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  28731. if (this._connectedAnalyser) {
  28732. this._connectedAnalyser.stopDebugCanvas();
  28733. }
  28734. if (this.canUseWebAudio && this._audioContextInitialized) {
  28735. this._connectedAnalyser = analyser;
  28736. this.masterGain.disconnect();
  28737. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  28738. }
  28739. };
  28740. return AudioEngine;
  28741. })();
  28742. BABYLON.AudioEngine = AudioEngine;
  28743. })(BABYLON || (BABYLON = {}));
  28744. //# sourceMappingURL=babylon.audioEngine.js.map
  28745. var BABYLON;
  28746. (function (BABYLON) {
  28747. var Sound = (function () {
  28748. /**
  28749. * Create a sound and attach it to a scene
  28750. * @param name Name of your sound
  28751. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  28752. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  28753. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  28754. */
  28755. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  28756. var _this = this;
  28757. this.autoplay = false;
  28758. this.loop = false;
  28759. this.useCustomAttenuation = false;
  28760. this.spatialSound = false;
  28761. this.refDistance = 1;
  28762. this.rolloffFactor = 1;
  28763. this.maxDistance = 100;
  28764. this.distanceModel = "linear";
  28765. this._panningModel = "equalpower";
  28766. this._playbackRate = 1;
  28767. this._startTime = 0;
  28768. this._startOffset = 0;
  28769. this._position = BABYLON.Vector3.Zero();
  28770. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  28771. this._volume = 1;
  28772. this._isLoaded = false;
  28773. this._isReadyToPlay = false;
  28774. this.isPlaying = false;
  28775. this.isPaused = false;
  28776. this._isDirectional = false;
  28777. // Used if you'd like to create a directional sound.
  28778. // If not set, the sound will be omnidirectional
  28779. this._coneInnerAngle = 360;
  28780. this._coneOuterAngle = 360;
  28781. this._coneOuterGain = 0;
  28782. this.name = name;
  28783. this._scene = scene;
  28784. this._readyToPlayCallback = readyToPlayCallback;
  28785. // Default custom attenuation function is a linear attenuation
  28786. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  28787. if (currentDistance < maxDistance) {
  28788. return currentVolume * (1 - currentDistance / maxDistance);
  28789. }
  28790. else {
  28791. return 0;
  28792. }
  28793. };
  28794. if (options) {
  28795. this.autoplay = options.autoplay || false;
  28796. this.loop = options.loop || false;
  28797. // if volume === 0, we need another way to check this option
  28798. if (options.volume !== undefined) {
  28799. this._volume = options.volume;
  28800. }
  28801. this.spatialSound = options.spatialSound || false;
  28802. this.maxDistance = options.maxDistance || 100;
  28803. this.useCustomAttenuation = options.useCustomAttenuation || false;
  28804. this.rolloffFactor = options.rolloffFactor || 1;
  28805. this.refDistance = options.refDistance || 1;
  28806. this.distanceModel = options.distanceModel || "linear";
  28807. this._playbackRate = options.playbackRate || 1;
  28808. }
  28809. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28810. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  28811. this._soundGain.gain.value = this._volume;
  28812. this._inputAudioNode = this._soundGain;
  28813. this._ouputAudioNode = this._soundGain;
  28814. if (this.spatialSound) {
  28815. this._createSpatialParameters();
  28816. }
  28817. this._scene.mainSoundTrack.AddSound(this);
  28818. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  28819. if (urlOrArrayBuffer) {
  28820. // If it's an URL
  28821. if (typeof (urlOrArrayBuffer) === "string") {
  28822. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  28823. }
  28824. else {
  28825. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  28826. this._soundLoaded(urlOrArrayBuffer);
  28827. }
  28828. else {
  28829. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  28830. }
  28831. }
  28832. }
  28833. }
  28834. else {
  28835. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  28836. this._scene.mainSoundTrack.AddSound(this);
  28837. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  28838. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  28839. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  28840. }
  28841. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  28842. if (this._readyToPlayCallback) {
  28843. window.setTimeout(function () {
  28844. _this._readyToPlayCallback();
  28845. }, 1000);
  28846. }
  28847. }
  28848. }
  28849. Sound.prototype.dispose = function () {
  28850. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  28851. if (this.isPlaying) {
  28852. this.stop();
  28853. }
  28854. this._isReadyToPlay = false;
  28855. if (this.soundTrackId === -1) {
  28856. this._scene.mainSoundTrack.RemoveSound(this);
  28857. }
  28858. else {
  28859. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  28860. }
  28861. if (this._soundGain) {
  28862. this._soundGain.disconnect();
  28863. this._soundGain = null;
  28864. }
  28865. if (this._soundPanner) {
  28866. this._soundPanner.disconnect();
  28867. this._soundPanner = null;
  28868. }
  28869. if (this._soundSource) {
  28870. this._soundSource.disconnect();
  28871. this._soundSource = null;
  28872. }
  28873. this._audioBuffer = null;
  28874. if (this._connectedMesh) {
  28875. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  28876. this._connectedMesh = null;
  28877. }
  28878. }
  28879. };
  28880. Sound.prototype._soundLoaded = function (audioData) {
  28881. var _this = this;
  28882. this._isLoaded = true;
  28883. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  28884. _this._audioBuffer = buffer;
  28885. _this._isReadyToPlay = true;
  28886. if (_this.autoplay) {
  28887. _this.play();
  28888. }
  28889. if (_this._readyToPlayCallback) {
  28890. _this._readyToPlayCallback();
  28891. }
  28892. }, function (error) { BABYLON.Tools.Error("Error while decoding audio data: " + error.err); });
  28893. };
  28894. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  28895. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28896. this._audioBuffer = audioBuffer;
  28897. this._isReadyToPlay = true;
  28898. }
  28899. };
  28900. Sound.prototype.updateOptions = function (options) {
  28901. if (options) {
  28902. this.loop = options.loop || this.loop;
  28903. this.maxDistance = options.maxDistance || this.maxDistance;
  28904. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  28905. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  28906. this.refDistance = options.refDistance || this.refDistance;
  28907. this.distanceModel = options.distanceModel || this.distanceModel;
  28908. this._playbackRate = options.playbackRate || this._playbackRate;
  28909. this._updateSpatialParameters();
  28910. if (this.isPlaying) {
  28911. this._soundSource.playbackRate.value = this._playbackRate;
  28912. }
  28913. }
  28914. };
  28915. Sound.prototype._createSpatialParameters = function () {
  28916. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28917. if (this._scene.headphone) {
  28918. this._panningModel = "HRTF";
  28919. }
  28920. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  28921. this._updateSpatialParameters();
  28922. this._soundPanner.connect(this._ouputAudioNode);
  28923. this._inputAudioNode = this._soundPanner;
  28924. }
  28925. };
  28926. Sound.prototype._updateSpatialParameters = function () {
  28927. if (this.spatialSound) {
  28928. if (this.useCustomAttenuation) {
  28929. // Tricks to disable in a way embedded Web Audio attenuation
  28930. this._soundPanner.distanceModel = "linear";
  28931. this._soundPanner.maxDistance = Number.MAX_VALUE;
  28932. this._soundPanner.refDistance = 1;
  28933. this._soundPanner.rolloffFactor = 1;
  28934. this._soundPanner.panningModel = this._panningModel;
  28935. }
  28936. else {
  28937. this._soundPanner.distanceModel = this.distanceModel;
  28938. this._soundPanner.maxDistance = this.maxDistance;
  28939. this._soundPanner.refDistance = this.refDistance;
  28940. this._soundPanner.rolloffFactor = this.rolloffFactor;
  28941. this._soundPanner.panningModel = this._panningModel;
  28942. }
  28943. }
  28944. };
  28945. Sound.prototype.switchPanningModelToHRTF = function () {
  28946. this._panningModel = "HRTF";
  28947. this._switchPanningModel();
  28948. };
  28949. Sound.prototype.switchPanningModelToEqualPower = function () {
  28950. this._panningModel = "equalpower";
  28951. this._switchPanningModel();
  28952. };
  28953. Sound.prototype._switchPanningModel = function () {
  28954. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  28955. this._soundPanner.panningModel = this._panningModel;
  28956. }
  28957. };
  28958. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  28959. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28960. this._ouputAudioNode.disconnect();
  28961. this._ouputAudioNode.connect(soundTrackAudioNode);
  28962. }
  28963. };
  28964. /**
  28965. * Transform this sound into a directional source
  28966. * @param coneInnerAngle Size of the inner cone in degree
  28967. * @param coneOuterAngle Size of the outer cone in degree
  28968. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  28969. */
  28970. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  28971. if (coneOuterAngle < coneInnerAngle) {
  28972. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  28973. return;
  28974. }
  28975. this._coneInnerAngle = coneInnerAngle;
  28976. this._coneOuterAngle = coneOuterAngle;
  28977. this._coneOuterGain = coneOuterGain;
  28978. this._isDirectional = true;
  28979. if (this.isPlaying && this.loop) {
  28980. this.stop();
  28981. this.play();
  28982. }
  28983. };
  28984. Sound.prototype.setPosition = function (newPosition) {
  28985. this._position = newPosition;
  28986. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  28987. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  28988. }
  28989. };
  28990. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  28991. this._localDirection = newLocalDirection;
  28992. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  28993. this._updateDirection();
  28994. }
  28995. };
  28996. Sound.prototype._updateDirection = function () {
  28997. var mat = this._connectedMesh.getWorldMatrix();
  28998. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  28999. direction.normalize();
  29000. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  29001. };
  29002. Sound.prototype.updateDistanceFromListener = function () {
  29003. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  29004. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  29005. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  29006. }
  29007. };
  29008. Sound.prototype.setAttenuationFunction = function (callback) {
  29009. this._customAttenuationFunction = callback;
  29010. };
  29011. /**
  29012. * Play the sound
  29013. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  29014. */
  29015. Sound.prototype.play = function (time) {
  29016. var _this = this;
  29017. if (this._isReadyToPlay && this._scene.audioEnabled) {
  29018. try {
  29019. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  29020. if (!this._soundSource) {
  29021. if (this.spatialSound) {
  29022. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  29023. if (this._isDirectional) {
  29024. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  29025. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  29026. this._soundPanner.coneOuterGain = this._coneOuterGain;
  29027. if (this._connectedMesh) {
  29028. this._updateDirection();
  29029. }
  29030. else {
  29031. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  29032. }
  29033. }
  29034. }
  29035. }
  29036. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  29037. this._soundSource.buffer = this._audioBuffer;
  29038. this._soundSource.connect(this._inputAudioNode);
  29039. this._soundSource.loop = this.loop;
  29040. this._soundSource.playbackRate.value = this._playbackRate;
  29041. this._startTime = startTime;
  29042. this._soundSource.onended = function () { _this._onended(); };
  29043. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  29044. this.isPlaying = true;
  29045. this.isPaused = false;
  29046. }
  29047. catch (ex) {
  29048. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  29049. }
  29050. }
  29051. };
  29052. Sound.prototype._onended = function () {
  29053. this.isPlaying = false;
  29054. if (this.onended) {
  29055. this.onended();
  29056. }
  29057. };
  29058. /**
  29059. * Stop the sound
  29060. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  29061. */
  29062. Sound.prototype.stop = function (time) {
  29063. if (this.isPlaying) {
  29064. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  29065. this._soundSource.stop(stopTime);
  29066. this.isPlaying = false;
  29067. }
  29068. };
  29069. Sound.prototype.pause = function () {
  29070. if (this.isPlaying) {
  29071. this.stop(0);
  29072. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  29073. this.isPaused = true;
  29074. }
  29075. };
  29076. Sound.prototype.setVolume = function (newVolume, time) {
  29077. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29078. if (time) {
  29079. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  29080. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  29081. }
  29082. else {
  29083. this._soundGain.gain.value = newVolume;
  29084. }
  29085. }
  29086. this._volume = newVolume;
  29087. };
  29088. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  29089. this._playbackRate = newPlaybackRate;
  29090. if (this.isPlaying) {
  29091. this._soundSource.playbackRate.value = this._playbackRate;
  29092. }
  29093. };
  29094. Sound.prototype.getVolume = function () {
  29095. return this._volume;
  29096. };
  29097. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  29098. var _this = this;
  29099. this._connectedMesh = meshToConnectTo;
  29100. if (!this.spatialSound) {
  29101. this.spatialSound = true;
  29102. this._createSpatialParameters();
  29103. if (this.isPlaying && this.loop) {
  29104. this.stop();
  29105. this.play();
  29106. }
  29107. }
  29108. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  29109. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  29110. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  29111. };
  29112. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  29113. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  29114. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  29115. this._updateDirection();
  29116. }
  29117. };
  29118. return Sound;
  29119. })();
  29120. BABYLON.Sound = Sound;
  29121. })(BABYLON || (BABYLON = {}));
  29122. //# sourceMappingURL=babylon.sound.js.map
  29123. var BABYLON;
  29124. (function (BABYLON) {
  29125. var SoundTrack = (function () {
  29126. function SoundTrack(scene, options) {
  29127. this.id = -1;
  29128. this._isMainTrack = false;
  29129. this._scene = scene;
  29130. this._audioEngine = BABYLON.Engine.audioEngine;
  29131. this.soundCollection = new Array();
  29132. if (this._audioEngine.canUseWebAudio) {
  29133. this._outputAudioNode = this._audioEngine.audioContext.createGain();
  29134. this._outputAudioNode.connect(this._audioEngine.masterGain);
  29135. if (options) {
  29136. if (options.volume) {
  29137. this._outputAudioNode.gain.value = options.volume;
  29138. }
  29139. if (options.mainTrack) {
  29140. this._isMainTrack = options.mainTrack;
  29141. }
  29142. }
  29143. }
  29144. if (!this._isMainTrack) {
  29145. this._scene.soundTracks.push(this);
  29146. this.id = this._scene.soundTracks.length - 1;
  29147. }
  29148. }
  29149. SoundTrack.prototype.dispose = function () {
  29150. if (this._audioEngine.canUseWebAudio) {
  29151. if (this._connectedAnalyser) {
  29152. this._connectedAnalyser.stopDebugCanvas();
  29153. }
  29154. while (this.soundCollection.length) {
  29155. this.soundCollection[0].dispose();
  29156. }
  29157. this._outputAudioNode.disconnect();
  29158. this._outputAudioNode = null;
  29159. }
  29160. };
  29161. SoundTrack.prototype.AddSound = function (sound) {
  29162. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29163. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  29164. }
  29165. if (sound.soundTrackId) {
  29166. if (sound.soundTrackId === -1) {
  29167. this._scene.mainSoundTrack.RemoveSound(sound);
  29168. }
  29169. else {
  29170. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  29171. }
  29172. }
  29173. this.soundCollection.push(sound);
  29174. sound.soundTrackId = this.id;
  29175. };
  29176. SoundTrack.prototype.RemoveSound = function (sound) {
  29177. var index = this.soundCollection.indexOf(sound);
  29178. if (index !== -1) {
  29179. this.soundCollection.splice(index, 1);
  29180. }
  29181. };
  29182. SoundTrack.prototype.setVolume = function (newVolume) {
  29183. if (this._audioEngine.canUseWebAudio) {
  29184. this._outputAudioNode.gain.value = newVolume;
  29185. }
  29186. };
  29187. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  29188. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29189. for (var i = 0; i < this.soundCollection.length; i++) {
  29190. this.soundCollection[i].switchPanningModelToHRTF();
  29191. }
  29192. }
  29193. };
  29194. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  29195. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29196. for (var i = 0; i < this.soundCollection.length; i++) {
  29197. this.soundCollection[i].switchPanningModelToEqualPower();
  29198. }
  29199. }
  29200. };
  29201. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  29202. if (this._connectedAnalyser) {
  29203. this._connectedAnalyser.stopDebugCanvas();
  29204. }
  29205. this._connectedAnalyser = analyser;
  29206. if (this._audioEngine.canUseWebAudio) {
  29207. this._outputAudioNode.disconnect();
  29208. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, this._audioEngine.masterGain);
  29209. }
  29210. };
  29211. return SoundTrack;
  29212. })();
  29213. BABYLON.SoundTrack = SoundTrack;
  29214. })(BABYLON || (BABYLON = {}));
  29215. //# sourceMappingURL=babylon.soundtrack.js.map
  29216. var BABYLON;
  29217. (function (BABYLON) {
  29218. var DebugLayer = (function () {
  29219. function DebugLayer(scene) {
  29220. var _this = this;
  29221. this._transformationMatrix = BABYLON.Matrix.Identity();
  29222. this._enabled = false;
  29223. this._labelsEnabled = false;
  29224. this._displayStatistics = true;
  29225. this._displayTree = false;
  29226. this._displayLogs = false;
  29227. this._identityMatrix = BABYLON.Matrix.Identity();
  29228. this.axisRatio = 0.02;
  29229. this.accentColor = "orange";
  29230. this._scene = scene;
  29231. this._syncPositions = function () {
  29232. var engine = _this._scene.getEngine();
  29233. var canvasRect = engine.getRenderingCanvasClientRect();
  29234. if (_this._showUI) {
  29235. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  29236. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  29237. _this._statsDiv.style.width = "400px";
  29238. _this._statsDiv.style.height = "auto";
  29239. _this._statsSubsetDiv.style.maxHeight = "240px";
  29240. _this._optionsDiv.style.left = "0px";
  29241. _this._optionsDiv.style.top = "10px";
  29242. _this._optionsDiv.style.width = "200px";
  29243. _this._optionsDiv.style.height = "auto";
  29244. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  29245. _this._logDiv.style.left = "0px";
  29246. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  29247. _this._logDiv.style.width = "600px";
  29248. _this._logDiv.style.height = "160px";
  29249. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  29250. _this._treeDiv.style.top = "10px";
  29251. _this._treeDiv.style.width = "300px";
  29252. _this._treeDiv.style.height = "auto";
  29253. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  29254. }
  29255. _this._globalDiv.style.left = canvasRect.left + "px";
  29256. _this._globalDiv.style.top = canvasRect.top + "px";
  29257. _this._drawingCanvas.style.left = "0px";
  29258. _this._drawingCanvas.style.top = "0px";
  29259. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  29260. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  29261. var devicePixelRatio = window.devicePixelRatio || 1;
  29262. var context = _this._drawingContext;
  29263. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  29264. context.mozBackingStorePixelRatio ||
  29265. context.msBackingStorePixelRatio ||
  29266. context.oBackingStorePixelRatio ||
  29267. context.backingStorePixelRatio || 1;
  29268. _this._ratio = devicePixelRatio / backingStoreRatio;
  29269. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  29270. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  29271. };
  29272. this._onCanvasClick = function (evt) {
  29273. _this._clickPosition = {
  29274. x: evt.clientX * _this._ratio,
  29275. y: evt.clientY * _this._ratio
  29276. };
  29277. };
  29278. this._syncUI = function () {
  29279. if (_this._showUI) {
  29280. if (_this._displayStatistics) {
  29281. _this._displayStats();
  29282. _this._statsDiv.style.display = "";
  29283. }
  29284. else {
  29285. _this._statsDiv.style.display = "none";
  29286. }
  29287. if (_this._displayLogs) {
  29288. _this._logDiv.style.display = "";
  29289. }
  29290. else {
  29291. _this._logDiv.style.display = "none";
  29292. }
  29293. if (_this._displayTree) {
  29294. _this._treeDiv.style.display = "";
  29295. if (_this._needToRefreshMeshesTree) {
  29296. _this._needToRefreshMeshesTree = false;
  29297. _this._refreshMeshesTreeContent();
  29298. }
  29299. }
  29300. else {
  29301. _this._treeDiv.style.display = "none";
  29302. }
  29303. }
  29304. };
  29305. this._syncData = function () {
  29306. if (_this._labelsEnabled || !_this._showUI) {
  29307. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  29308. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  29309. var engine = _this._scene.getEngine();
  29310. var viewport = _this._camera.viewport;
  29311. var globalViewport = viewport.toGlobal(engine);
  29312. // Meshes
  29313. var meshes = _this._camera.getActiveMeshes();
  29314. for (var index = 0; index < meshes.length; index++) {
  29315. var mesh = meshes.data[index];
  29316. var position = mesh.getBoundingInfo().boundingSphere.center;
  29317. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29318. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  29319. _this._renderAxis(projectedPosition, mesh, globalViewport);
  29320. }
  29321. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  29322. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  29323. }
  29324. }
  29325. // Cameras
  29326. var cameras = _this._scene.cameras;
  29327. for (index = 0; index < cameras.length; index++) {
  29328. var camera = cameras[index];
  29329. if (camera === _this._camera) {
  29330. continue;
  29331. }
  29332. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29333. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  29334. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  29335. _this._camera.detachControl(engine.getRenderingCanvas());
  29336. _this._camera = camera;
  29337. _this._camera.attachControl(engine.getRenderingCanvas());
  29338. }, function () { return "purple"; });
  29339. }
  29340. }
  29341. // Lights
  29342. var lights = _this._scene.lights;
  29343. for (index = 0; index < lights.length; index++) {
  29344. var light = lights[index];
  29345. if (light.position) {
  29346. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  29347. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  29348. _this._renderLabel(light.name, projectedPosition, -20, function () {
  29349. light.setEnabled(!light.isEnabled());
  29350. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  29351. }
  29352. }
  29353. }
  29354. }
  29355. _this._clickPosition = undefined;
  29356. };
  29357. }
  29358. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  29359. while (this._treeSubsetDiv.hasChildNodes()) {
  29360. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  29361. }
  29362. // Add meshes
  29363. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  29364. sortedArray.sort(function (a, b) {
  29365. if (a.name === b.name) {
  29366. return 0;
  29367. }
  29368. return (a.name > b.name) ? 1 : -1;
  29369. });
  29370. for (var index = 0; index < sortedArray.length; index++) {
  29371. var mesh = sortedArray[index];
  29372. if (!mesh.isEnabled()) {
  29373. continue;
  29374. }
  29375. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  29376. m.isVisible = element.checked;
  29377. }, mesh);
  29378. }
  29379. };
  29380. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  29381. this._drawingContext.beginPath();
  29382. this._drawingContext.moveTo(zero.x, zero.y);
  29383. this._drawingContext.lineTo(unit.x, unit.y);
  29384. this._drawingContext.strokeStyle = color;
  29385. this._drawingContext.lineWidth = 4;
  29386. this._drawingContext.stroke();
  29387. this._drawingContext.font = "normal 14px Segoe UI";
  29388. this._drawingContext.fillStyle = color;
  29389. this._drawingContext.fillText(label, unitText.x, unitText.y);
  29390. };
  29391. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  29392. var position = mesh.getBoundingInfo().boundingSphere.center;
  29393. var worldMatrix = mesh.getWorldMatrix();
  29394. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  29395. var unit = (unprojectedVector.subtract(position)).length();
  29396. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29397. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29398. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  29399. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29400. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29401. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  29402. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  29403. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  29404. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  29405. };
  29406. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  29407. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  29408. this._drawingContext.font = "normal 12px Segoe UI";
  29409. var textMetrics = this._drawingContext.measureText(text);
  29410. var centerX = projectedPosition.x - textMetrics.width / 2;
  29411. var centerY = projectedPosition.y;
  29412. var clientRect = this._drawingCanvas.getBoundingClientRect();
  29413. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  29414. onClick();
  29415. }
  29416. this._drawingContext.beginPath();
  29417. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  29418. this._drawingContext.fillStyle = getFillStyle();
  29419. this._drawingContext.globalAlpha = 0.5;
  29420. this._drawingContext.fill();
  29421. this._drawingContext.globalAlpha = 1.0;
  29422. this._drawingContext.strokeStyle = '#FFFFFF';
  29423. this._drawingContext.lineWidth = 1;
  29424. this._drawingContext.stroke();
  29425. this._drawingContext.fillStyle = "#FFFFFF";
  29426. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  29427. this._drawingContext.beginPath();
  29428. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  29429. this._drawingContext.fill();
  29430. }
  29431. };
  29432. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  29433. if (!this._clickPosition) {
  29434. return false;
  29435. }
  29436. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  29437. return false;
  29438. }
  29439. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  29440. return false;
  29441. }
  29442. return true;
  29443. };
  29444. DebugLayer.prototype.isVisible = function () {
  29445. return this._enabled;
  29446. };
  29447. DebugLayer.prototype.hide = function () {
  29448. if (!this._enabled) {
  29449. return;
  29450. }
  29451. this._enabled = false;
  29452. var engine = this._scene.getEngine();
  29453. this._scene.unregisterBeforeRender(this._syncData);
  29454. this._scene.unregisterAfterRender(this._syncUI);
  29455. document.body.removeChild(this._globalDiv);
  29456. window.removeEventListener("resize", this._syncPositions);
  29457. this._scene.forceShowBoundingBoxes = false;
  29458. this._scene.forceWireframe = false;
  29459. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  29460. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  29461. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  29462. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  29463. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  29464. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  29465. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  29466. this._scene.shadowsEnabled = true;
  29467. this._scene.particlesEnabled = true;
  29468. this._scene.postProcessesEnabled = true;
  29469. this._scene.collisionsEnabled = true;
  29470. this._scene.lightsEnabled = true;
  29471. this._scene.texturesEnabled = true;
  29472. this._scene.lensFlaresEnabled = true;
  29473. this._scene.proceduralTexturesEnabled = true;
  29474. this._scene.renderTargetsEnabled = true;
  29475. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  29476. };
  29477. DebugLayer.prototype.show = function (showUI, camera) {
  29478. if (showUI === void 0) { showUI = true; }
  29479. if (camera === void 0) { camera = null; }
  29480. if (this._enabled) {
  29481. return;
  29482. }
  29483. this._enabled = true;
  29484. if (camera) {
  29485. this._camera = camera;
  29486. }
  29487. else {
  29488. this._camera = this._scene.activeCamera;
  29489. }
  29490. this._showUI = showUI;
  29491. var engine = this._scene.getEngine();
  29492. this._globalDiv = document.createElement("div");
  29493. document.body.appendChild(this._globalDiv);
  29494. this._generateDOMelements();
  29495. window.addEventListener("resize", this._syncPositions);
  29496. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  29497. this._syncPositions();
  29498. this._scene.registerBeforeRender(this._syncData);
  29499. this._scene.registerAfterRender(this._syncUI);
  29500. };
  29501. DebugLayer.prototype._clearLabels = function () {
  29502. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  29503. for (var index = 0; index < this._scene.meshes.length; index++) {
  29504. var mesh = this._scene.meshes[index];
  29505. mesh.renderOverlay = false;
  29506. }
  29507. };
  29508. DebugLayer.prototype._generateheader = function (root, text) {
  29509. var header = document.createElement("div");
  29510. header.innerHTML = text + "&nbsp;";
  29511. header.style.textAlign = "right";
  29512. header.style.width = "100%";
  29513. header.style.color = "white";
  29514. header.style.backgroundColor = "Black";
  29515. header.style.padding = "5px 5px 4px 0px";
  29516. header.style.marginLeft = "-5px";
  29517. header.style.fontWeight = "bold";
  29518. root.appendChild(header);
  29519. };
  29520. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  29521. var label = document.createElement("label");
  29522. label.innerHTML = title;
  29523. label.style.color = color;
  29524. root.appendChild(label);
  29525. root.appendChild(document.createElement("br"));
  29526. };
  29527. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  29528. if (tag === void 0) { tag = null; }
  29529. var label = document.createElement("label");
  29530. var boundingBoxesCheckbox = document.createElement("input");
  29531. boundingBoxesCheckbox.type = "checkbox";
  29532. boundingBoxesCheckbox.checked = initialState;
  29533. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  29534. task(evt.target, tag);
  29535. });
  29536. label.appendChild(boundingBoxesCheckbox);
  29537. var container = document.createElement("span");
  29538. var leftPart = document.createElement("span");
  29539. var rightPart = document.createElement("span");
  29540. rightPart.style.cssFloat = "right";
  29541. leftPart.innerHTML = leftTitle;
  29542. rightPart.innerHTML = rightTitle;
  29543. rightPart.style.fontSize = "12px";
  29544. rightPart.style.maxWidth = "200px";
  29545. container.appendChild(leftPart);
  29546. container.appendChild(rightPart);
  29547. label.appendChild(container);
  29548. root.appendChild(label);
  29549. root.appendChild(document.createElement("br"));
  29550. };
  29551. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  29552. if (tag === void 0) { tag = null; }
  29553. var label = document.createElement("label");
  29554. var checkBox = document.createElement("input");
  29555. checkBox.type = "checkbox";
  29556. checkBox.checked = initialState;
  29557. checkBox.addEventListener("change", function (evt) {
  29558. task(evt.target, tag);
  29559. });
  29560. label.appendChild(checkBox);
  29561. label.appendChild(document.createTextNode(title));
  29562. root.appendChild(label);
  29563. root.appendChild(document.createElement("br"));
  29564. };
  29565. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  29566. if (tag === void 0) { tag = null; }
  29567. var button = document.createElement("button");
  29568. button.innerHTML = title;
  29569. button.style.height = "24px";
  29570. button.style.color = "#444444";
  29571. button.style.border = "1px solid white";
  29572. button.className = "debugLayerButton";
  29573. button.addEventListener("click", function (evt) {
  29574. task(evt.target, tag);
  29575. });
  29576. root.appendChild(button);
  29577. root.appendChild(document.createElement("br"));
  29578. };
  29579. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  29580. if (tag === void 0) { tag = null; }
  29581. var label = document.createElement("label");
  29582. var boundingBoxesRadio = document.createElement("input");
  29583. boundingBoxesRadio.type = "radio";
  29584. boundingBoxesRadio.name = name;
  29585. boundingBoxesRadio.checked = initialState;
  29586. boundingBoxesRadio.addEventListener("change", function (evt) {
  29587. task(evt.target, tag);
  29588. });
  29589. label.appendChild(boundingBoxesRadio);
  29590. label.appendChild(document.createTextNode(title));
  29591. root.appendChild(label);
  29592. root.appendChild(document.createElement("br"));
  29593. };
  29594. DebugLayer.prototype._generateDOMelements = function () {
  29595. var _this = this;
  29596. this._globalDiv.id = "DebugLayer";
  29597. this._globalDiv.style.position = "absolute";
  29598. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  29599. this._globalDiv.style.fontSize = "14px";
  29600. this._globalDiv.style.color = "white";
  29601. // Drawing canvas
  29602. this._drawingCanvas = document.createElement("canvas");
  29603. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  29604. this._drawingCanvas.style.position = "absolute";
  29605. this._drawingCanvas.style.pointerEvents = "none";
  29606. this._drawingContext = this._drawingCanvas.getContext("2d");
  29607. this._globalDiv.appendChild(this._drawingCanvas);
  29608. if (this._showUI) {
  29609. var background = "rgba(128, 128, 128, 0.4)";
  29610. var border = "rgb(180, 180, 180) solid 1px";
  29611. // Stats
  29612. this._statsDiv = document.createElement("div");
  29613. this._statsDiv.id = "DebugLayerStats";
  29614. this._statsDiv.style.border = border;
  29615. this._statsDiv.style.position = "absolute";
  29616. this._statsDiv.style.background = background;
  29617. this._statsDiv.style.padding = "0px 0px 0px 5px";
  29618. this._generateheader(this._statsDiv, "STATISTICS");
  29619. this._statsSubsetDiv = document.createElement("div");
  29620. this._statsSubsetDiv.style.paddingTop = "5px";
  29621. this._statsSubsetDiv.style.paddingBottom = "5px";
  29622. this._statsSubsetDiv.style.overflowY = "auto";
  29623. this._statsDiv.appendChild(this._statsSubsetDiv);
  29624. // Tree
  29625. this._treeDiv = document.createElement("div");
  29626. this._treeDiv.id = "DebugLayerTree";
  29627. this._treeDiv.style.border = border;
  29628. this._treeDiv.style.position = "absolute";
  29629. this._treeDiv.style.background = background;
  29630. this._treeDiv.style.padding = "0px 0px 0px 5px";
  29631. this._treeDiv.style.display = "none";
  29632. this._generateheader(this._treeDiv, "MESHES TREE");
  29633. this._treeSubsetDiv = document.createElement("div");
  29634. this._treeSubsetDiv.style.paddingTop = "5px";
  29635. this._treeSubsetDiv.style.paddingRight = "5px";
  29636. this._treeSubsetDiv.style.overflowY = "auto";
  29637. this._treeSubsetDiv.style.maxHeight = "300px";
  29638. this._treeDiv.appendChild(this._treeSubsetDiv);
  29639. this._needToRefreshMeshesTree = true;
  29640. // Logs
  29641. this._logDiv = document.createElement("div");
  29642. this._logDiv.style.border = border;
  29643. this._logDiv.id = "DebugLayerLogs";
  29644. this._logDiv.style.position = "absolute";
  29645. this._logDiv.style.background = background;
  29646. this._logDiv.style.padding = "0px 0px 0px 5px";
  29647. this._logDiv.style.display = "none";
  29648. this._generateheader(this._logDiv, "LOGS");
  29649. this._logSubsetDiv = document.createElement("div");
  29650. this._logSubsetDiv.style.height = "127px";
  29651. this._logSubsetDiv.style.paddingTop = "5px";
  29652. this._logSubsetDiv.style.overflowY = "auto";
  29653. this._logSubsetDiv.style.fontSize = "12px";
  29654. this._logSubsetDiv.style.fontFamily = "consolas";
  29655. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  29656. this._logDiv.appendChild(this._logSubsetDiv);
  29657. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  29658. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  29659. };
  29660. // Options
  29661. this._optionsDiv = document.createElement("div");
  29662. this._optionsDiv.id = "DebugLayerOptions";
  29663. this._optionsDiv.style.border = border;
  29664. this._optionsDiv.style.position = "absolute";
  29665. this._optionsDiv.style.background = background;
  29666. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  29667. this._optionsDiv.style.overflowY = "auto";
  29668. this._generateheader(this._optionsDiv, "OPTIONS");
  29669. this._optionsSubsetDiv = document.createElement("div");
  29670. this._optionsSubsetDiv.style.paddingTop = "5px";
  29671. this._optionsSubsetDiv.style.paddingBottom = "5px";
  29672. this._optionsSubsetDiv.style.overflowY = "auto";
  29673. this._optionsSubsetDiv.style.maxHeight = "200px";
  29674. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  29675. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  29676. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  29677. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  29678. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  29679. _this._displayTree = element.checked;
  29680. _this._needToRefreshMeshesTree = true;
  29681. });
  29682. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29683. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  29684. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  29685. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  29686. _this._labelsEnabled = element.checked;
  29687. if (!_this._labelsEnabled) {
  29688. _this._clearLabels();
  29689. }
  29690. });
  29691. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  29692. if (element.checked) {
  29693. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  29694. }
  29695. else {
  29696. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  29697. }
  29698. });
  29699. ;
  29700. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29701. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  29702. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  29703. if (element.checked) {
  29704. _this._scene.forceWireframe = false;
  29705. _this._scene.forcePointsCloud = false;
  29706. }
  29707. });
  29708. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  29709. if (element.checked) {
  29710. _this._scene.forceWireframe = true;
  29711. _this._scene.forcePointsCloud = false;
  29712. }
  29713. });
  29714. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  29715. if (element.checked) {
  29716. _this._scene.forceWireframe = false;
  29717. _this._scene.forcePointsCloud = true;
  29718. }
  29719. });
  29720. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29721. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  29722. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  29723. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  29724. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  29725. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  29726. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  29727. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  29728. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  29729. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  29730. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29731. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  29732. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  29733. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  29734. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  29735. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  29736. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  29737. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  29738. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  29739. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  29740. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  29741. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  29742. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  29743. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  29744. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  29745. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29746. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29747. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  29748. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  29749. if (element.checked) {
  29750. _this._scene.headphone = true;
  29751. }
  29752. });
  29753. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  29754. if (element.checked) {
  29755. _this._scene.headphone = false;
  29756. }
  29757. });
  29758. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  29759. _this._scene.audioEnabled = !element.checked;
  29760. });
  29761. }
  29762. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29763. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  29764. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  29765. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29766. this._globalDiv.appendChild(this._statsDiv);
  29767. this._globalDiv.appendChild(this._logDiv);
  29768. this._globalDiv.appendChild(this._optionsDiv);
  29769. this._globalDiv.appendChild(this._treeDiv);
  29770. }
  29771. };
  29772. DebugLayer.prototype._displayStats = function () {
  29773. var scene = this._scene;
  29774. var engine = scene.getEngine();
  29775. var glInfo = engine.getGlInfo();
  29776. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  29777. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29778. + "<b>Count</b><br>"
  29779. + "Total meshes: " + scene.meshes.length + "<br>"
  29780. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  29781. + "Total materials: " + scene.materials.length + "<br>"
  29782. + "Total textures: " + scene.textures.length + "<br>"
  29783. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  29784. + "Active indices: " + scene.getActiveIndices() + "<br>"
  29785. + "Active bones: " + scene.getActiveBones() + "<br>"
  29786. + "Active particles: " + scene.getActiveParticles() + "<br>"
  29787. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  29788. + "<b>Duration</b><br>"
  29789. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  29790. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  29791. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  29792. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  29793. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  29794. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  29795. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  29796. + "</div>"
  29797. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29798. + "<b>Extensions</b><br>"
  29799. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  29800. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  29801. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  29802. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  29803. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  29804. + "<b>Caps.</b><br>"
  29805. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  29806. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  29807. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  29808. + "</div><br>"
  29809. + "<b>Info</b><br>"
  29810. + glInfo.version + "<br>"
  29811. + glInfo.renderer + "<br>";
  29812. if (this.customStatsFunction) {
  29813. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  29814. }
  29815. };
  29816. return DebugLayer;
  29817. })();
  29818. BABYLON.DebugLayer = DebugLayer;
  29819. })(BABYLON || (BABYLON = {}));
  29820. //# sourceMappingURL=babylon.debugLayer.js.map
  29821. var BABYLON;
  29822. (function (BABYLON) {
  29823. var RawTexture = (function (_super) {
  29824. __extends(RawTexture, _super);
  29825. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  29826. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29827. if (invertY === void 0) { invertY = false; }
  29828. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29829. _super.call(this, null, scene, !generateMipMaps, invertY);
  29830. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  29831. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29832. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29833. }
  29834. // Statics
  29835. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29836. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29837. if (invertY === void 0) { invertY = false; }
  29838. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29839. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  29840. };
  29841. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29842. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29843. if (invertY === void 0) { invertY = false; }
  29844. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29845. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  29846. };
  29847. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29848. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29849. if (invertY === void 0) { invertY = false; }
  29850. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29851. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  29852. };
  29853. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29854. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29855. if (invertY === void 0) { invertY = false; }
  29856. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29857. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  29858. };
  29859. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29860. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29861. if (invertY === void 0) { invertY = false; }
  29862. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29863. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  29864. };
  29865. return RawTexture;
  29866. })(BABYLON.Texture);
  29867. BABYLON.RawTexture = RawTexture;
  29868. })(BABYLON || (BABYLON = {}));
  29869. //# sourceMappingURL=babylon.rawTexture.js.map
  29870. var BABYLON;
  29871. (function (BABYLON) {
  29872. var IndexedVector2 = (function (_super) {
  29873. __extends(IndexedVector2, _super);
  29874. function IndexedVector2(original, index) {
  29875. _super.call(this, original.x, original.y);
  29876. this.index = index;
  29877. }
  29878. return IndexedVector2;
  29879. })(BABYLON.Vector2);
  29880. var PolygonPoints = (function () {
  29881. function PolygonPoints() {
  29882. this.elements = new Array();
  29883. }
  29884. PolygonPoints.prototype.add = function (originalPoints) {
  29885. var _this = this;
  29886. var result = new Array();
  29887. originalPoints.forEach(function (point) {
  29888. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  29889. var newPoint = new IndexedVector2(point, _this.elements.length);
  29890. result.push(newPoint);
  29891. _this.elements.push(newPoint);
  29892. }
  29893. });
  29894. return result;
  29895. };
  29896. PolygonPoints.prototype.computeBounds = function () {
  29897. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  29898. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  29899. this.elements.forEach(function (point) {
  29900. // x
  29901. if (point.x < lmin.x) {
  29902. lmin.x = point.x;
  29903. }
  29904. else if (point.x > lmax.x) {
  29905. lmax.x = point.x;
  29906. }
  29907. // y
  29908. if (point.y < lmin.y) {
  29909. lmin.y = point.y;
  29910. }
  29911. else if (point.y > lmax.y) {
  29912. lmax.y = point.y;
  29913. }
  29914. });
  29915. return {
  29916. min: lmin,
  29917. max: lmax,
  29918. width: lmax.x - lmin.x,
  29919. height: lmax.y - lmin.y
  29920. };
  29921. };
  29922. return PolygonPoints;
  29923. })();
  29924. var Polygon = (function () {
  29925. function Polygon() {
  29926. }
  29927. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  29928. return [
  29929. new BABYLON.Vector2(xmin, ymin),
  29930. new BABYLON.Vector2(xmax, ymin),
  29931. new BABYLON.Vector2(xmax, ymax),
  29932. new BABYLON.Vector2(xmin, ymax)
  29933. ];
  29934. };
  29935. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  29936. if (cx === void 0) { cx = 0; }
  29937. if (cy === void 0) { cy = 0; }
  29938. if (numberOfSides === void 0) { numberOfSides = 32; }
  29939. var result = new Array();
  29940. var angle = 0;
  29941. var increment = (Math.PI * 2) / numberOfSides;
  29942. for (var i = 0; i < numberOfSides; i++) {
  29943. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  29944. angle -= increment;
  29945. }
  29946. return result;
  29947. };
  29948. Polygon.Parse = function (input) {
  29949. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  29950. var i, result = [];
  29951. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  29952. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  29953. }
  29954. return result;
  29955. };
  29956. Polygon.StartingAt = function (x, y) {
  29957. return BABYLON.Path2.StartingAt(x, y);
  29958. };
  29959. return Polygon;
  29960. })();
  29961. BABYLON.Polygon = Polygon;
  29962. var PolygonMeshBuilder = (function () {
  29963. function PolygonMeshBuilder(name, contours, scene) {
  29964. this._points = new PolygonPoints();
  29965. this._outlinepoints = new PolygonPoints();
  29966. this._holes = [];
  29967. if (!("poly2tri" in window)) {
  29968. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  29969. }
  29970. this._name = name;
  29971. this._scene = scene;
  29972. var points;
  29973. if (contours instanceof BABYLON.Path2) {
  29974. points = contours.getPoints();
  29975. }
  29976. else {
  29977. points = contours;
  29978. }
  29979. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  29980. this._outlinepoints.add(points);
  29981. }
  29982. PolygonMeshBuilder.prototype.addHole = function (hole) {
  29983. this._swctx.addHole(this._points.add(hole));
  29984. var holepoints = new PolygonPoints();
  29985. holepoints.add(hole);
  29986. this._holes.push(holepoints);
  29987. return this;
  29988. };
  29989. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  29990. var _this = this;
  29991. if (updatable === void 0) { updatable = false; }
  29992. var result = new BABYLON.Mesh(this._name, this._scene);
  29993. var normals = [];
  29994. var positions = [];
  29995. var uvs = [];
  29996. var bounds = this._points.computeBounds();
  29997. this._points.elements.forEach(function (p) {
  29998. normals.push(0, 1.0, 0);
  29999. positions.push(p.x, 0, p.y);
  30000. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  30001. });
  30002. var indices = [];
  30003. this._swctx.triangulate();
  30004. this._swctx.getTriangles().forEach(function (triangle) {
  30005. triangle.getPoints().forEach(function (point) {
  30006. indices.push(point.index);
  30007. });
  30008. });
  30009. if (depth > 0) {
  30010. var positionscount = (positions.length / 3); //get the current pointcount
  30011. this._points.elements.forEach(function (p) {
  30012. normals.push(0, -1.0, 0);
  30013. positions.push(p.x, -depth, p.y);
  30014. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  30015. });
  30016. var p1; //we need to change order of point so the triangles are made in the rigth way.
  30017. var p2;
  30018. var poscounter = 0;
  30019. this._swctx.getTriangles().forEach(function (triangle) {
  30020. triangle.getPoints().forEach(function (point) {
  30021. switch (poscounter) {
  30022. case 0:
  30023. p1 = point;
  30024. break;
  30025. case 1:
  30026. p2 = point;
  30027. break;
  30028. case 2:
  30029. indices.push(point.index + positionscount);
  30030. indices.push(p2.index + positionscount);
  30031. indices.push(p1.index + positionscount);
  30032. poscounter = -1;
  30033. break;
  30034. }
  30035. poscounter++;
  30036. //indices.push((<IndexedVector2>point).index + positionscount);
  30037. });
  30038. });
  30039. //Add the sides
  30040. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  30041. this._holes.forEach(function (hole) {
  30042. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  30043. });
  30044. }
  30045. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  30046. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  30047. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  30048. result.setIndices(indices);
  30049. return result;
  30050. };
  30051. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  30052. var StartIndex = positions.length / 3;
  30053. var ulength = 0;
  30054. for (var i = 0; i < points.elements.length; i++) {
  30055. var p = points.elements[i];
  30056. var p1;
  30057. if ((i + 1) > points.elements.length - 1) {
  30058. p1 = points.elements[0];
  30059. }
  30060. else {
  30061. p1 = points.elements[i + 1];
  30062. }
  30063. positions.push(p.x, 0, p.y);
  30064. positions.push(p.x, -depth, p.y);
  30065. positions.push(p1.x, 0, p1.y);
  30066. positions.push(p1.x, -depth, p1.y);
  30067. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  30068. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  30069. var v3 = v2.subtract(v1);
  30070. var v4 = new BABYLON.Vector3(0, 1, 0);
  30071. var vn = BABYLON.Vector3.Cross(v3, v4);
  30072. vn = vn.normalize();
  30073. uvs.push(ulength / bounds.width, 0);
  30074. uvs.push(ulength / bounds.width, 1);
  30075. ulength += v3.length();
  30076. uvs.push((ulength / bounds.width), 0);
  30077. uvs.push((ulength / bounds.width), 1);
  30078. if (!flip) {
  30079. normals.push(-vn.x, -vn.y, -vn.z);
  30080. normals.push(-vn.x, -vn.y, -vn.z);
  30081. normals.push(-vn.x, -vn.y, -vn.z);
  30082. normals.push(-vn.x, -vn.y, -vn.z);
  30083. indices.push(StartIndex);
  30084. indices.push(StartIndex + 1);
  30085. indices.push(StartIndex + 2);
  30086. indices.push(StartIndex + 1);
  30087. indices.push(StartIndex + 3);
  30088. indices.push(StartIndex + 2);
  30089. }
  30090. else {
  30091. normals.push(vn.x, vn.y, vn.z);
  30092. normals.push(vn.x, vn.y, vn.z);
  30093. normals.push(vn.x, vn.y, vn.z);
  30094. normals.push(vn.x, vn.y, vn.z);
  30095. indices.push(StartIndex);
  30096. indices.push(StartIndex + 2);
  30097. indices.push(StartIndex + 1);
  30098. indices.push(StartIndex + 1);
  30099. indices.push(StartIndex + 2);
  30100. indices.push(StartIndex + 3);
  30101. }
  30102. StartIndex += 4;
  30103. }
  30104. ;
  30105. };
  30106. return PolygonMeshBuilder;
  30107. })();
  30108. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  30109. })(BABYLON || (BABYLON = {}));
  30110. //# sourceMappingURL=babylon.polygonMesh.js.map
  30111. var BABYLON;
  30112. (function (BABYLON) {
  30113. var SimplificationSettings = (function () {
  30114. function SimplificationSettings(quality, distance, optimizeMesh) {
  30115. this.quality = quality;
  30116. this.distance = distance;
  30117. this.optimizeMesh = optimizeMesh;
  30118. }
  30119. return SimplificationSettings;
  30120. })();
  30121. BABYLON.SimplificationSettings = SimplificationSettings;
  30122. var SimplificationQueue = (function () {
  30123. function SimplificationQueue() {
  30124. this.running = false;
  30125. this._simplificationArray = [];
  30126. }
  30127. SimplificationQueue.prototype.addTask = function (task) {
  30128. this._simplificationArray.push(task);
  30129. };
  30130. SimplificationQueue.prototype.executeNext = function () {
  30131. var task = this._simplificationArray.pop();
  30132. if (task) {
  30133. this.running = true;
  30134. this.runSimplification(task);
  30135. }
  30136. else {
  30137. this.running = false;
  30138. }
  30139. };
  30140. SimplificationQueue.prototype.runSimplification = function (task) {
  30141. var _this = this;
  30142. if (task.parallelProcessing) {
  30143. //parallel simplifier
  30144. task.settings.forEach(function (setting) {
  30145. var simplifier = _this.getSimplifier(task);
  30146. simplifier.simplify(setting, function (newMesh) {
  30147. task.mesh.addLODLevel(setting.distance, newMesh);
  30148. newMesh.isVisible = true;
  30149. //check if it is the last
  30150. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  30151. //all done, run the success callback.
  30152. task.successCallback();
  30153. }
  30154. _this.executeNext();
  30155. });
  30156. });
  30157. }
  30158. else {
  30159. //single simplifier.
  30160. var simplifier = this.getSimplifier(task);
  30161. var runDecimation = function (setting, callback) {
  30162. simplifier.simplify(setting, function (newMesh) {
  30163. task.mesh.addLODLevel(setting.distance, newMesh);
  30164. newMesh.isVisible = true;
  30165. //run the next quality level
  30166. callback();
  30167. });
  30168. };
  30169. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  30170. runDecimation(task.settings[loop.index], function () {
  30171. loop.executeNext();
  30172. });
  30173. }, function () {
  30174. //execution ended, run the success callback.
  30175. if (task.successCallback) {
  30176. task.successCallback();
  30177. }
  30178. _this.executeNext();
  30179. });
  30180. }
  30181. };
  30182. SimplificationQueue.prototype.getSimplifier = function (task) {
  30183. switch (task.simplificationType) {
  30184. case SimplificationType.QUADRATIC:
  30185. default:
  30186. return new QuadraticErrorSimplification(task.mesh);
  30187. }
  30188. };
  30189. return SimplificationQueue;
  30190. })();
  30191. BABYLON.SimplificationQueue = SimplificationQueue;
  30192. /**
  30193. * The implemented types of simplification.
  30194. * At the moment only Quadratic Error Decimation is implemented.
  30195. */
  30196. (function (SimplificationType) {
  30197. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  30198. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  30199. var SimplificationType = BABYLON.SimplificationType;
  30200. var DecimationTriangle = (function () {
  30201. function DecimationTriangle(vertices) {
  30202. this.vertices = vertices;
  30203. this.error = new Array(4);
  30204. this.deleted = false;
  30205. this.isDirty = false;
  30206. this.deletePending = false;
  30207. this.borderFactor = 0;
  30208. }
  30209. return DecimationTriangle;
  30210. })();
  30211. BABYLON.DecimationTriangle = DecimationTriangle;
  30212. var DecimationVertex = (function () {
  30213. function DecimationVertex(position, id) {
  30214. this.position = position;
  30215. this.id = id;
  30216. this.isBorder = true;
  30217. this.q = new QuadraticMatrix();
  30218. this.triangleCount = 0;
  30219. this.triangleStart = 0;
  30220. this.originalOffsets = [];
  30221. }
  30222. DecimationVertex.prototype.updatePosition = function (newPosition) {
  30223. this.position.copyFrom(newPosition);
  30224. };
  30225. return DecimationVertex;
  30226. })();
  30227. BABYLON.DecimationVertex = DecimationVertex;
  30228. var QuadraticMatrix = (function () {
  30229. function QuadraticMatrix(data) {
  30230. this.data = new Array(10);
  30231. for (var i = 0; i < 10; ++i) {
  30232. if (data && data[i]) {
  30233. this.data[i] = data[i];
  30234. }
  30235. else {
  30236. this.data[i] = 0;
  30237. }
  30238. }
  30239. }
  30240. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  30241. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  30242. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  30243. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  30244. return det;
  30245. };
  30246. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  30247. for (var i = 0; i < 10; ++i) {
  30248. this.data[i] += matrix.data[i];
  30249. }
  30250. };
  30251. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  30252. for (var i = 0; i < 10; ++i) {
  30253. this.data[i] += data[i];
  30254. }
  30255. };
  30256. QuadraticMatrix.prototype.add = function (matrix) {
  30257. var m = new QuadraticMatrix();
  30258. for (var i = 0; i < 10; ++i) {
  30259. m.data[i] = this.data[i] + matrix.data[i];
  30260. }
  30261. return m;
  30262. };
  30263. QuadraticMatrix.FromData = function (a, b, c, d) {
  30264. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  30265. };
  30266. //returning an array to avoid garbage collection
  30267. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  30268. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  30269. };
  30270. return QuadraticMatrix;
  30271. })();
  30272. BABYLON.QuadraticMatrix = QuadraticMatrix;
  30273. var Reference = (function () {
  30274. function Reference(vertexId, triangleId) {
  30275. this.vertexId = vertexId;
  30276. this.triangleId = triangleId;
  30277. }
  30278. return Reference;
  30279. })();
  30280. BABYLON.Reference = Reference;
  30281. /**
  30282. * An implementation of the Quadratic Error simplification algorithm.
  30283. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  30284. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  30285. * @author RaananW
  30286. */
  30287. var QuadraticErrorSimplification = (function () {
  30288. function QuadraticErrorSimplification(_mesh) {
  30289. this._mesh = _mesh;
  30290. this.initialized = false;
  30291. this.syncIterations = 5000;
  30292. this.aggressiveness = 7;
  30293. this.decimationIterations = 100;
  30294. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  30295. }
  30296. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  30297. var _this = this;
  30298. this.initDecimatedMesh();
  30299. //iterating through the submeshes array, one after the other.
  30300. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  30301. _this.initWithMesh(loop.index, function () {
  30302. _this.runDecimation(settings, loop.index, function () {
  30303. loop.executeNext();
  30304. });
  30305. }, settings.optimizeMesh);
  30306. }, function () {
  30307. setTimeout(function () {
  30308. successCallback(_this._reconstructedMesh);
  30309. }, 0);
  30310. });
  30311. };
  30312. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  30313. var _this = this;
  30314. var gCount = 0;
  30315. triangle.vertices.forEach(function (vertex) {
  30316. var count = 0;
  30317. var vPos = vertex.position;
  30318. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  30319. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  30320. ++count;
  30321. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  30322. ++count;
  30323. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  30324. ++count;
  30325. if (count > 1) {
  30326. ++gCount;
  30327. }
  30328. ;
  30329. });
  30330. if (gCount > 1) {
  30331. console.log(triangle, gCount);
  30332. }
  30333. return gCount > 1;
  30334. };
  30335. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  30336. var _this = this;
  30337. var targetCount = ~~(this.triangles.length * settings.quality);
  30338. var deletedTriangles = 0;
  30339. var triangleCount = this.triangles.length;
  30340. var iterationFunction = function (iteration, callback) {
  30341. setTimeout(function () {
  30342. if (iteration % 5 === 0) {
  30343. _this.updateMesh(iteration === 0);
  30344. }
  30345. for (var i = 0; i < _this.triangles.length; ++i) {
  30346. _this.triangles[i].isDirty = false;
  30347. }
  30348. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  30349. var trianglesIterator = function (i) {
  30350. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  30351. var t = _this.triangles[tIdx];
  30352. if (!t)
  30353. return;
  30354. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  30355. return;
  30356. }
  30357. for (var j = 0; j < 3; ++j) {
  30358. if (t.error[j] < threshold) {
  30359. var deleted0 = [];
  30360. var deleted1 = [];
  30361. var v0 = t.vertices[j];
  30362. var v1 = t.vertices[(j + 1) % 3];
  30363. if (v0.isBorder !== v1.isBorder)
  30364. continue;
  30365. var p = BABYLON.Vector3.Zero();
  30366. var n = BABYLON.Vector3.Zero();
  30367. var uv = BABYLON.Vector2.Zero();
  30368. var color = new BABYLON.Color4(0, 0, 0, 1);
  30369. _this.calculateError(v0, v1, p, n, uv, color);
  30370. var delTr = [];
  30371. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  30372. continue;
  30373. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  30374. continue;
  30375. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  30376. continue;
  30377. var uniqueArray = [];
  30378. delTr.forEach(function (deletedT) {
  30379. if (uniqueArray.indexOf(deletedT) === -1) {
  30380. deletedT.deletePending = true;
  30381. uniqueArray.push(deletedT);
  30382. }
  30383. });
  30384. if (uniqueArray.length % 2 != 0) {
  30385. continue;
  30386. }
  30387. v0.q = v1.q.add(v0.q);
  30388. v0.updatePosition(p);
  30389. var tStart = _this.references.length;
  30390. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  30391. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  30392. var tCount = _this.references.length - tStart;
  30393. if (tCount <= v0.triangleCount) {
  30394. if (tCount) {
  30395. for (var c = 0; c < tCount; c++) {
  30396. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  30397. }
  30398. }
  30399. }
  30400. else {
  30401. v0.triangleStart = tStart;
  30402. }
  30403. v0.triangleCount = tCount;
  30404. break;
  30405. }
  30406. }
  30407. };
  30408. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  30409. }, 0);
  30410. };
  30411. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  30412. if (triangleCount - deletedTriangles <= targetCount)
  30413. loop.breakLoop();
  30414. else {
  30415. iterationFunction(loop.index, function () {
  30416. loop.executeNext();
  30417. });
  30418. }
  30419. }, function () {
  30420. setTimeout(function () {
  30421. //reconstruct this part of the mesh
  30422. _this.reconstructMesh(submeshIndex);
  30423. successCallback();
  30424. }, 0);
  30425. });
  30426. };
  30427. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  30428. var _this = this;
  30429. this.vertices = [];
  30430. this.triangles = [];
  30431. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30432. var indices = this._mesh.getIndices();
  30433. var submesh = this._mesh.subMeshes[submeshIndex];
  30434. var findInVertices = function (positionToSearch) {
  30435. if (optimizeMesh) {
  30436. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  30437. if (_this.vertices[ii].position.equals(positionToSearch)) {
  30438. return _this.vertices[ii];
  30439. }
  30440. }
  30441. }
  30442. return null;
  30443. };
  30444. var vertexReferences = [];
  30445. var vertexInit = function (i) {
  30446. var offset = i + submesh.verticesStart;
  30447. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  30448. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  30449. vertex.originalOffsets.push(offset);
  30450. if (vertex.id == _this.vertices.length) {
  30451. _this.vertices.push(vertex);
  30452. }
  30453. vertexReferences.push(vertex.id);
  30454. };
  30455. //var totalVertices = mesh.getTotalVertices();
  30456. var totalVertices = submesh.verticesCount;
  30457. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  30458. var indicesInit = function (i) {
  30459. var offset = (submesh.indexStart / 3) + i;
  30460. var pos = (offset * 3);
  30461. var i0 = indices[pos + 0];
  30462. var i1 = indices[pos + 1];
  30463. var i2 = indices[pos + 2];
  30464. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  30465. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  30466. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  30467. var triangle = new DecimationTriangle([v0, v1, v2]);
  30468. triangle.originalOffset = pos;
  30469. _this.triangles.push(triangle);
  30470. };
  30471. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  30472. _this.init(callback);
  30473. });
  30474. });
  30475. };
  30476. QuadraticErrorSimplification.prototype.init = function (callback) {
  30477. var _this = this;
  30478. var triangleInit1 = function (i) {
  30479. var t = _this.triangles[i];
  30480. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  30481. for (var j = 0; j < 3; j++) {
  30482. 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))));
  30483. }
  30484. };
  30485. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  30486. var triangleInit2 = function (i) {
  30487. var t = _this.triangles[i];
  30488. for (var j = 0; j < 3; ++j) {
  30489. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  30490. }
  30491. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30492. };
  30493. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  30494. _this.initialized = true;
  30495. callback();
  30496. });
  30497. });
  30498. };
  30499. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  30500. var newTriangles = [];
  30501. var i;
  30502. for (i = 0; i < this.vertices.length; ++i) {
  30503. this.vertices[i].triangleCount = 0;
  30504. }
  30505. var t;
  30506. var j;
  30507. for (i = 0; i < this.triangles.length; ++i) {
  30508. if (!this.triangles[i].deleted) {
  30509. t = this.triangles[i];
  30510. for (j = 0; j < 3; ++j) {
  30511. t.vertices[j].triangleCount = 1;
  30512. }
  30513. newTriangles.push(t);
  30514. }
  30515. }
  30516. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  30517. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  30518. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  30519. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  30520. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30521. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30522. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  30523. var vertexCount = 0;
  30524. for (i = 0; i < this.vertices.length; ++i) {
  30525. var vertex = this.vertices[i];
  30526. vertex.id = vertexCount;
  30527. if (vertex.triangleCount) {
  30528. vertex.originalOffsets.forEach(function (originalOffset) {
  30529. newPositionData.push(vertex.position.x);
  30530. newPositionData.push(vertex.position.y);
  30531. newPositionData.push(vertex.position.z);
  30532. newNormalData.push(normalData[originalOffset * 3]);
  30533. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  30534. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  30535. if (uvs && uvs.length) {
  30536. newUVsData.push(uvs[(originalOffset * 2)]);
  30537. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  30538. }
  30539. else if (colorsData && colorsData.length) {
  30540. newColorsData.push(colorsData[(originalOffset * 4)]);
  30541. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  30542. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  30543. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  30544. }
  30545. ++vertexCount;
  30546. });
  30547. }
  30548. }
  30549. var startingIndex = this._reconstructedMesh.getTotalIndices();
  30550. var startingVertex = this._reconstructedMesh.getTotalVertices();
  30551. var submeshesArray = this._reconstructedMesh.subMeshes;
  30552. this._reconstructedMesh.subMeshes = [];
  30553. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  30554. var originalIndices = this._mesh.getIndices();
  30555. for (i = 0; i < newTriangles.length; ++i) {
  30556. var t = newTriangles[i];
  30557. //now get the new referencing point for each vertex
  30558. [0, 1, 2].forEach(function (idx) {
  30559. var id = originalIndices[t.originalOffset + idx];
  30560. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  30561. if (offset < 0)
  30562. offset = 0;
  30563. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  30564. });
  30565. }
  30566. //overwriting the old vertex buffers and indices.
  30567. this._reconstructedMesh.setIndices(newIndicesArray);
  30568. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  30569. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  30570. if (newUVsData.length > 0)
  30571. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  30572. if (newColorsData.length > 0)
  30573. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  30574. //create submesh
  30575. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  30576. if (submeshIndex > 0) {
  30577. this._reconstructedMesh.subMeshes = [];
  30578. submeshesArray.forEach(function (submesh) {
  30579. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  30580. });
  30581. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  30582. }
  30583. };
  30584. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  30585. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  30586. this._reconstructedMesh.material = this._mesh.material;
  30587. this._reconstructedMesh.parent = this._mesh.parent;
  30588. this._reconstructedMesh.isVisible = false;
  30589. };
  30590. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  30591. for (var i = 0; i < vertex1.triangleCount; ++i) {
  30592. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  30593. if (t.deleted)
  30594. continue;
  30595. var s = this.references[vertex1.triangleStart + i].vertexId;
  30596. var v1 = t.vertices[(s + 1) % 3];
  30597. var v2 = t.vertices[(s + 2) % 3];
  30598. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  30599. deletedArray[i] = true;
  30600. delTr.push(t);
  30601. continue;
  30602. }
  30603. var d1 = v1.position.subtract(point);
  30604. d1 = d1.normalize();
  30605. var d2 = v2.position.subtract(point);
  30606. d2 = d2.normalize();
  30607. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  30608. return true;
  30609. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  30610. deletedArray[i] = false;
  30611. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  30612. return true;
  30613. }
  30614. return false;
  30615. };
  30616. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  30617. var newDeleted = deletedTriangles;
  30618. for (var i = 0; i < vertex.triangleCount; ++i) {
  30619. var ref = this.references[vertex.triangleStart + i];
  30620. var t = this.triangles[ref.triangleId];
  30621. if (t.deleted)
  30622. continue;
  30623. if (deletedArray[i] && t.deletePending) {
  30624. t.deleted = true;
  30625. newDeleted++;
  30626. continue;
  30627. }
  30628. t.vertices[ref.vertexId] = origVertex;
  30629. t.isDirty = true;
  30630. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  30631. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  30632. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  30633. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30634. this.references.push(ref);
  30635. }
  30636. return newDeleted;
  30637. };
  30638. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  30639. for (var i = 0; i < this.vertices.length; ++i) {
  30640. var vCount = [];
  30641. var vId = [];
  30642. var v = this.vertices[i];
  30643. var j;
  30644. for (j = 0; j < v.triangleCount; ++j) {
  30645. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  30646. for (var ii = 0; ii < 3; ii++) {
  30647. var ofs = 0;
  30648. var vv = triangle.vertices[ii];
  30649. while (ofs < vCount.length) {
  30650. if (vId[ofs] === vv.id)
  30651. break;
  30652. ++ofs;
  30653. }
  30654. if (ofs === vCount.length) {
  30655. vCount.push(1);
  30656. vId.push(vv.id);
  30657. }
  30658. else {
  30659. vCount[ofs]++;
  30660. }
  30661. }
  30662. }
  30663. for (j = 0; j < vCount.length; ++j) {
  30664. if (vCount[j] === 1) {
  30665. this.vertices[vId[j]].isBorder = true;
  30666. }
  30667. else {
  30668. this.vertices[vId[j]].isBorder = false;
  30669. }
  30670. }
  30671. }
  30672. };
  30673. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  30674. if (identifyBorders === void 0) { identifyBorders = false; }
  30675. var i;
  30676. if (!identifyBorders) {
  30677. var newTrianglesVector = [];
  30678. for (i = 0; i < this.triangles.length; ++i) {
  30679. if (!this.triangles[i].deleted) {
  30680. newTrianglesVector.push(this.triangles[i]);
  30681. }
  30682. }
  30683. this.triangles = newTrianglesVector;
  30684. }
  30685. for (i = 0; i < this.vertices.length; ++i) {
  30686. this.vertices[i].triangleCount = 0;
  30687. this.vertices[i].triangleStart = 0;
  30688. }
  30689. var t;
  30690. var j;
  30691. var v;
  30692. for (i = 0; i < this.triangles.length; ++i) {
  30693. t = this.triangles[i];
  30694. for (j = 0; j < 3; ++j) {
  30695. v = t.vertices[j];
  30696. v.triangleCount++;
  30697. }
  30698. }
  30699. var tStart = 0;
  30700. for (i = 0; i < this.vertices.length; ++i) {
  30701. this.vertices[i].triangleStart = tStart;
  30702. tStart += this.vertices[i].triangleCount;
  30703. this.vertices[i].triangleCount = 0;
  30704. }
  30705. var newReferences = new Array(this.triangles.length * 3);
  30706. for (i = 0; i < this.triangles.length; ++i) {
  30707. t = this.triangles[i];
  30708. for (j = 0; j < 3; ++j) {
  30709. v = t.vertices[j];
  30710. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  30711. v.triangleCount++;
  30712. }
  30713. }
  30714. this.references = newReferences;
  30715. if (identifyBorders) {
  30716. this.identifyBorder();
  30717. }
  30718. };
  30719. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  30720. var x = point.x;
  30721. var y = point.y;
  30722. var z = point.z;
  30723. 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
  30724. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  30725. };
  30726. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  30727. var q = vertex1.q.add(vertex2.q);
  30728. var border = vertex1.isBorder && vertex2.isBorder;
  30729. var error = 0;
  30730. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  30731. if (qDet !== 0 && !border) {
  30732. if (!pointResult) {
  30733. pointResult = BABYLON.Vector3.Zero();
  30734. }
  30735. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  30736. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  30737. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  30738. error = this.vertexError(q, pointResult);
  30739. }
  30740. else {
  30741. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  30742. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  30743. var error1 = this.vertexError(q, vertex1.position);
  30744. var error2 = this.vertexError(q, vertex2.position);
  30745. var error3 = this.vertexError(q, p3);
  30746. error = Math.min(error1, error2, error3);
  30747. if (error === error1) {
  30748. if (pointResult) {
  30749. pointResult.copyFrom(vertex1.position);
  30750. }
  30751. }
  30752. else if (error === error2) {
  30753. if (pointResult) {
  30754. pointResult.copyFrom(vertex2.position);
  30755. }
  30756. }
  30757. else {
  30758. if (pointResult) {
  30759. pointResult.copyFrom(p3);
  30760. }
  30761. }
  30762. }
  30763. return error;
  30764. };
  30765. return QuadraticErrorSimplification;
  30766. })();
  30767. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  30768. })(BABYLON || (BABYLON = {}));
  30769. //# sourceMappingURL=babylon.meshSimplification.js.map
  30770. var BABYLON;
  30771. (function (BABYLON) {
  30772. var Analyser = (function () {
  30773. function Analyser(scene) {
  30774. this.SMOOTHING = 0.75;
  30775. this.FFT_SIZE = 512;
  30776. this.BARGRAPHAMPLITUDE = 256;
  30777. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  30778. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  30779. this._scene = scene;
  30780. this._audioEngine = BABYLON.Engine.audioEngine;
  30781. if (this._audioEngine.canUseWebAudio) {
  30782. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  30783. this._webAudioAnalyser.minDecibels = -140;
  30784. this._webAudioAnalyser.maxDecibels = 0;
  30785. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  30786. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  30787. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  30788. }
  30789. }
  30790. Analyser.prototype.getFrequencyBinCount = function () {
  30791. if (this._audioEngine.canUseWebAudio) {
  30792. return this._webAudioAnalyser.frequencyBinCount;
  30793. }
  30794. else {
  30795. return 0;
  30796. }
  30797. };
  30798. Analyser.prototype.getByteFrequencyData = function () {
  30799. if (this._audioEngine.canUseWebAudio) {
  30800. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30801. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30802. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  30803. }
  30804. return this._byteFreqs;
  30805. };
  30806. Analyser.prototype.getByteTimeDomainData = function () {
  30807. if (this._audioEngine.canUseWebAudio) {
  30808. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30809. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30810. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  30811. }
  30812. return this._byteTime;
  30813. };
  30814. Analyser.prototype.getFloatFrequencyData = function () {
  30815. if (this._audioEngine.canUseWebAudio) {
  30816. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30817. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30818. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  30819. }
  30820. return this._floatFreqs;
  30821. };
  30822. Analyser.prototype.drawDebugCanvas = function () {
  30823. var _this = this;
  30824. if (this._audioEngine.canUseWebAudio) {
  30825. if (!this._debugCanvas) {
  30826. this._debugCanvas = document.createElement("canvas");
  30827. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  30828. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  30829. this._debugCanvas.style.position = "absolute";
  30830. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  30831. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  30832. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  30833. document.body.appendChild(this._debugCanvas);
  30834. this._registerFunc = function () {
  30835. _this.drawDebugCanvas();
  30836. };
  30837. this._scene.registerBeforeRender(this._registerFunc);
  30838. }
  30839. if (this._registerFunc) {
  30840. var workingArray = this.getByteFrequencyData();
  30841. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  30842. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  30843. // Draw the frequency domain chart.
  30844. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  30845. var value = workingArray[i];
  30846. var percent = value / this.BARGRAPHAMPLITUDE;
  30847. var height = this.DEBUGCANVASSIZE.height * percent;
  30848. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  30849. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  30850. var hue = i / this.getFrequencyBinCount() * 360;
  30851. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  30852. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  30853. }
  30854. }
  30855. }
  30856. };
  30857. Analyser.prototype.stopDebugCanvas = function () {
  30858. if (this._debugCanvas) {
  30859. this._scene.unregisterBeforeRender(this._registerFunc);
  30860. this._registerFunc = null;
  30861. document.body.removeChild(this._debugCanvas);
  30862. this._debugCanvas = null;
  30863. this._debugCanvasContext = null;
  30864. }
  30865. };
  30866. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  30867. if (this._audioEngine.canUseWebAudio) {
  30868. inputAudioNode.connect(this._webAudioAnalyser);
  30869. this._webAudioAnalyser.connect(outputAudioNode);
  30870. }
  30871. };
  30872. Analyser.prototype.dispose = function () {
  30873. if (this._audioEngine.canUseWebAudio) {
  30874. this._webAudioAnalyser.disconnect();
  30875. }
  30876. };
  30877. return Analyser;
  30878. })();
  30879. BABYLON.Analyser = Analyser;
  30880. })(BABYLON || (BABYLON = {}));
  30881. //# sourceMappingURL=babylon.analyser.js.map
  30882. var BABYLON;
  30883. (function (BABYLON) {
  30884. var DepthRenderer = (function () {
  30885. function DepthRenderer(scene, type) {
  30886. var _this = this;
  30887. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  30888. this._viewMatrix = BABYLON.Matrix.Zero();
  30889. this._projectionMatrix = BABYLON.Matrix.Zero();
  30890. this._transformMatrix = BABYLON.Matrix.Zero();
  30891. this._worldViewProjection = BABYLON.Matrix.Zero();
  30892. this._scene = scene;
  30893. var engine = scene.getEngine();
  30894. // Render target
  30895. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  30896. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30897. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30898. this._depthMap.refreshRate = 1;
  30899. this._depthMap.renderParticles = false;
  30900. this._depthMap.renderList = null;
  30901. // set default depth value to 1.0 (far away)
  30902. this._depthMap.onClear = function (engine) {
  30903. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  30904. };
  30905. // Custom render function
  30906. var renderSubMesh = function (subMesh) {
  30907. var mesh = subMesh.getRenderingMesh();
  30908. var scene = _this._scene;
  30909. var engine = scene.getEngine();
  30910. // Culling
  30911. engine.setState(subMesh.getMaterial().backFaceCulling);
  30912. // Managing instances
  30913. var batch = mesh._getInstancesRenderList(subMesh._id);
  30914. if (batch.mustReturn) {
  30915. return;
  30916. }
  30917. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  30918. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  30919. engine.enableEffect(_this._effect);
  30920. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  30921. var material = subMesh.getMaterial();
  30922. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  30923. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  30924. // Alpha test
  30925. if (material && material.needAlphaTesting()) {
  30926. var alphaTexture = material.getAlphaTestTexture();
  30927. _this._effect.setTexture("diffuseSampler", alphaTexture);
  30928. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  30929. }
  30930. // Bones
  30931. if (mesh.useBones) {
  30932. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  30933. }
  30934. // Draw
  30935. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  30936. }
  30937. };
  30938. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  30939. var index;
  30940. for (index = 0; index < opaqueSubMeshes.length; index++) {
  30941. renderSubMesh(opaqueSubMeshes.data[index]);
  30942. }
  30943. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  30944. renderSubMesh(alphaTestSubMeshes.data[index]);
  30945. }
  30946. };
  30947. }
  30948. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  30949. var defines = [];
  30950. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30951. var mesh = subMesh.getMesh();
  30952. var scene = mesh.getScene();
  30953. var material = subMesh.getMaterial();
  30954. // Alpha test
  30955. if (material && material.needAlphaTesting()) {
  30956. defines.push("#define ALPHATEST");
  30957. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30958. attribs.push(BABYLON.VertexBuffer.UVKind);
  30959. defines.push("#define UV1");
  30960. }
  30961. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30962. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30963. defines.push("#define UV2");
  30964. }
  30965. }
  30966. // Bones
  30967. if (mesh.useBones) {
  30968. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30969. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30970. defines.push("#define BONES");
  30971. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  30972. }
  30973. // Instances
  30974. if (useInstances) {
  30975. defines.push("#define INSTANCES");
  30976. attribs.push("world0");
  30977. attribs.push("world1");
  30978. attribs.push("world2");
  30979. attribs.push("world3");
  30980. }
  30981. // Get correct effect
  30982. var join = defines.join("\n");
  30983. if (this._cachedDefines !== join) {
  30984. this._cachedDefines = join;
  30985. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  30986. }
  30987. return this._effect.isReady();
  30988. };
  30989. DepthRenderer.prototype.getDepthMap = function () {
  30990. return this._depthMap;
  30991. };
  30992. // Methods
  30993. DepthRenderer.prototype.dispose = function () {
  30994. this._depthMap.dispose();
  30995. };
  30996. return DepthRenderer;
  30997. })();
  30998. BABYLON.DepthRenderer = DepthRenderer;
  30999. })(BABYLON || (BABYLON = {}));
  31000. //# sourceMappingURL=babylon.depthRenderer.js.map
  31001. var BABYLON;
  31002. (function (BABYLON) {
  31003. var SSAORenderingPipeline = (function (_super) {
  31004. __extends(SSAORenderingPipeline, _super);
  31005. /**
  31006. * @constructor
  31007. * @param {string} name - The rendering pipeline name
  31008. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  31009. * @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 }
  31010. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  31011. */
  31012. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  31013. var _this = this;
  31014. _super.call(this, scene.getEngine(), name);
  31015. // Members
  31016. /**
  31017. * The PassPostProcess id in the pipeline that contains the original scene color
  31018. * @type {string}
  31019. */
  31020. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  31021. /**
  31022. * The SSAO PostProcess id in the pipeline
  31023. * @type {string}
  31024. */
  31025. this.SSAORenderEffect = "SSAORenderEffect";
  31026. /**
  31027. * The horizontal blur PostProcess id in the pipeline
  31028. * @type {string}
  31029. */
  31030. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  31031. /**
  31032. * The vertical blur PostProcess id in the pipeline
  31033. * @type {string}
  31034. */
  31035. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  31036. /**
  31037. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  31038. * @type {string}
  31039. */
  31040. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  31041. /**
  31042. * The output strength of the SSAO post-process. Default value is 1.0.
  31043. * @type {number}
  31044. */
  31045. this.totalStrength = 1.0;
  31046. /**
  31047. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  31048. * @type {number}
  31049. */
  31050. this.radius = 0.0002;
  31051. /**
  31052. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  31053. * Must not be equal to fallOff and superior to fallOff.
  31054. * Default value is 0.0075
  31055. * @type {number}
  31056. */
  31057. this.area = 0.0075;
  31058. /**
  31059. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  31060. * Must not be equal to area and inferior to area.
  31061. * Default value is 0.0002
  31062. * @type {number}
  31063. */
  31064. this.fallOff = 0.0002;
  31065. this._firstUpdate = true;
  31066. this._scene = scene;
  31067. // Set up assets
  31068. this._createRandomTexture();
  31069. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  31070. var ssaoRatio = ratio.ssaoRatio || ratio;
  31071. var combineRatio = ratio.combineRatio || ratio;
  31072. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  31073. this._createSSAOPostProcess(ssaoRatio);
  31074. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  31075. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  31076. this._createSSAOCombinePostProcess(combineRatio);
  31077. // Set up pipeline
  31078. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  31079. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  31080. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  31081. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  31082. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  31083. // Finish
  31084. scene.postProcessRenderPipelineManager.addPipeline(this);
  31085. if (cameras)
  31086. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  31087. }
  31088. // Public Methods
  31089. /**
  31090. * Returns the horizontal blur PostProcess
  31091. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  31092. */
  31093. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  31094. return this._blurHPostProcess;
  31095. };
  31096. /**
  31097. * Returns the vertical blur PostProcess
  31098. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  31099. */
  31100. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  31101. return this._blurVPostProcess;
  31102. };
  31103. /**
  31104. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  31105. */
  31106. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  31107. if (disableDepthRender === void 0) { disableDepthRender = false; }
  31108. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  31109. this._originalColorPostProcess = undefined;
  31110. this._ssaoPostProcess = undefined;
  31111. this._blurHPostProcess = undefined;
  31112. this._blurVPostProcess = undefined;
  31113. this._ssaoCombinePostProcess = undefined;
  31114. this._randomTexture.dispose();
  31115. if (disableDepthRender)
  31116. this._scene.disableDepthRenderer();
  31117. };
  31118. // Private Methods
  31119. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  31120. var _this = this;
  31121. var sampleSphere = [
  31122. 0.5381, 0.1856, -0.4319,
  31123. 0.1379, 0.2486, 0.4430,
  31124. 0.3371, 0.5679, -0.0057,
  31125. -0.6999, -0.0451, -0.0019,
  31126. 0.0689, -0.1598, -0.8547,
  31127. 0.0560, 0.0069, -0.1843,
  31128. -0.0146, 0.1402, 0.0762,
  31129. 0.0100, -0.1924, -0.0344,
  31130. -0.3577, -0.5301, -0.4358,
  31131. -0.3169, 0.1063, 0.0158,
  31132. 0.0103, -0.5869, 0.0046,
  31133. -0.0897, -0.4940, 0.3287,
  31134. 0.7119, -0.0154, -0.0918,
  31135. -0.0533, 0.0596, -0.5411,
  31136. 0.0352, -0.0631, 0.5460,
  31137. -0.4776, 0.2847, -0.0271
  31138. ];
  31139. var samplesFactor = 1.0 / 16.0;
  31140. 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);
  31141. this._ssaoPostProcess.onApply = function (effect) {
  31142. if (_this._firstUpdate) {
  31143. effect.setArray3("sampleSphere", sampleSphere);
  31144. effect.setFloat("samplesFactor", samplesFactor);
  31145. effect.setFloat("randTextureTiles", 4.0 / ratio);
  31146. _this._firstUpdate = false;
  31147. }
  31148. effect.setFloat("totalStrength", _this.totalStrength);
  31149. effect.setFloat("radius", _this.radius);
  31150. effect.setFloat("area", _this.area);
  31151. effect.setFloat("fallOff", _this.fallOff);
  31152. effect.setTexture("textureSampler", _this._depthTexture);
  31153. effect.setTexture("randomSampler", _this._randomTexture);
  31154. };
  31155. };
  31156. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  31157. var _this = this;
  31158. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31159. this._ssaoCombinePostProcess.onApply = function (effect) {
  31160. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  31161. };
  31162. };
  31163. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  31164. var size = 512;
  31165. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31166. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31167. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31168. var context = this._randomTexture.getContext();
  31169. var rand = function (min, max) {
  31170. return Math.random() * (max - min) + min;
  31171. };
  31172. for (var x = 0; x < size; x++) {
  31173. for (var y = 0; y < size; y++) {
  31174. var randVector = BABYLON.Vector3.Zero();
  31175. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  31176. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  31177. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  31178. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  31179. context.fillRect(x, y, 1, 1);
  31180. }
  31181. }
  31182. this._randomTexture.update(false);
  31183. };
  31184. return SSAORenderingPipeline;
  31185. })(BABYLON.PostProcessRenderPipeline);
  31186. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  31187. })(BABYLON || (BABYLON = {}));
  31188. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  31189. var BABYLON;
  31190. (function (BABYLON) {
  31191. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  31192. var VolumetricLightScatteringPostProcess = (function (_super) {
  31193. __extends(VolumetricLightScatteringPostProcess, _super);
  31194. /**
  31195. * @constructor
  31196. * @param {string} name - The post-process name
  31197. * @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)
  31198. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  31199. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  31200. * @param {number} samples - The post-process quality, default 100
  31201. * @param {number} samplingMode - The post-process filtering mode
  31202. * @param {BABYLON.Engine} engine - The babylon engine
  31203. * @param {boolean} reusable - If the post-process is reusable
  31204. */
  31205. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  31206. var _this = this;
  31207. if (samples === void 0) { samples = 100; }
  31208. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  31209. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  31210. this._screenCoordinates = BABYLON.Vector2.Zero();
  31211. /**
  31212. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  31213. * @type {boolean}
  31214. */
  31215. this.useCustomMeshPosition = false;
  31216. /**
  31217. * If the post-process should inverse the light scattering direction
  31218. * @type {boolean}
  31219. */
  31220. this.invert = true;
  31221. /**
  31222. * Array containing the excluded meshes not rendered in the internal pass
  31223. */
  31224. this.excludedMeshes = new Array();
  31225. this.exposure = 0.3;
  31226. this.decay = 0.96815;
  31227. this.weight = 0.58767;
  31228. this.density = 0.926;
  31229. var scene = camera.getScene();
  31230. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  31231. // Configure mesh
  31232. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  31233. // Configure
  31234. this._createPass(scene, ratio.passRatio || ratio);
  31235. this.onApply = function (effect) {
  31236. _this._updateMeshScreenCoordinates(scene);
  31237. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  31238. effect.setFloat("exposure", _this.exposure);
  31239. effect.setFloat("decay", _this.decay);
  31240. effect.setFloat("weight", _this.weight);
  31241. effect.setFloat("density", _this.density);
  31242. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  31243. };
  31244. }
  31245. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  31246. var mesh = subMesh.getMesh();
  31247. var defines = [];
  31248. var attribs = [BABYLON.VertexBuffer.PositionKind];
  31249. var material = subMesh.getMaterial();
  31250. var needUV = false;
  31251. // Render this.mesh as default
  31252. if (mesh === this.mesh) {
  31253. defines.push("#define BASIC_RENDER");
  31254. defines.push("#define NEED_UV");
  31255. needUV = true;
  31256. }
  31257. // Alpha test
  31258. if (material) {
  31259. if (material.needAlphaTesting() || mesh === this.mesh)
  31260. defines.push("#define ALPHATEST");
  31261. if (material.opacityTexture !== undefined) {
  31262. defines.push("#define OPACITY");
  31263. if (material.opacityTexture.getAlphaFromRGB)
  31264. defines.push("#define OPACITYRGB");
  31265. if (!needUV)
  31266. defines.push("#define NEED_UV");
  31267. }
  31268. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31269. attribs.push(BABYLON.VertexBuffer.UVKind);
  31270. defines.push("#define UV1");
  31271. }
  31272. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31273. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31274. defines.push("#define UV2");
  31275. }
  31276. }
  31277. // Bones
  31278. if (mesh.useBones) {
  31279. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31280. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31281. defines.push("#define BONES");
  31282. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31283. }
  31284. // Instances
  31285. if (useInstances) {
  31286. defines.push("#define INSTANCES");
  31287. attribs.push("world0");
  31288. attribs.push("world1");
  31289. attribs.push("world2");
  31290. attribs.push("world3");
  31291. }
  31292. // Get correct effect
  31293. var join = defines.join("\n");
  31294. if (this._cachedDefines !== join) {
  31295. this._cachedDefines = join;
  31296. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel"], ["diffuseSampler", "opacitySampler"], join);
  31297. }
  31298. return this._volumetricLightScatteringPass.isReady();
  31299. };
  31300. /**
  31301. * Sets the new light position for light scattering effect
  31302. * @param {BABYLON.Vector3} The new custom light position
  31303. */
  31304. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  31305. this._customMeshPosition = position;
  31306. };
  31307. /**
  31308. * Returns the light position for light scattering effect
  31309. * @return {BABYLON.Vector3} The custom light position
  31310. */
  31311. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  31312. return this._customMeshPosition;
  31313. };
  31314. /**
  31315. * Disposes the internal assets and detaches the post-process from the camera
  31316. */
  31317. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  31318. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  31319. if (rttIndex !== -1) {
  31320. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  31321. }
  31322. this._volumetricLightScatteringRTT.dispose();
  31323. _super.prototype.dispose.call(this, camera);
  31324. };
  31325. /**
  31326. * Returns the render target texture used by the post-process
  31327. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  31328. */
  31329. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  31330. return this._volumetricLightScatteringRTT;
  31331. };
  31332. // Private methods
  31333. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  31334. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  31335. return true;
  31336. }
  31337. return false;
  31338. };
  31339. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  31340. var _this = this;
  31341. var engine = scene.getEngine();
  31342. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  31343. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31344. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31345. this._volumetricLightScatteringRTT.renderList = null;
  31346. this._volumetricLightScatteringRTT.renderParticles = false;
  31347. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  31348. // Custom render function for submeshes
  31349. var renderSubMesh = function (subMesh) {
  31350. var mesh = subMesh.getRenderingMesh();
  31351. if (_this._meshExcluded(mesh)) {
  31352. return;
  31353. }
  31354. var scene = mesh.getScene();
  31355. var engine = scene.getEngine();
  31356. // Culling
  31357. engine.setState(subMesh.getMaterial().backFaceCulling);
  31358. // Managing instances
  31359. var batch = mesh._getInstancesRenderList(subMesh._id);
  31360. if (batch.mustReturn) {
  31361. return;
  31362. }
  31363. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  31364. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  31365. engine.enableEffect(_this._volumetricLightScatteringPass);
  31366. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  31367. var material = subMesh.getMaterial();
  31368. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  31369. // Alpha test
  31370. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  31371. var alphaTexture = material.getAlphaTestTexture();
  31372. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  31373. if (alphaTexture) {
  31374. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31375. }
  31376. if (material.opacityTexture !== undefined) {
  31377. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  31378. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  31379. }
  31380. }
  31381. // Bones
  31382. if (mesh.useBones) {
  31383. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31384. }
  31385. // Draw
  31386. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  31387. }
  31388. };
  31389. // Render target texture callbacks
  31390. var savedSceneClearColor;
  31391. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  31392. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  31393. savedSceneClearColor = scene.clearColor;
  31394. scene.clearColor = sceneClearColor;
  31395. };
  31396. this._volumetricLightScatteringRTT.onAfterRender = function () {
  31397. scene.clearColor = savedSceneClearColor;
  31398. };
  31399. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  31400. var engine = scene.getEngine();
  31401. var index;
  31402. for (index = 0; index < opaqueSubMeshes.length; index++) {
  31403. renderSubMesh(opaqueSubMeshes.data[index]);
  31404. }
  31405. engine.setAlphaTesting(true);
  31406. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  31407. renderSubMesh(alphaTestSubMeshes.data[index]);
  31408. }
  31409. engine.setAlphaTesting(false);
  31410. if (transparentSubMeshes.length) {
  31411. // Sort sub meshes
  31412. for (index = 0; index < transparentSubMeshes.length; index++) {
  31413. var submesh = transparentSubMeshes.data[index];
  31414. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  31415. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  31416. }
  31417. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  31418. sortedArray.sort(function (a, b) {
  31419. // Alpha index first
  31420. if (a._alphaIndex > b._alphaIndex) {
  31421. return 1;
  31422. }
  31423. if (a._alphaIndex < b._alphaIndex) {
  31424. return -1;
  31425. }
  31426. // Then distance to camera
  31427. if (a._distanceToCamera < b._distanceToCamera) {
  31428. return 1;
  31429. }
  31430. if (a._distanceToCamera > b._distanceToCamera) {
  31431. return -1;
  31432. }
  31433. return 0;
  31434. });
  31435. // Render sub meshes
  31436. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31437. for (index = 0; index < sortedArray.length; index++) {
  31438. renderSubMesh(sortedArray[index]);
  31439. }
  31440. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31441. }
  31442. };
  31443. };
  31444. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  31445. var transform = scene.getTransformMatrix();
  31446. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  31447. this._screenCoordinates.x = pos.x / this._viewPort.width;
  31448. this._screenCoordinates.y = pos.y / this._viewPort.height;
  31449. if (this.invert)
  31450. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  31451. };
  31452. // Static methods
  31453. /**
  31454. * Creates a default mesh for the Volumeric Light Scattering post-process
  31455. * @param {string} The mesh name
  31456. * @param {BABYLON.Scene} The scene where to create the mesh
  31457. * @return {BABYLON.Mesh} the default mesh
  31458. */
  31459. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  31460. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  31461. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  31462. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  31463. return mesh;
  31464. };
  31465. return VolumetricLightScatteringPostProcess;
  31466. })(BABYLON.PostProcess);
  31467. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  31468. })(BABYLON || (BABYLON = {}));
  31469. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  31470. var BABYLON;
  31471. (function (BABYLON) {
  31472. var LensRenderingPipeline = (function (_super) {
  31473. __extends(LensRenderingPipeline, _super);
  31474. /**
  31475. * @constructor
  31476. *
  31477. * Effect parameters are as follow:
  31478. * {
  31479. * chromatic_aberration: number; // from 0 to x (1 for realism)
  31480. * edge_blur: number; // from 0 to x (1 for realism)
  31481. * distortion: number; // from 0 to x (1 for realism)
  31482. * grain_amount: number; // from 0 to 1
  31483. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  31484. * dof_focus_depth: number; // depth-of-field: focus depth; unset to disable (disabled by default)
  31485. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  31486. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  31487. * dof_gain: number; // depth-of-field: depthOfField gain; unset to disable (disabled by default)
  31488. * dof_threshold: number; // depth-of-field: depthOfField threshold (default: 1)
  31489. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  31490. * }
  31491. * Note: if an effect parameter is unset, effect is disabled
  31492. *
  31493. * @param {string} name - The rendering pipeline name
  31494. * @param {object} parameters - An object containing all parameters (see above)
  31495. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  31496. * @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)
  31497. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  31498. */
  31499. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  31500. var _this = this;
  31501. if (ratio === void 0) { ratio = 1.0; }
  31502. _super.call(this, scene.getEngine(), name);
  31503. // Lens effects can be of the following:
  31504. // - chromatic aberration (slight shift of RGB colors)
  31505. // - blur on the edge of the lens
  31506. // - lens distortion
  31507. // - depth-of-field blur & highlights enhancing
  31508. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  31509. // - grain effect (noise or custom texture)
  31510. // Two additional texture samplers are needed:
  31511. // - depth map (for depth-of-field)
  31512. // - grain texture
  31513. /**
  31514. * The chromatic aberration PostProcess id in the pipeline
  31515. * @type {string}
  31516. */
  31517. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  31518. /**
  31519. * The highlights enhancing PostProcess id in the pipeline
  31520. * @type {string}
  31521. */
  31522. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  31523. /**
  31524. * The depth-of-field PostProcess id in the pipeline
  31525. * @type {string}
  31526. */
  31527. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  31528. this._scene = scene;
  31529. // Fetch texture samplers
  31530. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  31531. if (parameters.grain_texture) {
  31532. this._grainTexture = parameters.grain_texture;
  31533. }
  31534. else {
  31535. this._createGrainTexture();
  31536. }
  31537. // save parameters
  31538. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  31539. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  31540. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  31541. this._distortion = parameters.distortion ? parameters.distortion : 0;
  31542. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  31543. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  31544. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  31545. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  31546. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  31547. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  31548. // Create effects
  31549. this._createChromaticAberrationPostProcess(ratio);
  31550. this._createHighlightsPostProcess(ratio);
  31551. this._createDepthOfFieldPostProcess(ratio);
  31552. // Set up pipeline
  31553. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  31554. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  31555. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  31556. if (this._highlightsGain == -1) {
  31557. this._disableEffect(this.HighlightsEnhancingEffect, null);
  31558. }
  31559. // Finish
  31560. scene.postProcessRenderPipelineManager.addPipeline(this);
  31561. if (cameras) {
  31562. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  31563. }
  31564. }
  31565. // public methods (self explanatory)
  31566. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  31567. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  31568. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  31569. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  31570. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  31571. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  31572. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  31573. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  31574. LensRenderingPipeline.prototype.setFocusDepth = function (amount) { this._dofDepth = amount; };
  31575. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDepth = -1; };
  31576. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  31577. LensRenderingPipeline.prototype.enablePentagonBokeh = function () { this._dofPentagon = true; };
  31578. LensRenderingPipeline.prototype.disablePentagonBokeh = function () { this._dofPentagon = false; };
  31579. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  31580. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  31581. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  31582. this._highlightsGain = amount;
  31583. };
  31584. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  31585. if (this._highlightsGain == -1) {
  31586. this._highlightsGain = 1.0;
  31587. }
  31588. this._highlightsThreshold = amount;
  31589. };
  31590. LensRenderingPipeline.prototype.disableHighlights = function () {
  31591. this._highlightsGain = -1;
  31592. };
  31593. /**
  31594. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  31595. */
  31596. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  31597. if (disableDepthRender === void 0) { disableDepthRender = false; }
  31598. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  31599. this._chromaticAberrationPostProcess = undefined;
  31600. this._highlightsPostProcess = undefined;
  31601. this._depthOfFieldPostProcess = undefined;
  31602. this._grainTexture.dispose();
  31603. if (disableDepthRender)
  31604. this._scene.disableDepthRenderer();
  31605. };
  31606. // colors shifting and distortion
  31607. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  31608. var _this = this;
  31609. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31610. this._chromaticAberrationPostProcess.onApply = function (effect) {
  31611. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  31612. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31613. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31614. };
  31615. };
  31616. // highlights enhancing
  31617. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  31618. var _this = this;
  31619. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31620. this._highlightsPostProcess.onApply = function (effect) {
  31621. effect.setFloat('gain', _this._highlightsGain);
  31622. effect.setFloat('threshold', _this._highlightsThreshold);
  31623. effect.setBool('pentagon', _this._dofPentagon);
  31624. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  31625. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31626. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31627. };
  31628. };
  31629. // colors shifting and distortion
  31630. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  31631. var _this = this;
  31632. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  31633. "focus_depth", "aperture", "pentagon", "maxZ", "edge_blur", "chromatic_aberration",
  31634. "distortion", "blur_noise", "grain_amount", "screen_width", "screen_height", "highlights"
  31635. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31636. this._depthOfFieldPostProcess.onApply = function (effect) {
  31637. effect.setBool('blur_noise', _this._blurNoise);
  31638. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  31639. effect.setFloat('grain_amount', _this._grainAmount);
  31640. effect.setTexture("depthSampler", _this._depthTexture);
  31641. effect.setTexture("grainSampler", _this._grainTexture);
  31642. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  31643. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  31644. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31645. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31646. effect.setFloat('distortion', _this._distortion);
  31647. effect.setFloat('focus_depth', _this._dofDepth);
  31648. effect.setFloat('aperture', _this._dofAperture);
  31649. effect.setFloat('edge_blur', _this._edgeBlur);
  31650. effect.setBool('highlights', (_this._highlightsGain != -1));
  31651. };
  31652. };
  31653. // creates a black and white random noise texture, 512x512
  31654. LensRenderingPipeline.prototype._createGrainTexture = function () {
  31655. var size = 512;
  31656. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31657. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31658. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31659. var context = this._grainTexture.getContext();
  31660. var rand = function (min, max) {
  31661. return Math.random() * (max - min) + min;
  31662. };
  31663. var value;
  31664. for (var x = 0; x < size; x++) {
  31665. for (var y = 0; y < size; y++) {
  31666. value = Math.floor(rand(0.42, 0.58) * 255);
  31667. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  31668. context.fillRect(x, y, 1, 1);
  31669. }
  31670. }
  31671. this._grainTexture.update(false);
  31672. };
  31673. return LensRenderingPipeline;
  31674. })(BABYLON.PostProcessRenderPipeline);
  31675. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  31676. })(BABYLON || (BABYLON = {}));
  31677. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  31678. //
  31679. // This post-process allows the modification of rendered colors by using
  31680. // a 'look-up table' (LUT). This effect is also called Color Grading.
  31681. //
  31682. // The object needs to be provided an url to a texture containing the color
  31683. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  31684. // Use an image editing software to tweak the LUT to match your needs.
  31685. //
  31686. // For an example of a color LUT, see here:
  31687. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  31688. // For explanations on color grading, see here:
  31689. // http://udn.epicgames.com/Three/ColorGrading.html
  31690. //
  31691. var BABYLON;
  31692. (function (BABYLON) {
  31693. var ColorCorrectionPostProcess = (function (_super) {
  31694. __extends(ColorCorrectionPostProcess, _super);
  31695. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  31696. var _this = this;
  31697. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  31698. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  31699. this._colorTableTexture.anisotropicFilteringLevel = 1;
  31700. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31701. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31702. this.onApply = function (effect) {
  31703. effect.setTexture("colorTable", _this._colorTableTexture);
  31704. };
  31705. }
  31706. return ColorCorrectionPostProcess;
  31707. })(BABYLON.PostProcess);
  31708. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  31709. })(BABYLON || (BABYLON = {}));
  31710. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  31711. var BABYLON;
  31712. (function (BABYLON) {
  31713. var StereoscopicFreeCamera = (function (_super) {
  31714. __extends(StereoscopicFreeCamera, _super);
  31715. function StereoscopicFreeCamera(name, position, eyeSpace, isVertical, scene) {
  31716. _super.call(this, name, position, scene);
  31717. this.setSubCameraMode(isVertical ? BABYLON.Camera.SUB_CAMERA_MODE_OVERUNDER_STEREOSCOPIC : BABYLON.Camera.SUB_CAMERA_MODE_CROSSEDSIDEBYSIDE_STEREOSCOPIC, eyeSpace);
  31718. }
  31719. return StereoscopicFreeCamera;
  31720. })(BABYLON.FreeCamera);
  31721. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  31722. var StereoscopicArcRotateCamera = (function (_super) {
  31723. __extends(StereoscopicArcRotateCamera, _super);
  31724. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, isVertical, scene) {
  31725. _super.call(this, name, alpha, beta, radius, target, scene);
  31726. this.setSubCameraMode(isVertical ? BABYLON.Camera.SUB_CAMERA_MODE_OVERUNDER_STEREOSCOPIC : BABYLON.Camera.SUB_CAMERA_MODE_CROSSEDSIDEBYSIDE_STEREOSCOPIC, eyeSpace);
  31727. }
  31728. return StereoscopicArcRotateCamera;
  31729. })(BABYLON.ArcRotateCamera);
  31730. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  31731. var StereoscopicGamepadCamera = (function (_super) {
  31732. __extends(StereoscopicGamepadCamera, _super);
  31733. function StereoscopicGamepadCamera(name, position, eyeSpace, isVertical, scene) {
  31734. _super.call(this, name, position, scene);
  31735. this.setSubCameraMode(isVertical ? BABYLON.Camera.SUB_CAMERA_MODE_OVERUNDER_STEREOSCOPIC : BABYLON.Camera.SUB_CAMERA_MODE_CROSSEDSIDEBYSIDE_STEREOSCOPIC, eyeSpace);
  31736. }
  31737. return StereoscopicGamepadCamera;
  31738. })(BABYLON.GamepadCamera);
  31739. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  31740. })(BABYLON || (BABYLON = {}));
  31741. //# sourceMappingURL=babylon.stereoscopicCamera.js.map
  31742. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D leftSampler;\r\n\r\nvoid main(void)\r\n{\r\n vec4 leftFrag = texture2D(leftSampler, vUV);\r\n leftFrag = vec4(1.0, leftFrag.g, leftFrag.b, 1.0);\r\n\r\n\tvec4 rightFrag = texture2D(textureSampler, vUV);\r\n rightFrag = vec4(rightFrag.r, 1.0, 1.0, 1.0);\r\n\r\n gl_FragColor = vec4(rightFrag.rgb * leftFrag.rgb, 1.0);\r\n}","blackAndWhitePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tfloat luminance = dot(texture2D(textureSampler, vUV).rgb, vec3(0.3, 0.59, 0.11));\r\n\tgl_FragColor = vec4(luminance, luminance, luminance, 1.0);\r\n}","blurPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\nuniform vec2 direction;\r\nuniform float blurWidth;\r\n\r\nvoid main(void)\r\n{\r\n\tfloat weights[7];\r\n\tweights[0] = 0.05;\r\n\tweights[1] = 0.1;\r\n\tweights[2] = 0.2;\r\n\tweights[3] = 0.3;\r\n\tweights[4] = 0.2;\r\n\tweights[5] = 0.1;\r\n\tweights[6] = 0.05;\r\n\r\n\tvec2 texelSize = vec2(1.0 / screenSize.x, 1.0 / screenSize.y);\r\n\tvec2 texelStep = texelSize * direction * blurWidth;\r\n\tvec2 start = vUV - 3.0 * texelStep;\r\n\r\n\tvec4 baseColor = vec4(0., 0., 0., 0.);\r\n\tvec2 texelOffset = vec2(0., 0.);\r\n\r\n\tfor (int i = 0; i < 7; i++)\r\n\t{\r\n\t\tbaseColor += texture2D(textureSampler, start + texelOffset) * weights[i];\r\n\t\ttexelOffset += texelStep;\r\n\t}\r\n\r\n\tgl_FragColor = baseColor;\r\n}","brickPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfBricksHeight;\r\nuniform float numberOfBricksWidth;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tfloat brickW = 1.0 / numberOfBricksWidth;\r\n\tfloat brickH = 1.0 / numberOfBricksHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.05;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat brickColorSwitch = mod(floor(yi) + floor(xi), 3.0);\r\n\r\n\t\tif (brickColorSwitch == 0.0)\r\n\t\t\tcolor = mix(color, vec3(0.33, 0.33, 0.33), 0.3);\r\n\t\telse if (brickColorSwitch == 2.0)\r\n\t\t\tcolor = mix(color, vec3(0.11, 0.11, 0.11), 0.3);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","chromaticAberrationPixelShader":"// BABYLON.JS Chromatic Aberration GLSL Shader\r\n// Author: Olivier Guyot\r\n// Separates very slightly R, G and B colors on the edges of the screen\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\n#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float chromatic_aberration;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 centered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tfloat radius2 = centered_screen_pos.x*centered_screen_pos.x\r\n\t\t+ centered_screen_pos.y*centered_screen_pos.y;\r\n\tfloat radius = sqrt(radius2);\r\n\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\tif (chromatic_aberration > 0.0) {\r\n\t\t//index of refraction of each color channel, causing chromatic dispersion\r\n\t\tvec3 ref_indices = vec3(-0.3, 0.0, 0.3);\r\n\t\tfloat ref_shiftX = chromatic_aberration * radius * 17.0 / screen_width;\r\n\t\tfloat ref_shiftY = chromatic_aberration * radius * 17.0 / screen_height;\r\n\r\n\t\t// shifts for red, green & blue\r\n\t\tvec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\r\n\t\tvec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\r\n\r\n\t\toriginal.r = texture2D(textureSampler, ref_coords_r).r;\r\n\t\toriginal.g = texture2D(textureSampler, ref_coords_g).g;\r\n\t\toriginal.b = texture2D(textureSampler, ref_coords_b).b;\r\n\t}\r\n\r\n\tgl_FragColor = original;\r\n}","cloudPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vUV;\r\n\r\nuniform vec3 skyColor;\r\nuniform vec3 cloudColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\r\n\tvec2 p = vUV * 12.0;\r\n\tvec3 c = mix(skyColor, cloudColor, fbm(p));\r\n\tgl_FragColor = vec4(c, 1);\r\n\r\n}","colorPixelShader":"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n\tgl_FragColor = color;\n}","colorVertexShader":"precision highp float;\n\n// Attributes\nattribute vec3 position;\n\n// Uniforms\nuniform mat4 worldViewProjection;\n\nvoid main(void) {\n\tgl_Position = worldViewProjection * vec4(position, 1.0);\n}","colorCorrectionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// screen render\r\nuniform sampler2D colorTable;\t\t// color table with modified colors\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\nconst float SLICE_COUNT = 16.0;\t\t// how many slices in the color cube; 1 slice = 1 pixel\r\n// it means the image is 256x16 pixels\r\n\r\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\r\n\tfloat sliceSize = 1.0 / width; // space of 1 slice\r\n\tfloat slicePixelSize = sliceSize / width; // space of 1 pixel\r\n\tfloat sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\r\n\tfloat zSlice0 = min(floor(uv.z * width), width - 1.0);\r\n\tfloat zSlice1 = min(zSlice0 + 1.0, width - 1.0);\r\n\tfloat xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\r\n\tfloat s0 = xOffset + (zSlice0 * sliceSize);\r\n\tfloat s1 = xOffset + (zSlice1 * sliceSize);\r\n\tvec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\r\n\tvec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\r\n\tfloat zOffset = mod(uv.z * width, 1.0);\r\n\tvec4 result = mix(slice0Color, slice1Color, zOffset);\r\n\treturn result;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 screen_color = texture2D(textureSampler, vUV);\r\n\tgl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\r\n\r\n}","convolutionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform vec2 screenSize;\r\nuniform float kernel[9];\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 onePixel = vec2(1.0, 1.0) / screenSize;\r\n\tvec4 colorSum =\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, -1)) * kernel[0] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, -1)) * kernel[1] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, -1)) * kernel[2] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 0)) * kernel[3] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 0)) * kernel[4] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 0)) * kernel[5] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(-1, 1)) * kernel[6] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(0, 1)) * kernel[7] +\r\n\t\ttexture2D(textureSampler, vUV + onePixel * vec2(1, 1)) * kernel[8];\r\n\r\n\tfloat kernelWeight =\r\n\t\tkernel[0] +\r\n\t\tkernel[1] +\r\n\t\tkernel[2] +\r\n\t\tkernel[3] +\r\n\t\tkernel[4] +\r\n\t\tkernel[5] +\r\n\t\tkernel[6] +\r\n\t\tkernel[7] +\r\n\t\tkernel[8];\r\n\r\n\tif (kernelWeight <= 0.0) {\r\n\t\tkernelWeight = 1.0;\r\n\t}\r\n\r\n\tgl_FragColor = vec4((colorSum / kernelWeight).rgb, 1);\r\n}","defaultPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_EXPLICIT\t0.\r\n#define MAP_SPHERICAL\t1.\r\n#define MAP_PLANAR\t\t2.\r\n#define MAP_CUBIC\t\t3.\r\n#define MAP_PROJECTION\t4.\r\n#define MAP_SKYBOX\t\t5.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\nuniform vec4 vSpecularColor;\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\n\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\nuniform vec3 vLightSpecular0;\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\nuniform vec3 shadowsInfo0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\nuniform vec3 vLightSpecular1;\r\n#ifdef SHADOW1\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\nuniform vec3 shadowsInfo1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\nuniform vec3 vLightSpecular2;\r\n#ifdef SHADOW2\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\nuniform vec3 shadowsInfo2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\nuniform vec3 vLightSpecular3;\r\n#ifdef SHADOW3\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\nuniform vec3 shadowsInfo3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#ifdef SPECULAR\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Reflection\r\n#ifdef REFLECTION\r\nvarying vec3 vPositionUVW;\r\nuniform samplerCube reflectionCubeSampler;\r\nuniform sampler2D reflection2DSampler;\r\nuniform vec3 vReflectionInfos;\r\nuniform mat4 reflectionMatrix;\r\nuniform mat4 view;\r\n\r\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\r\n{\r\n\tif (mode == MAP_SPHERICAL)\r\n\t{\r\n\t\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n\t}\r\n\telse if (mode == MAP_PLANAR)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n\t}\r\n\telse if (mode == MAP_CUBIC)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = reflect(viewDir, worldNormal);\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n\t}\r\n\telse if (mode == MAP_PROJECTION)\r\n\t{\r\n\t\treturn vec3(reflectionMatrix * (view * worldPos));\r\n\t}\r\n\telse if (mode == MAP_SKYBOX)\r\n\t{\r\n\t\treturn vPositionUVW;\r\n\t}\r\n\r\n\treturn vec3(0, 0, 0);\r\n}\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\r\n\treturn dot(color, bit_shift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv)) + bias;\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn darkness;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat visibility = 1.;\r\n\r\n\tvec2 poissonDisk[4];\r\n\tpoissonDisk[0] = vec2(-0.94201624, -0.39906216);\r\n\tpoissonDisk[1] = vec2(0.94558609, -0.76890725);\r\n\tpoissonDisk[2] = vec2(-0.094184101, -0.92938870);\r\n\tpoissonDisk[3] = vec2(0.34495938, 0.29387760);\r\n\r\n\t// Poisson Sampling\r\n\tfloat biasedDepth = depth.z - bias;\r\n\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\tif (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) < biasedDepth) visibility -= 0.25;\r\n\r\n\treturn visibility;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat linstep(float low, float high, float v) {\r\n\treturn clamp((v - low) / (high - low), 0.0, 1.0);\r\n}\r\n\r\nfloat ChebychevInequality(vec2 moments, float compare, float bias)\r\n{\r\n\tfloat p = smoothstep(compare - bias, compare, moments.x);\r\n\tfloat variance = max(moments.y - moments.x * moments.x, 0.02);\r\n\tfloat d = compare - moments.x;\r\n\tfloat p_max = linstep(0.2, 1.0, variance / (variance + d * d));\r\n\r\n\treturn clamp(max(p, p_max), 0.0, 1.0);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tdepth = 0.5 * depth + vec3(0.5);\r\n\tvec2 uv = depth.xy;\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z >= 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn 1.0 - ChebychevInequality(moments, depth.z, bias);\r\n}\r\n#endif\r\n\r\n// Bump\r\n#ifdef BUMP\r\n#extension GL_OES_standard_derivatives : enable\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform sampler2D bumpSampler;\r\n\r\n// Thanks to http://www.thetenthplanet.de/archives/1180\r\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\r\n{\r\n\t// get edge vectors of the pixel triangle\r\n\tvec3 dp1 = dFdx(p);\r\n\tvec3 dp2 = dFdy(p);\r\n\tvec2 duv1 = dFdx(uv);\r\n\tvec2 duv2 = dFdy(uv);\r\n\r\n\t// solve the linear system\r\n\tvec3 dp2perp = cross(dp2, normal);\r\n\tvec3 dp1perp = cross(normal, dp1);\r\n\tvec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\r\n\tvec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\r\n\r\n\t// construct a scale-invariant frame \r\n\tfloat invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\r\n\treturn mat3(tangent * invmax, binormal * invmax, normal);\r\n}\r\n\r\nvec3 perturbNormal(vec3 viewDir)\r\n{\r\n\tvec3 map = texture2D(bumpSampler, vBumpUV).xyz;\r\n\tmap = map * 255. / 127. - 128. / 127.;\r\n\tmat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\r\n\treturn normalize(TBN * map);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nstruct lightingInfo\r\n{\r\n\tvec3 diffuse;\r\n\tvec3 specular;\r\n};\r\n\r\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 lightVectorW;\r\n\tfloat attenuation = 1.0;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tvec3 direction = lightData.xyz - vPositionW;\r\n\r\n\t\tattenuation = max(0., 1.0 - length(direction) / range);\r\n\t\tlightVectorW = normalize(direction);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, max(1., vSpecularColor.a));\r\n\r\n\tresult.diffuse = ndl * diffuseColor * attenuation;\r\n\tresult.specular = specComp * specularColor * attenuation;\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\r\n\tlightingInfo result;\r\n\r\n\tvec3 direction = lightData.xyz - vPositionW;\r\n\tvec3 lightVectorW = normalize(direction);\r\n\tfloat attenuation = max(0., 1.0 - length(direction) / range);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, vSpecularColor.a);\r\n\r\n\t\tresult.diffuse = ndl * spotAtten * diffuseColor * attenuation;\r\n\t\tresult.specular = specComp * specularColor * spotAtten * attenuation;\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult.diffuse = vec3(0.);\r\n\tresult.specular = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\r\n\tlightingInfo result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, vSpecularColor.a);\r\n\r\n\tresult.diffuse = mix(groundColor, diffuseColor, ndl);\r\n\tresult.specular = specComp * specularColor;\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef ALPHAFROMDIFFUSE\r\n\talpha *= baseColor.a;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n\t// Bump\r\n#ifdef NORMAL\r\n\tvec3 normalW = normalize(vNormalW);\r\n#else\r\n\tvec3 normalW = vec3(1.0, 1.0, 1.0);\r\n#endif\r\n\r\n\r\n#ifdef BUMP\r\n\tnormalW = perturbNormal(viewDirectionW);\r\n#endif\r\n\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifdef SPOTLIGHT0\r\n\tlightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tlightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tlightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z);\r\n#else\r\n\t#ifdef SHADOWPCF0\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\r\n\t#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z);\r\n#else\r\n\t#ifdef SHADOWPCF1\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\r\n\t#endif\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z);\r\n#else\r\n\t#ifdef SHADOWPCF2\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\r\n\t#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z);\r\n#else\r\n\t#ifdef SHADOWPCF3\r\n\t\tshadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z);\r\n\t#else\r\n\t\tshadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\r\n\t#endif\t\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info.diffuse * shadow;\r\n\tspecularBase += info.specular * shadow;\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tvec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\r\n\r\n\tif (vReflectionInfos.z != 0.0)\r\n\t{\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n\t\tif (vReflectionInfos.x == MAP_PROJECTION)\r\n\t\t{\r\n\t\t\tcoords /= vReflectionUVW.z;\r\n\t\t}\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\r\n\t}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n\r\n#ifdef SPECULAROVERALPHA\r\n\talpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\r\n#endif\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","defaultVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n#ifdef NORMAL\r\nattribute vec3 normal;\r\n#endif\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#ifdef SPECULAR\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef POINTSIZE\r\nuniform float pointSize;\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\n#ifdef NORMAL\r\nvarying vec3 vNormalW;\r\n#endif\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vPositionUVW;\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef REFLECTION\r\n\tvPositionUVW = position;\r\n#endif \r\n\r\n#ifdef INSTANCES\r\n\tfinalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2);\r\n#endif \r\n\r\n#endif\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\r\n#ifdef NORMAL\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n#endif\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef SPECULAR\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n\r\n\t// Point size\r\n#ifdef POINTSIZE\r\n\tgl_PointSize = pointSize;\r\n#endif\r\n}","depthPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nuniform float far;\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tfloat depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\r\n\tgl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\r\n}","depthVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","depthBoxBlurPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Parameters\r\nuniform vec2 screenSize;\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 colorDepth = vec4(0.0);\r\n\r\n\tfor (int x = -OFFSET; x <= OFFSET; x++)\r\n\t\tfor (int y = -OFFSET; y <= OFFSET; y++)\r\n\t\t\tcolorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\r\n\r\n\tgl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\r\n}","depthOfFieldPixelShader":"// BABYLON.JS Depth-of-field GLSL Shader\r\n// Author: Olivier Guyot\r\n// Does depth-of-field blur, edge blur\r\n// Inspired by Francois Tarlier & Martins Upitis\r\n\r\n#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D highlightsSampler;\r\nuniform sampler2D depthSampler;\r\nuniform sampler2D grainSampler;\r\n\r\n// uniforms\r\nuniform float grain_amount;\r\nuniform float maxZ;\r\nuniform bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform float focus_depth;\r\nuniform float aperture;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI 3.14159265\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nfloat radius2;\r\nfloat radius;\r\n\r\n\r\n// applies edge distortion on texture coords\r\nvec2 getDistortedCoords(vec2 coords) {\r\n\r\n\tif (distortion == 0.0) { return coords; }\r\n\r\n\tvec2 direction = 1.0 * normalize(centered_screen_pos);\r\n\tvec2 dist_coords = vec2(0.5, 0.5);\r\n\tdist_coords.x = 0.5 + direction.x * radius2 * 1.0;\r\n\tdist_coords.y = 0.5 + direction.y * radius2 * 1.0;\r\n\tfloat dist_amount = clamp(distortion*0.23, 0.0, 1.0);\r\n\r\n\tdist_coords = mix(coords, dist_coords, dist_amount);\r\n\r\n\treturn dist_coords;\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(vec2 coords, float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, coords);\r\n\tif (size == 0.0) { return col; }\r\n\r\n\t// there are max. 30 samples; the number of samples chosen is dependant on the blur size\r\n\t// there can be 10, 20 or 30 samples chosen; levels of blur are then 1, 2 or 3\r\n\tfloat blur_level = min(3.0, ceil(size / 1.0));\r\n\r\n\tfloat w = (size / screen_width);\r\n\tfloat h = (size / screen_height);\r\n\tfloat total_weight = 1.0;\r\n\r\n\tcol += texture2D(textureSampler, coords + vec2(-0.53*w, 0.15*h))*0.93;\r\n\tcol += texture2D(textureSampler, coords + vec2(0.42*w, -0.69*h))*0.90;\r\n\tcol += texture2D(textureSampler, coords + vec2(0.20*w, 1.00*h))*0.87;\r\n\tcol += texture2D(textureSampler, coords + vec2(-0.97*w, -0.72*h))*0.85;\r\n\tcol += texture2D(textureSampler, coords + vec2(1.37*w, -0.14*h))*0.83;\r\n\tcol += texture2D(textureSampler, coords + vec2(-1.02*w, 1.16*h))*0.80;\r\n\tcol += texture2D(textureSampler, coords + vec2(-0.03*w, -1.69*h))*0.78;\r\n\tcol += texture2D(textureSampler, coords + vec2(1.27*w, 1.34*h))*0.76;\r\n\tcol += texture2D(textureSampler, coords + vec2(-1.98*w, -0.14*h))*0.74;\r\n\tcol += texture2D(textureSampler, coords + vec2(1.66*w, -1.32*h))*0.72;\r\n\ttotal_weight += 8.18;\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-0.35*w, 2.22*h))*0.70;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-1.31*w, -1.98*h))*0.67;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(2.42*w, 0.61*h))*0.65;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-2.31*w, 1.25*h))*0.63;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(0.90*w, -2.59*h))*0.61;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(1.14*w, 2.62*h))*0.59;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-2.72*w, -1.21*h))*0.56;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(2.93*w, -0.98*h))*0.54;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-1.56*w, 2.80*h))*0.52;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-0.77*w, -3.22*h))*0.49;\r\n\t\ttotal_weight += 5.96;\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\tcol += texture2D(textureSampler, coords + vec2(2.83*w, 1.92*h))*0.46;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-3.49*w, 0.51*h))*0.44;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(2.30*w, -2.82*h))*0.41;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(0.22*w, 3.74*h))*0.38;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-2.76*w, -2.68*h))*0.34;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(3.95*w, 0.11*h))*0.31;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(-3.07*w, 2.65*h))*0.26;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(0.48*w, -4.13*h))*0.22;\r\n\t\tcol += texture2D(textureSampler, coords + vec2(2.49*w, 3.46*h))*0.15;\r\n\t\ttotal_weight += 2.97;\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\tcol.a = 1.0;\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b = 0.0; }\r\n\t// if(blur_level == 2.0) { col.r = 0.0; }\r\n\t// if(blur_level == 3.0) { col.g = 0.0; }\r\n\r\n\treturn col;\r\n}\r\n\r\n// on-the-fly constant noise\r\nvec2 rand(vec2 co)\r\n{\r\n\tfloat noise1 = (fract(sin(dot(co, vec2(12.9898, 78.233))) * 43758.5453));\r\n\tfloat noise2 = (fract(sin(dot(co, vec2(12.9898, 78.233)*2.0)) * 43758.5453));\r\n\treturn clamp(vec2(noise1, noise2), 0.0, 1.0);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc\r\n\tcentered_screen_pos = vec2(vUV.x - 0.5, vUV.y - 0.5);\r\n\tradius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\r\n\tradius = sqrt(radius2);\r\n\r\n\tvec4 final_color;\r\n\tvec2 distorted_coords = getDistortedCoords(vUV);\r\n\tvec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height);\t// varies from 0 to SCREEN_WIDTH or _HEIGHT\r\n\r\n\t// blur from depth of field effect\r\n\tfloat dof_blur_amount = 0.0;\r\n\tfloat depth_bias = 0.0;\t\t// positive if the pixel is further than focus depth; negative if closer\r\n\tif (focus_depth != -1.0) {\r\n\t\tvec4 depth_sample = texture2D(depthSampler, distorted_coords);\r\n\t\tfloat depth = depth_sample.r;\r\n\t\tdepth_bias = depth - focus_depth;\r\n\r\n\t\t// compute blur amount with distance\r\n\t\tif (depth_bias > 0.0) { dof_blur_amount = depth_bias * aperture * 2.2; }\r\n\t\telse { dof_blur_amount = depth_bias * depth_bias * aperture * 30.0; }\r\n\r\n\t\tif (dof_blur_amount < 0.05) { dof_blur_amount = 0.0; }\t// no blur at all\r\n\t}\r\n\r\n\t// blur from edge blur effect\r\n\tfloat edge_blur_amount = 0.0;\r\n\tif (edge_blur > 0.0) {\r\n\t\tedge_blur_amount = clamp((radius*2.0 - 1.0 + 0.15*edge_blur) * 1.5, 0.0, 1.0) * 1.3;\r\n\t}\r\n\r\n\t// total blur amount\r\n\tfloat blur_amount = max(edge_blur_amount, dof_blur_amount);\r\n\r\n\t// apply blur if necessary\r\n\tif (blur_amount == 0.0) {\r\n\t\tgl_FragColor = texture2D(textureSampler, distorted_coords);\r\n\t}\r\n\telse {\r\n\r\n\t\t// add blurred color\r\n\t\tgl_FragColor = getBlurColor(distorted_coords, blur_amount * 1.7);\r\n\r\n\t\t// if further than focus depth & we have computed highlights: enhance highlights\r\n\t\tif (depth_bias > 0.0 && highlights) {\r\n\t\t\tgl_FragColor += clamp(dof_blur_amount, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords);\r\n\t\t}\r\n\r\n\t\tif (blur_noise) {\r\n\t\t\t// we put a slight amount of noise in the blurred color\r\n\t\t\tvec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\r\n\t\t\tvec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\r\n\t\t\tgl_FragColor = 0.04 * texture2D(textureSampler, blurred_coord) + 0.96 * gl_FragColor;\r\n\t\t}\r\n\t}\r\n\r\n\t// apply grain\r\n\tif (grain_amount > 0.0) {\r\n\t\tvec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\r\n\t\tgl_FragColor.rgb += (-0.5 + grain_color.rgb) * 0.20;\r\n\t}\r\n}","displayPassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D passSampler;\r\n\r\nvoid main(void)\r\n{\r\n gl_FragColor = texture2D(passSampler, vUV);\r\n}","filterPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nuniform mat4 kernelMatrix;\r\n\r\nvoid main(void)\r\n{\r\n\tvec3 baseColor = texture2D(textureSampler, vUV).rgb;\r\n\tvec3 updatedColor = (kernelMatrix * vec4(baseColor, 1.0)).rgb;\r\n\r\n\tgl_FragColor = vec4(updatedColor, 1.0);\r\n}","firePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform float time;\r\nuniform vec3 c1;\r\nuniform vec3 c2;\r\nuniform vec3 c3;\r\nuniform vec3 c4;\r\nuniform vec3 c5;\r\nuniform vec3 c6;\r\nuniform vec2 speed;\r\nuniform float shift;\r\nuniform float alphaThreshold;\r\n\r\nvarying vec2 vUV;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main() {\r\n\tvec2 p = vUV * 8.0;\r\n\tfloat q = fbm(p - time * 0.1);\r\n\tvec2 r = vec2(fbm(p + q + time * speed.x - p.x - p.y), fbm(p + q - time * speed.y));\r\n\tvec3 c = mix(c1, c2, fbm(p + r)) + mix(c3, c4, r.x) - mix(c5, c6, r.y);\r\n\tvec3 color = c * cos(shift * vUV.y);\r\n\tfloat luminance = dot(color.rgb, vec3(0.3, 0.59, 0.11));\r\n\r\n\tgl_FragColor = vec4(color, luminance * alphaThreshold + (1.0 - alphaThreshold));\r\n}","fxaaPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define FXAA_REDUCE_MIN (1.0/128.0)\r\n#define FXAA_REDUCE_MUL (1.0/8.0)\r\n#define FXAA_SPAN_MAX 8.0\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 texelSize;\r\n\r\nvoid main(){\r\n\tvec2 localTexelSize = texelSize;\r\n\tvec4 rgbNW = texture2D(textureSampler, (vUV + vec2(-1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbNE = texture2D(textureSampler, (vUV + vec2(1.0, -1.0) * localTexelSize));\r\n\tvec4 rgbSW = texture2D(textureSampler, (vUV + vec2(-1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbSE = texture2D(textureSampler, (vUV + vec2(1.0, 1.0) * localTexelSize));\r\n\tvec4 rgbM = texture2D(textureSampler, vUV);\r\n\tvec4 luma = vec4(0.299, 0.587, 0.114, 1.0);\r\n\tfloat lumaNW = dot(rgbNW, luma);\r\n\tfloat lumaNE = dot(rgbNE, luma);\r\n\tfloat lumaSW = dot(rgbSW, luma);\r\n\tfloat lumaSE = dot(rgbSE, luma);\r\n\tfloat lumaM = dot(rgbM, luma);\r\n\tfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\r\n\tfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\r\n\r\n\tvec2 dir = vec2(-((lumaNW + lumaNE) - (lumaSW + lumaSE)), ((lumaNW + lumaSW) - (lumaNE + lumaSE)));\r\n\r\n\tfloat dirReduce = max(\r\n\t\t(lumaNW + lumaNE + lumaSW + lumaSE) * (0.25 * FXAA_REDUCE_MUL),\r\n\t\tFXAA_REDUCE_MIN);\r\n\r\n\tfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\r\n\tdir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\r\n\t\tmax(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\r\n\t\tdir * rcpDirMin)) * localTexelSize;\r\n\r\n\tvec4 rgbA = 0.5 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * (1.0 / 3.0 - 0.5)) +\r\n\t\ttexture2D(textureSampler, vUV + dir * (2.0 / 3.0 - 0.5)));\r\n\r\n\tvec4 rgbB = rgbA * 0.5 + 0.25 * (\r\n\t\ttexture2D(textureSampler, vUV + dir * -0.5) +\r\n\t\ttexture2D(textureSampler, vUV + dir * 0.5));\r\n\tfloat lumaB = dot(rgbB, luma);\r\n\tif ((lumaB < lumaMin) || (lumaB > lumaMax)) {\r\n\t\tgl_FragColor = rgbA;\r\n\t}\r\n\telse {\r\n\t\tgl_FragColor = rgbB;\r\n\t}\r\n}","grassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform vec3 herb1Color;\r\nuniform vec3 herb2Color;\r\nuniform vec3 herb3Color;\r\nuniform vec3 groundColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tvec3 color = mix(groundColor, herb1Color, rand(gl_FragCoord.xy * 4.0));\r\n\tcolor = mix(color, herb2Color, rand(gl_FragCoord.xy * 8.0));\r\n\tcolor = mix(color, herb3Color, rand(gl_FragCoord.xy));\r\n\tcolor = mix(color, herb1Color, fbm(gl_FragCoord.xy * 16.0));\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","layerPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","layerVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 textureMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = vec2(textureMatrix * vec4(position * madd + madd, 1.0, 0.0));\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","legacydefaultPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_PROJECTION\t4.\r\n\r\n// Constants\r\nuniform vec3 vEyePosition;\r\nuniform vec3 vAmbientColor;\r\nuniform vec4 vDiffuseColor;\r\nuniform vec4 vSpecularColor;\r\nuniform vec3 vEmissiveColor;\r\n\r\n// Input\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n// Lights\r\n#ifdef LIGHT0\r\nuniform vec4 vLightData0;\r\nuniform vec4 vLightDiffuse0;\r\nuniform vec3 vLightSpecular0;\r\n#ifdef SHADOW0\r\nvarying vec4 vPositionFromLight0;\r\nuniform sampler2D shadowSampler0;\r\n#endif\r\n#ifdef SPOTLIGHT0\r\nuniform vec4 vLightDirection0;\r\n#endif\r\n#ifdef HEMILIGHT0\r\nuniform vec3 vLightGround0;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT1\r\nuniform vec4 vLightData1;\r\nuniform vec4 vLightDiffuse1;\r\nuniform vec3 vLightSpecular1;\r\n#ifdef SHADOW1\r\nvarying vec4 vPositionFromLight1;\r\nuniform sampler2D shadowSampler1;\r\n#endif\r\n#ifdef SPOTLIGHT1\r\nuniform vec4 vLightDirection1;\r\n#endif\r\n#ifdef HEMILIGHT1\r\nuniform vec3 vLightGround1;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT2\r\nuniform vec4 vLightData2;\r\nuniform vec4 vLightDiffuse2;\r\nuniform vec3 vLightSpecular2;\r\n#ifdef SHADOW2\r\nvarying vec4 vPositionFromLight2;\r\nuniform sampler2D shadowSampler2;\r\n#endif\r\n#ifdef SPOTLIGHT2\r\nuniform vec4 vLightDirection2;\r\n#endif\r\n#ifdef HEMILIGHT2\r\nuniform vec3 vLightGround2;\r\n#endif\r\n#endif\r\n\r\n#ifdef LIGHT3\r\nuniform vec4 vLightData3;\r\nuniform vec4 vLightDiffuse3;\r\nuniform vec3 vLightSpecular3;\r\n#ifdef SHADOW3\r\nvarying vec4 vPositionFromLight3;\r\nuniform sampler2D shadowSampler3;\r\n#endif\r\n#ifdef SPOTLIGHT3\r\nuniform vec4 vLightDirection3;\r\n#endif\r\n#ifdef HEMILIGHT3\r\nuniform vec3 vLightGround3;\r\n#endif\r\n#endif\r\n\r\n// Samplers\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform sampler2D diffuseSampler;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform sampler2D ambientSampler;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\t\r\nvarying vec2 vOpacityUV;\r\nuniform sampler2D opacitySampler;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvarying vec3 vReflectionUVW;\r\nuniform samplerCube reflectionCubeSampler;\r\nuniform sampler2D reflection2DSampler;\r\nuniform vec3 vReflectionInfos;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform sampler2D emissiveSampler;\r\n#endif\r\n\r\n#ifdef SPECULAR\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform sampler2D specularSampler;\r\n#endif\r\n\r\n// Fresnel\r\n#ifdef FRESNEL\r\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\r\n{\r\n\tfloat fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\r\n\treturn clamp(fresnelTerm, 0., 1.);\r\n}\r\n#endif\r\n\r\n#ifdef DIFFUSEFRESNEL\r\nuniform vec4 diffuseLeftColor;\r\nuniform vec4 diffuseRightColor;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\nuniform vec4 opacityParts;\r\n#endif\r\n\r\n#ifdef REFLECTIONFRESNEL\r\nuniform vec4 reflectionLeftColor;\r\nuniform vec4 reflectionRightColor;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\nuniform vec4 emissiveLeftColor;\r\nuniform vec4 emissiveRightColor;\r\n#endif\r\n\r\n// Shadows\r\n#ifdef SHADOWS\r\n\r\nfloat unpack(vec4 color)\r\n{\r\n\tconst vec4 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\r\n\treturn dot(color, bitShift);\r\n}\r\n\r\nfloat unpackHalf(vec2 color)\r\n{\r\n\treturn color.x + (color.y / 255.0);\r\n}\r\n\r\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat shadow = unpack(texture2D(shadowSampler, uv));\r\n\r\n\tif (depth.z > shadow)\r\n\t{\r\n\t\treturn 0.;\r\n\t}\r\n\treturn 1.;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nfloat ChebychevInequality(vec2 moments, float t)\r\n{\r\n\tif (t <= moments.x)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tfloat variance = moments.y - (moments.x * moments.x);\r\n\tvariance = max(variance, 0.);\r\n\r\n\tfloat d = t - moments.x;\r\n\treturn variance / (variance + d * d);\r\n}\r\n\r\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler)\r\n{\r\n\tvec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\r\n\tvec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\r\n\r\n\tif (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\r\n\t{\r\n\t\treturn 1.0;\r\n\t}\r\n\r\n\tvec4 texel = texture2D(shadowSampler, uv);\r\n\r\n\tvec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\r\n\treturn clamp(1.3 - ChebychevInequality(moments, depth.z), 0., 1.0);\r\n}\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn clamp(fogCoeff, 0.0, 1.0);\r\n}\r\n#endif\r\n\r\n// Light Computing\r\nmat3 computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW;\r\n\tif (lightData.w == 0.)\r\n\t{\r\n\t\tlightVectorW = normalize(lightData.xyz - vPositionW);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tlightVectorW = normalize(-lightData.xyz);\r\n\t}\r\n\r\n\t// diffuse\r\n\tfloat ndl = max(0., dot(vNormal, lightVectorW));\r\n\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightVectorW);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = max(0., pow(specComp, max(1.0, vSpecularColor.a)));\r\n\r\n\tresult[0] = ndl * diffuseColor.rgb;\r\n\tresult[1] = specComp * specularColor;\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec4 diffuseColor, vec3 specularColor) {\r\n\tmat3 result;\r\n\r\n\tvec3 lightVectorW = normalize(lightData.xyz - vPositionW);\r\n\r\n\t// diffuse\r\n\tfloat cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\r\n\tfloat spotAtten = 0.0;\r\n\r\n\tif (cosAngle >= lightDirection.w)\r\n\t{\r\n\t\tcosAngle = max(0., pow(cosAngle, lightData.w));\r\n\t\tspotAtten = max(0., (cosAngle - lightDirection.w) / (1. - cosAngle));\r\n\r\n\t\t// Diffuse\r\n\t\tfloat ndl = max(0., dot(vNormal, -lightDirection.xyz));\r\n\r\n\t\t// Specular\r\n\t\tvec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\r\n\t\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\t\tspecComp = pow(specComp, vSpecularColor.a);\r\n\r\n\t\tresult[0] = ndl * spotAtten * diffuseColor.rgb;\r\n\t\tresult[1] = specComp * specularColor * spotAtten;\r\n\t\tresult[2] = vec3(0.);\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tresult[0] = vec3(0.);\r\n\tresult[1] = vec3(0.);\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nmat3 computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 diffuseColor, vec3 specularColor, vec3 groundColor) {\r\n\tmat3 result;\r\n\r\n\t// Diffuse\r\n\tfloat ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\r\n\r\n\t// Specular\r\n\tvec3 angleW = normalize(viewDirectionW + lightData.xyz);\r\n\tfloat specComp = max(0., dot(vNormal, angleW));\r\n\tspecComp = pow(specComp, vSpecularColor.a);\r\n\r\n\tresult[0] = mix(groundColor, diffuseColor.rgb, ndl);\r\n\tresult[1] = specComp * specularColor;\r\n\tresult[2] = vec3(0.);\r\n\r\n\treturn result;\r\n}\r\n\r\nvoid main(void) {\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tvec3 viewDirectionW = normalize(vEyePosition - vPositionW);\r\n\r\n\t// Base color\r\n\tvec4 baseColor = vec4(1., 1., 1., 1.);\r\n\tvec3 diffuseColor = vDiffuseColor.rgb;\r\n\r\n#ifdef VERTEXCOLOR\r\n\tbaseColor.rgb *= vColor.rgb;\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tbaseColor = texture2D(diffuseSampler, vDiffuseUV);\r\n\r\n#ifdef ALPHATEST\r\n\tif (baseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tbaseColor.rgb *= vDiffuseInfos.y;\r\n#endif\r\n\r\n\t// Bump\r\n\tvec3 normalW = normalize(vNormalW);\r\n\r\n\t// Ambient color\r\n\tvec3 baseAmbientColor = vec3(1., 1., 1.);\r\n\r\n#ifdef AMBIENT\r\n\tbaseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\r\n#endif\r\n\r\n\t// Lighting\r\n\tvec3 diffuseBase = vec3(0., 0., 0.);\r\n\tvec3 specularBase = vec3(0., 0., 0.);\r\n\tfloat shadow = 1.;\r\n\r\n#ifdef LIGHT0\r\n#ifdef SPOTLIGHT0\r\n\tmat3 info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef HEMILIGHT0\r\n\tmat3 info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0, vLightGround0);\r\n#endif\r\n#ifdef POINTDIRLIGHT0\r\n\tmat3 info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0, vLightSpecular0);\r\n#endif\r\n#ifdef SHADOW0\r\n#ifdef SHADOWVSM0\r\n\tshadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight0, shadowSampler0);\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT1\r\n#ifdef SPOTLIGHT1\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef HEMILIGHT1\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1, vLightGround1);\r\n#endif\r\n#ifdef POINTDIRLIGHT1\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1, vLightSpecular1);\r\n#endif\r\n#ifdef SHADOW1\r\n#ifdef SHADOWVSM1\r\n\tshadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight1, shadowSampler1);\r\n#endif\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT2\r\n#ifdef SPOTLIGHT2\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef HEMILIGHT2\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2, vLightGround2);\r\n#endif\r\n#ifdef POINTDIRLIGHT2\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2, vLightSpecular2);\r\n#endif\r\n#ifdef SHADOW2\r\n#ifdef SHADOWVSM2\r\n\tshadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight2, shadowSampler2);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n\r\n#ifdef LIGHT3\r\n#ifdef SPOTLIGHT3\r\n\tinfo = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef HEMILIGHT3\r\n\tinfo = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3, vLightGround3);\r\n#endif\r\n#ifdef POINTDIRLIGHT3\r\n\tinfo = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3, vLightSpecular3);\r\n#endif\r\n#ifdef SHADOW3\r\n#ifdef SHADOWVSM3\r\n\tshadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3);\r\n#else\r\n\tshadow = computeShadow(vPositionFromLight3, shadowSampler3);\r\n#endif\t\r\n#else\r\n\tshadow = 1.;\r\n#endif\r\n\tdiffuseBase += info[0] * shadow;\r\n\tspecularBase += info[1] * shadow;\r\n#endif\r\n\r\n\t// Reflection\r\n\tvec3 reflectionColor = vec3(0., 0., 0.);\r\n\r\n#ifdef REFLECTION\r\n\tif (vReflectionInfos.z != 0.0)\r\n\t{\r\n\t\treflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvec2 coords = vReflectionUVW.xy;\r\n\r\n\t\tif (vReflectionInfos.x == MAP_PROJECTION)\r\n\t\t{\r\n\t\t\tcoords /= vReflectionUVW.z;\r\n\t\t}\r\n\r\n\t\tcoords.y = 1.0 - coords.y;\r\n\r\n\t\treflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y;\r\n\t}\r\n\r\n#ifdef REFLECTIONFRESNEL\r\n\tfloat reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\r\n\r\n\treflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\r\n#endif\r\n#endif\r\n\r\n\t// Alpha\r\n\tfloat alpha = vDiffuseColor.a;\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\r\n#ifdef OPACITYRGB\r\n\topacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\r\n#else\r\n\talpha *= opacityMap.a * vOpacityInfos.y;\r\n#endif\r\n#endif\r\n\r\n#ifdef VERTEXALPHA\r\n\talpha *= vColor.a;\r\n#endif\r\n\r\n#ifdef OPACITYFRESNEL\r\n\tfloat opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\r\n\r\n\talpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\r\n#endif\r\n\r\n\t// Emissive\r\n\tvec3 emissiveColor = vEmissiveColor;\r\n#ifdef EMISSIVE\r\n\temissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\r\n#endif\r\n\r\n#ifdef EMISSIVEFRESNEL\r\n\tfloat emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\r\n\r\n\temissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\r\n#endif\r\n\r\n\t// Specular map\r\n\tvec3 specularColor = vSpecularColor.rgb;\r\n#ifdef SPECULAR\r\n\tspecularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\r\n#endif\r\n\r\n\t// Fresnel\r\n#ifdef DIFFUSEFRESNEL\r\n\tfloat diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\r\n\r\n\tdiffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\r\n#endif\r\n\r\n\t// Composition\r\n\tvec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\r\n\tvec3 finalSpecular = specularBase * specularColor;\r\n\r\n\tvec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tcolor.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","legacydefaultVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define MAP_EXPLICIT\t0.\r\n#define MAP_SPHERICAL\t1.\r\n#define MAP_PLANAR\t\t2.\r\n#define MAP_CUBIC\t\t3.\r\n#define MAP_PROJECTION\t4.\r\n#define MAP_SKYBOX\t\t5.\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#ifdef VERTEXCOLOR\r\nattribute vec4 color;\r\n#endif\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniforms\r\nuniform mat4 world;\r\nuniform mat4 view;\r\nuniform mat4 viewProjection;\r\n\r\n#ifdef DIFFUSE\r\nvarying vec2 vDiffuseUV;\r\nuniform mat4 diffuseMatrix;\r\nuniform vec2 vDiffuseInfos;\r\n#endif\r\n\r\n#ifdef AMBIENT\r\nvarying vec2 vAmbientUV;\r\nuniform mat4 ambientMatrix;\r\nuniform vec2 vAmbientInfos;\r\n#endif\r\n\r\n#ifdef OPACITY\r\nvarying vec2 vOpacityUV;\r\nuniform mat4 opacityMatrix;\r\nuniform vec2 vOpacityInfos;\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nuniform vec3 vEyePosition;\r\nvarying vec3 vReflectionUVW;\r\nuniform vec3 vReflectionInfos;\r\nuniform mat4 reflectionMatrix;\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\nvarying vec2 vEmissiveUV;\r\nuniform vec2 vEmissiveInfos;\r\nuniform mat4 emissiveMatrix;\r\n#endif\r\n\r\n#ifdef SPECULAR\r\nvarying vec2 vSpecularUV;\r\nuniform vec2 vSpecularInfos;\r\nuniform mat4 specularMatrix;\r\n#endif\r\n\r\n#ifdef BUMP\r\nvarying vec2 vBumpUV;\r\nuniform vec2 vBumpInfos;\r\nuniform mat4 bumpMatrix;\r\n#endif\r\n\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n// Output\r\nvarying vec3 vPositionW;\r\nvarying vec3 vNormalW;\r\n\r\n#ifdef VERTEXCOLOR\r\nvarying vec4 vColor;\r\n#endif\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\nuniform mat4 lightMatrix0;\r\nvarying vec4 vPositionFromLight0;\r\n#endif\r\n#ifdef LIGHT1\r\nuniform mat4 lightMatrix1;\r\nvarying vec4 vPositionFromLight1;\r\n#endif\r\n#ifdef LIGHT2\r\nuniform mat4 lightMatrix2;\r\nvarying vec4 vPositionFromLight2;\r\n#endif\r\n#ifdef LIGHT3\r\nuniform mat4 lightMatrix3;\r\nvarying vec4 vPositionFromLight3;\r\n#endif\r\n#endif\r\n\r\n#ifdef REFLECTION\r\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\r\n{\r\n\tif (mode == MAP_SPHERICAL)\r\n\t{\r\n\t\tvec3 coords = vec3(view * vec4(worldNormal, 0.0));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1.0));\r\n\t}\r\n\telse if (mode == MAP_PLANAR)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = normalize(reflect(viewDir, worldNormal));\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 1));\r\n\t}\r\n\telse if (mode == MAP_CUBIC)\r\n\t{\r\n\t\tvec3 viewDir = worldPos.xyz - vEyePosition;\r\n\t\tvec3 coords = reflect(viewDir, worldNormal);\r\n\r\n\t\treturn vec3(reflectionMatrix * vec4(coords, 0));\r\n\t}\r\n\telse if (mode == MAP_PROJECTION)\r\n\t{\r\n\t\treturn vec3(reflectionMatrix * (view * worldPos));\r\n\t}\r\n\telse if (mode == MAP_SKYBOX)\r\n\t{\r\n\t\treturn position;\r\n\t}\r\n\r\n\treturn vec3(0, 0, 0);\r\n}\r\n#endif\r\n\r\nvoid main(void) {\r\n\tmat4 finalWorld;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\r\n#ifdef BONES4\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = world * (m0 + m1 + m2 + m3);\r\n#else\r\n\tfinalWorld = world * (m0 + m1 + m2);\r\n#endif \r\n\r\n#else\r\n\tfinalWorld = world;\r\n#endif\r\n\r\n\tgl_Position = viewProjection * finalWorld * vec4(position, 1.0);\r\n\r\n\tvec4 worldPos = finalWorld * vec4(position, 1.0);\r\n\tvPositionW = vec3(worldPos);\r\n\tvNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\r\n\r\n\t// Texture coordinates\r\n#ifndef UV1\r\n\tvec2 uv = vec2(0., 0.);\r\n#endif\r\n#ifndef UV2\r\n\tvec2 uv2 = vec2(0., 0.);\r\n#endif\r\n\r\n#ifdef DIFFUSE\r\n\tif (vDiffuseInfos.x == 0.)\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvDiffuseUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef AMBIENT\r\n\tif (vAmbientInfos.x == 0.)\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvAmbientUV = vec2(ambientMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tif (vOpacityInfos.x == 0.)\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvOpacityUV = vec2(opacityMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef REFLECTION\r\n\tvReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), vNormalW);\r\n#endif\r\n\r\n#ifdef EMISSIVE\r\n\tif (vEmissiveInfos.x == 0.)\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvEmissiveUV = vec2(emissiveMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef SPECULAR\r\n\tif (vSpecularInfos.x == 0.)\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvSpecularUV = vec2(specularMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n#ifdef BUMP\r\n\tif (vBumpInfos.x == 0.)\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv, 1.0, 0.0));\r\n\t}\r\n\telse\r\n\t{\r\n\t\tvBumpUV = vec2(bumpMatrix * vec4(uv2, 1.0, 0.0));\r\n\t}\r\n#endif\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = (view * worldPos).z;\r\n#endif\r\n\r\n\t// Shadows\r\n#ifdef SHADOWS\r\n#ifdef LIGHT0\r\n\tvPositionFromLight0 = lightMatrix0 * worldPos;\r\n#endif\r\n#ifdef LIGHT1\r\n\tvPositionFromLight1 = lightMatrix1 * worldPos;\r\n#endif\r\n#ifdef LIGHT2\r\n\tvPositionFromLight2 = lightMatrix2 * worldPos;\r\n#endif\r\n#ifdef LIGHT3\r\n\tvPositionFromLight3 = lightMatrix3 * worldPos;\r\n#endif\r\n#endif\r\n\r\n\t// Vertex color\r\n#ifdef VERTEXCOLOR\r\n\tvColor = color;\r\n#endif\r\n}","lensFlarePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\n// Color\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(textureSampler, vUV);\r\n\r\n\tgl_FragColor = baseColor * color;\r\n}","lensFlareVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Uniforms\r\nuniform mat4 viewportMatrix;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = viewportMatrix * vec4(position, 0.0, 1.0);\r\n}","lensHighlightsPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// samplers\r\nuniform sampler2D textureSampler;\t// original color\r\n\r\n// uniforms\r\nuniform float gain;\r\nuniform float threshold;\r\nuniform bool pentagon;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// apply luminance filter\r\nvec4 highlightColor(vec4 color) {\r\n\tvec4 highlight = color;\r\n\tfloat luminance = dot(highlight.rgb, vec3(0.2125, 0.7154, 0.0721));\r\n\tfloat lum_threshold;\r\n\tif (threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\r\n\telse { lum_threshold = 0.5 + 0.44 * threshold; }\r\n\r\n\tluminance = clamp((luminance - lum_threshold) * (1.0 / (1.0 - lum_threshold)), 0.0, 1.0);\r\n\r\n\thighlight *= luminance * gain;\r\n\thighlight.a = 1.0;\r\n\r\n\treturn highlight;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec4 original = texture2D(textureSampler, vUV);\r\n\r\n\t// quick exit if no highlight computing\r\n\tif (gain == -1.0) {\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t\treturn;\r\n\t}\r\n\r\n\tfloat w = 2.0 / screen_width;\r\n\tfloat h = 2.0 / screen_height;\r\n\r\n\tfloat weight = 1.0;\r\n\r\n\t// compute blurred color\r\n\tvec4 blurred = vec4(0.0, 0.0, 0.0, 0.0);\r\n\r\n\tif (pentagon) {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.84*w, 0.43*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.48*w, -1.29*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.61*w, 1.51*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.55*w, -0.74*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.71*w, -0.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.94*w, 1.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.40*w, -1.87*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.62*w, 1.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.09*w, 0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.46*w, -1.71*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.08*w, 2.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.85*w, -1.89*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.89*w, 0.16*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.29*w, 1.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.40*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.54*w, 2.26*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.60*w, -0.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.31*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.83*w, 2.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.12*w, -2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.60*w, 1.11*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.99*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.50*w, -2.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.85*w, 3.33*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.94*w, -1.92*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.27*w, -0.53*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.95*w, 2.48*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.23*w, -3.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.17*w, 2.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.97*w, -0.04*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.25*w, -2.00*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.31*w, 3.08*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.94*w, -2.59*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.37*w, 0.64*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.13*w, 1.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.03*w, -3.65*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.60*w, 3.17*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.14*w, -1.19*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.00*w, -1.19*h)));\r\n\t}\r\n\telse {\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.85*w, 0.36*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.52*w, -1.14*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.46*w, 1.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.46*w, -0.83*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.79*w, -0.42*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.11*w, 1.62*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.29*w, -2.07*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.69*w, 1.39*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.28*w, 0.12*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.65*w, -1.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.08*w, 2.44*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.63*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.55*w, 0.31*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.13*w, 1.52*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.56*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.38*w, 2.34*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.64*w, -0.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.53*w, -1.21*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.06*w, 2.63*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.00*w, -2.69*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.59*w, 1.32*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.82*w, 0.78*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.57*w, -2.50*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(0.54*w, 2.93*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.39*w, -1.81*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, -0.28*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.04*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.02*w, -3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.09*w, 2.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-3.07*w, -0.25*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.44*w, -1.90*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-0.52*w, 3.05*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-1.68*w, -2.61*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(3.01*w, 0.79*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.76*w, 1.46*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.05*w, -2.94*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(1.21*w, 2.88*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(-2.84*w, -1.30*h)));\r\n\t\tblurred += highlightColor(texture2D(textureSampler, vUV + vec2(2.98*w, -0.96*h)));\r\n\t}\r\n\r\n\tblurred /= 39.0;\r\n\r\n\tgl_FragColor = blurred;\r\n\r\n\t//if(vUV.x > 0.5) { gl_FragColor.rgb *= 0.0; }\r\n}","marblePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float numberOfTilesHeight;\r\nuniform float numberOfTilesWidth;\r\nuniform float amplitude;\r\nuniform vec3 brickColor;\r\nuniform vec3 jointColor;\r\n\r\nconst vec3 tileSize = vec3(1.1, 1.0, 1.1);\r\nconst vec3 tilePct = vec3(0.98, 1.0, 0.98);\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat turbulence(vec2 P)\r\n{\r\n\tfloat val = 0.0;\r\n\tfloat freq = 1.0;\r\n\tfor (int i = 0; i < 4; i++)\r\n\t{\r\n\t\tval += abs(noise(P*freq) / freq);\r\n\t\tfreq *= 2.07;\r\n\t}\r\n\treturn val;\r\n}\r\n\r\nfloat round(float number){\r\n\treturn sign(number)*floor(abs(number) + 0.5);\r\n}\r\n\r\nvec3 marble_color(float x)\r\n{\r\n\tvec3 col;\r\n\tx = 0.5*(x + 1.);\r\n\tx = sqrt(x); \r\n\tx = sqrt(x);\r\n\tx = sqrt(x);\r\n\tcol = vec3(.2 + .75*x); \r\n\tcol.b *= 0.95; \r\n\treturn col;\r\n}\r\n\r\nvoid main()\r\n{\r\n\tfloat brickW = 1.0 / numberOfTilesWidth;\r\n\tfloat brickH = 1.0 / numberOfTilesHeight;\r\n\tfloat jointWPercentage = 0.01;\r\n\tfloat jointHPercentage = 0.01;\r\n\tvec3 color = brickColor;\r\n\tfloat yi = vUV.y / brickH;\r\n\tfloat nyi = round(yi);\r\n\tfloat xi = vUV.x / brickW;\r\n\r\n\tif (mod(floor(yi), 2.0) == 0.0){\r\n\t\txi = xi - 0.5;\r\n\t}\r\n\r\n\tfloat nxi = round(xi);\r\n\tvec2 brickvUV = vec2((xi - floor(xi)) / brickH, (yi - floor(yi)) / brickW);\r\n\r\n\tif (yi < nyi + jointHPercentage && yi > nyi - jointHPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.37, 0.25, 0.25), (yi - nyi) / jointHPercentage + 0.2);\r\n\t}\r\n\telse if (xi < nxi + jointWPercentage && xi > nxi - jointWPercentage){\r\n\t\tcolor = mix(jointColor, vec3(0.44, 0.44, 0.44), (xi - nxi) / jointWPercentage + 0.2);\r\n\t}\r\n\telse {\r\n\t\tfloat t = 6.28 * brickvUV.x / (tileSize.x + noise(vec2(vUV)*6.0));\r\n\t\tt += amplitude * turbulence(brickvUV.xy);\r\n\t\tt = sin(t);\r\n\t\tcolor = marble_color(t);\r\n\t}\r\n\r\n\tgl_FragColor = vec4(color, 0.0);\r\n}","outlinePixelShader":"precision highp float;\r\n\r\nuniform vec4 color;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n\tgl_FragColor = color;\r\n}","outlineVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\nattribute vec3 normal;\r\n\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\nuniform float offset;\r\n\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n\tvec3 offsetPosition = position + normal * offset;\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#else\r\n\tgl_Position = viewProjection * finalWorld * vec4(offsetPosition, 1.0);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","particlesPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\nuniform vec4 textureMask;\r\nuniform sampler2D diffuseSampler;\r\n\r\n#ifdef CLIPPLANE\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\r\n#ifdef CLIPPLANE\r\n\tif (fClipDistance > 0.0)\r\n\t\tdiscard;\r\n#endif\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tgl_FragColor = (baseColor * textureMask + (vec4(1., 1., 1., 1.) - textureMask)) * vColor;\r\n}","particlesVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec3 position;\r\nattribute vec4 color;\r\nattribute vec4 options;\r\n\r\n// Uniforms\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef CLIPPLANE\r\nuniform vec4 vClipPlane;\r\nuniform mat4 invView;\r\nvarying float fClipDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position, 1.0)).xyz; \r\n\tvec3 cornerPos;\r\n\tfloat size = options.y;\r\n\tfloat angle = options.x;\r\n\tvec2 offset = options.zw;\r\n\r\n\tcornerPos = vec3(offset.x - 0.5, offset.y - 0.5, 0.) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\t\r\n\tvColor = color;\r\n\tvUV = offset;\r\n\r\n\t// Clip plane\r\n#ifdef CLIPPLANE\r\n\tvec4 worldPos = invView * vec4(viewPos, 1.0);\r\n\tfClipDistance = dot(worldPos, vClipPlane);\r\n#endif\r\n}","passPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\n\r\nvoid main(void) \r\n{\r\n\tgl_FragColor = texture2D(textureSampler, vUV);\r\n}","postprocessVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","proceduralVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec2 position;\r\n\r\n// Output\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nconst vec2 madd = vec2(0.5, 0.5);\r\n\r\nvoid main(void) {\t\r\n\tvPosition = position;\r\n\tvUV = position * madd + madd;\r\n\tgl_Position = vec4(position, 0.0, 1.0);\r\n}","refractionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D refractionSampler;\r\n\r\n// Parameters\r\nuniform vec3 baseColor;\r\nuniform float depth;\r\nuniform float colorLevel;\r\n\r\nvoid main() {\r\n\tfloat ref = 1.0 - texture2D(refractionSampler, vUV).r;\r\n\r\n\tvec2 uv = vUV - vec2(0.5);\r\n\tvec2 offset = uv * depth * ref;\r\n\tvec3 sourceColor = texture2D(textureSampler, vUV - offset).rgb;\r\n\r\n\tgl_FragColor = vec4(sourceColor + sourceColor * ref * colorLevel, 1.0);\r\n}","roadPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vUV; \r\nuniform vec3 roadColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(gl_FragCoord.y * 100.0 , fbm(vUV * 2.0));\r\n\tvec3 color = roadColor * ratioy;\r\n\tgl_FragColor = vec4(color, 1.0);\r\n}","shadowMapPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvec4 pack(float depth)\r\n{\r\n\tconst vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\r\n\tconst vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\r\n\r\n\tvec4 res = fract(depth * bit_shift);\r\n\tres -= res.xxyz * bit_mask;\r\n\r\n\treturn res;\r\n}\r\n\r\n// Thanks to http://devmaster.net/\r\nvec2 packHalf(float depth) \r\n{ \r\n\tconst vec2 bitOffset = vec2(1.0 / 255., 0.);\r\n\tvec2 color = vec2(depth, fract(depth * 255.));\r\n\r\n\treturn color - (color.yy * bitOffset);\r\n}\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef ALPHATEST\r\n\tif (texture2D(diffuseSampler, vUV).a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\tfloat depth = vPosition.z / vPosition.w;\r\n\tdepth = depth * 0.5 + 0.5;\r\n\r\n#ifdef VSM\r\n\tfloat moment1 = depth;\r\n\tfloat moment2 = moment1 * moment1;\r\n\r\n\tgl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\r\n#else\r\n\tgl_FragColor = pack(depth);\r\n#endif\r\n}","shadowMapVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attribute\r\nattribute vec3 position;\r\n#ifdef BONES\r\nattribute vec4 matricesIndices;\r\nattribute vec4 matricesWeights;\r\n#endif\r\n\r\n// Uniform\r\n#ifdef INSTANCES\r\nattribute vec4 world0;\r\nattribute vec4 world1;\r\nattribute vec4 world2;\r\nattribute vec4 world3;\r\n#else\r\nuniform mat4 world;\r\n#endif\r\n\r\nuniform mat4 viewProjection;\r\n#ifdef BONES\r\nuniform mat4 mBones[BonesPerMesh];\r\n#endif\r\n\r\nvarying vec4 vPosition;\r\n\r\n#ifdef ALPHATEST\r\nvarying vec2 vUV;\r\nuniform mat4 diffuseMatrix;\r\n#ifdef UV1\r\nattribute vec2 uv;\r\n#endif\r\n#ifdef UV2\r\nattribute vec2 uv2;\r\n#endif\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#ifdef INSTANCES\r\n\tmat4 finalWorld = mat4(world0, world1, world2, world3);\r\n#else\r\n\tmat4 finalWorld = world;\r\n#endif\r\n\r\n#ifdef BONES\r\n\tmat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\r\n\tmat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\r\n\tmat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\r\n\tmat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\r\n\tfinalWorld = finalWorld * (m0 + m1 + m2 + m3);\r\n#endif\r\n\r\n\tvPosition = viewProjection * finalWorld * vec4(position, 1.0);\r\n\tgl_Position = vPosition;\r\n\r\n#ifdef ALPHATEST\r\n#ifdef UV1\r\n\tvUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\r\n#endif\r\n#ifdef UV2\r\n\tvUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\r\n#endif\r\n#endif\r\n}","spritesPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform bool alphaTest;\r\n\r\nvarying vec4 vColor;\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D diffuseSampler;\r\n\r\n// Fog\r\n#ifdef FOG\r\n\r\n#define FOGMODE_NONE 0.\r\n#define FOGMODE_EXP 1.\r\n#define FOGMODE_EXP2 2.\r\n#define FOGMODE_LINEAR 3.\r\n#define E 2.71828\r\n\r\nuniform vec4 vFogInfos;\r\nuniform vec3 vFogColor;\r\nvarying float fFogDistance;\r\n\r\nfloat CalcFogFactor()\r\n{\r\n\tfloat fogCoeff = 1.0;\r\n\tfloat fogStart = vFogInfos.y;\r\n\tfloat fogEnd = vFogInfos.z;\r\n\tfloat fogDensity = vFogInfos.w;\r\n\r\n\tif (FOGMODE_LINEAR == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\r\n\t}\r\n\telse if (FOGMODE_EXP == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\r\n\t}\r\n\telse if (FOGMODE_EXP2 == vFogInfos.x)\r\n\t{\r\n\t\tfogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\r\n\t}\r\n\r\n\treturn min(1., max(0., fogCoeff));\r\n}\r\n#endif\r\n\r\n\r\nvoid main(void) {\r\n\tvec4 baseColor = texture2D(diffuseSampler, vUV);\r\n\r\n\tif (alphaTest) \r\n\t{\r\n\t\tif (baseColor.a < 0.95)\r\n\t\t\tdiscard;\r\n\t}\r\n\r\n\tbaseColor *= vColor;\r\n\r\n#ifdef FOG\r\n\tfloat fog = CalcFogFactor();\r\n\tbaseColor.rgb = fog * baseColor.rgb + (1.0 - fog) * vFogColor;\r\n#endif\r\n\r\n\tgl_FragColor = baseColor;\r\n}","spritesVertexShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Attributes\r\nattribute vec4 position;\r\nattribute vec4 options;\r\nattribute vec4 cellInfo;\r\nattribute vec4 color;\r\n\r\n// Uniforms\r\nuniform vec2 textureInfos;\r\nuniform mat4 view;\r\nuniform mat4 projection;\r\n\r\n// Output\r\nvarying vec2 vUV;\r\nvarying vec4 vColor;\r\n\r\n#ifdef FOG\r\nvarying float fFogDistance;\r\n#endif\r\n\r\nvoid main(void) {\t\r\n\tvec3 viewPos = (view * vec4(position.xyz, 1.0)).xyz; \r\n\tvec2 cornerPos;\r\n\t\r\n\tfloat angle = position.w;\r\n\tvec2 size = vec2(options.x, options.y);\r\n\tvec2 offset = options.zw;\r\n\tvec2 uvScale = textureInfos.xy;\r\n\r\n\tcornerPos = vec2(offset.x - 0.5, offset.y - 0.5) * size;\r\n\r\n\t// Rotate\r\n\tvec3 rotatedCorner;\r\n\trotatedCorner.x = cornerPos.x * cos(angle) - cornerPos.y * sin(angle);\r\n\trotatedCorner.y = cornerPos.x * sin(angle) + cornerPos.y * cos(angle);\r\n\trotatedCorner.z = 0.;\r\n\r\n\t// Position\r\n\tviewPos += rotatedCorner;\r\n\tgl_Position = projection * vec4(viewPos, 1.0); \r\n\r\n\t// Color\r\n\tvColor = color;\r\n\t\r\n\t// Texture\r\n\tvec2 uvOffset = vec2(abs(offset.x - cellInfo.x), 1.0 - abs(offset.y - cellInfo.y));\r\n\r\n\tvUV = (uvOffset + cellInfo.zw) * uvScale;\r\n\r\n\t// Fog\r\n#ifdef FOG\r\n\tfFogDistance = viewPos.z;\r\n#endif\r\n}","ssaoPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#define SAMPLES 16\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D randomSampler;\r\n\r\nuniform float randTextureTiles;\r\nuniform float samplesFactor;\r\nuniform vec3 sampleSphere[16];\r\n\r\nuniform float totalStrength;\r\nuniform float radius;\r\nuniform float area;\r\nuniform float fallOff;\r\n\r\nvarying vec2 vUV;\r\n\r\nconst vec2 offset1 = vec2(0.0, 0.001);\r\nconst vec2 offset2 = vec2(0.001, 0.0);\r\n\r\nvec3 normalFromDepth(const float depth, const vec2 coords) {\r\n\tfloat depth1 = texture2D(textureSampler, coords + offset1).r;\r\n\tfloat depth2 = texture2D(textureSampler, coords + offset2).r;\r\n\r\n vec3 p1 = vec3(offset1, depth1 - depth);\r\n vec3 p2 = vec3(offset2, depth2 - depth);\r\n\r\n vec3 normal = cross(p1, p2);\r\n normal.z = -normal.z;\r\n\r\n return normalize(normal);\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tconst float base = 0.2;\r\n\r\n\tvec3 random = texture2D(randomSampler, vUV * randTextureTiles).rgb;\r\n\tfloat depth = texture2D(textureSampler, vUV).r;\r\n\tvec3 position = vec3(vUV, depth);\r\n\tvec3 normal = normalFromDepth(depth, vUV);\r\n\tfloat radiusDepth = radius / depth;\r\n\tfloat occlusion = 0.0;\r\n\r\n\tvec3 ray;\r\n\tvec3 hemiRay;\r\n\tfloat occlusionDepth;\r\n\tfloat difference;\r\n\r\n\tfor (int i = 0; i < SAMPLES; i++)\r\n\t{\r\n\t\tray = radiusDepth * reflect(sampleSphere[i], random);\r\n\t\themiRay = position + sign(dot(ray, normal)) * ray;\r\n\r\n\t\tocclusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;\r\n\t\tdifference = depth - occlusionDepth;\r\n\r\n\t\tocclusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\r\n\t}\r\n\r\n\tfloat ao = 1.0 - totalStrength * occlusion * samplesFactor;\r\n\r\n\tfloat result = clamp(ao + base, 0.0, 1.0);\r\n\tgl_FragColor.r = result;\r\n\tgl_FragColor.g = result;\r\n\tgl_FragColor.b = result;\r\n\tgl_FragColor.a = 1.0;\r\n}\r\n","ssaoCombinePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D originalColor;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = texture2D(originalColor, vUV) * texture2D(textureSampler, vUV);\r\n}\r\n","stereoscopicInterlacePixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nconst vec3 TWO = vec3(2.0, 2.0, 2.0);\r\n\r\nvarying vec2 vUV;\r\nuniform sampler2D camASampler;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 stepSize;\r\n\r\nvoid main(void)\r\n{\r\n bool useCamB;\r\n vec2 texCoord1;\r\n vec2 texCoord2;\r\n \r\n vec3 frag1;\r\n vec3 frag2;\r\n \r\n#ifdef IS_STEREOSCOPIC_HORIZ\r\n\t useCamB = vUV.x > 0.5;\r\n\t texCoord1 = vec2(useCamB ? (vUV.x - 0.5) * 2.0 : vUV.x * 2.0, vUV.y);\r\n\t texCoord2 = vec2(texCoord1.x + stepSize.x, vUV.y);\r\n#else\r\n\t useCamB = vUV.y > 0.5;\r\n\t texCoord1 = vec2(vUV.x, useCamB ? (vUV.y - 0.5) * 2.0 : vUV.y * 2.0);\r\n\t texCoord2 = vec2(vUV.x, texCoord1.y + stepSize.y);\r\n#endif\r\n \r\n // cannot assign a sampler to a variable, so must duplicate texture accesses\r\n if (useCamB){\r\n frag1 = texture2D(textureSampler, texCoord1).rgb;\r\n frag2 = texture2D(textureSampler, texCoord2).rgb;\r\n }else{\r\n frag1 = texture2D(camASampler , texCoord1).rgb;\r\n frag2 = texture2D(camASampler , texCoord2).rgb;\r\n }\r\n \r\n gl_FragColor = vec4((frag1 + frag2) / TWO, 1.0);\r\n}","volumetricLightScatteringPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nuniform sampler2D textureSampler;\r\nuniform sampler2D lightScatteringSampler;\r\n\r\nuniform float decay;\r\nuniform float exposure;\r\nuniform float weight;\r\nuniform float density;\r\nuniform vec2 meshPositionOnScreen;\r\n\r\nvarying vec2 vUV;\r\n\r\nvoid main(void) {\r\n vec2 tc = vUV;\r\n\tvec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\r\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\r\n\r\n float illuminationDecay = 1.0;\r\n\r\n\tvec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\r\n\r\n for(int i=0; i < NUM_SAMPLES; i++) {\r\n tc -= deltaTexCoord;\r\n\t\tvec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\r\n sample *= illuminationDecay * weight;\r\n color += sample;\r\n illuminationDecay *= decay;\r\n }\r\n\r\n vec4 realColor = texture2D(textureSampler, vUV);\r\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\r\n}\r\n","volumetricLightScatteringPassPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(NEED_UV)\r\nvarying vec2 vUV;\r\n#endif\r\n\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\nuniform sampler2D diffuseSampler;\r\n#endif\r\n\r\n#if defined(OPACITY)\r\nuniform sampler2D opacitySampler;\r\nuniform float opacityLevel;\r\n#endif\r\n\r\nvoid main(void)\r\n{\r\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\r\n\tvec4 diffuseColor = texture2D(diffuseSampler, vUV);\r\n#endif\r\n\r\n#ifdef ALPHATEST\r\n\tif (diffuseColor.a < 0.4)\r\n\t\tdiscard;\r\n#endif\r\n\r\n#ifdef OPACITY\r\n\tvec4 opacityColor = texture2D(opacitySampler, vUV);\r\n\tfloat alpha = 1.0;\r\n\r\n\t#ifdef OPACITYRGB\r\n\topacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\r\n\talpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\r\n\t#else\r\n\talpha *= opacityColor.a * opacityLevel;\r\n\t#endif\r\n\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = vec4(diffuseColor.rgb, alpha);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\r\n\t#endif\r\n\r\n\tgl_FragColor.a = alpha;\r\n#else\r\n\t#ifndef BASIC_RENDER\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\t#else\r\n\tgl_FragColor = diffuseColor;\r\n\t#endif\r\n#endif\r\n\r\n}\r\n","vrDistortionCorrectionPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\n// Samplers\r\nvarying vec2 vUV;\r\nuniform sampler2D textureSampler;\r\nuniform vec2 LensCenter;\r\nuniform vec2 Scale;\r\nuniform vec2 ScaleIn;\r\nuniform vec4 HmdWarpParam;\r\n\r\nvec2 HmdWarp(vec2 in01) {\r\n\r\n\tvec2 theta = (in01 - LensCenter) * ScaleIn; // Scales to [-1, 1]\r\n\tfloat rSq = theta.x * theta.x + theta.y * theta.y;\r\n\tvec2 rvector = theta * (HmdWarpParam.x + HmdWarpParam.y * rSq + HmdWarpParam.z * rSq * rSq + HmdWarpParam.w * rSq * rSq * rSq);\r\n\treturn LensCenter + Scale * rvector;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\tvec2 tc = HmdWarp(vUV);\r\n\tif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\r\n\t\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\r\n\telse{\r\n\t\tgl_FragColor = vec4(texture2D(textureSampler, tc).rgb, 1.0);\r\n\t}\r\n}","woodPixelShader":"#ifdef GL_ES\r\nprecision highp float;\r\n#endif\r\n\r\nvarying vec2 vPosition;\r\nvarying vec2 vUV;\r\n\r\nuniform float ampScale;\r\nuniform vec3 woodColor;\r\n\r\nfloat rand(vec2 n) {\r\n\treturn fract(cos(dot(n, vec2(12.9898, 4.1414))) * 43758.5453);\r\n}\r\n\r\nfloat noise(vec2 n) {\r\n\tconst vec2 d = vec2(0.0, 1.0);\r\n\tvec2 b = floor(n), f = smoothstep(vec2(0.0), vec2(1.0), fract(n));\r\n\treturn mix(mix(rand(b), rand(b + d.yx), f.x), mix(rand(b + d.xy), rand(b + d.yy), f.x), f.y);\r\n}\r\n\r\nfloat fbm(vec2 n) {\r\n\tfloat total = 0.0, amplitude = 1.0;\r\n\tfor (int i = 0; i < 4; i++) {\r\n\t\ttotal += noise(n) * amplitude;\r\n\t\tn += n;\r\n\t\tamplitude *= 0.5;\r\n\t}\r\n\treturn total;\r\n}\r\n\r\nvoid main(void) {\r\n\tfloat ratioy = mod(vUV.x * ampScale, 2.0 + fbm(vUV * 0.8));\r\n\tvec3 wood = woodColor * ratioy;\r\n\tgl_FragColor = vec4(wood, 1.0);\r\n}"};
  31743. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return t.x>o.x+i?!1:o.x-i>e.x?!1:t.y>o.y+i?!1:o.y-i>e.y?!1:t.z>o.z+i?!1:o.z-i>e.z?!1:!0},o=function(t,e,o,i){var s=e*e-4*t*o,r={root:0,found:!1};if(0>s)return r;var n=Math.sqrt(s),c=(-e-n)/(2*t),h=(-e+n)/(2*t);if(c>h){var a=h;h=c,c=a}return c>0&&i>c?(r.root=c,r.found=!0,r):h>0&&i>h?(r.root=h,r.found=!0,r):r},i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return 0>n?!1:(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),0>n?!1:(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return n>this.velocityWorldLength+c+i?!1:e(s,r,this.basePointWorld,this.velocityWorldLength+c)?!0:!1},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||0>V)return;0>h&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var m=this.velocity.lengthSquared(),f=m;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(f,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),f=g*-m+v*v,T=2*g*t.Vector3.Dot(this.velocity,this._baseToVertex)-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(f,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&1>=D&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;s>c;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;a>c;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?((0!==e.x||0!==e.y||0!==e.z)&&this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i,r;if(r=e.subMeshes,i=r.length,!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;i>s;s++){var l=r[s];i>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;s>t;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;a>t;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){for(var i in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(i)&&this._collisionCache.addGeometry(e.updatedGeometries[i]);for(var r in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(r)&&this._collisionCache.addMesh(e.updatedMeshes[r]);var t={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};postMessage(t,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\",function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(e.WorkerTaskType||(e.WorkerTaskType={}));var o=e.WorkerTaskType;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(e.WorkerReplyType||(e.WorkerReplyType={}));var i=e.WorkerReplyType,t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t.SerializeMesh=function(e){var o=[];e.subMeshes&&(o=e.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var i=e.geometry?e.geometry.id:null;return{uniqueId:e.uniqueId,id:e.id,name:e.name,geometryId:i,sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:e.worldMatrixFromCache.asArray(),subMeshes:o,checkCollisions:e.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Int32Array(o.getIndices()||[])}},t}();e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?((0!==i.x||0!==i.y||0!==i.z)&&t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){var i=function(){function t(t,i,o){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),this.r=t,this.g=i,this.b=o}return t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},t.prototype.toColor4=function(t){return void 0===t&&(t=1),new o(this.r,this.g,this.b,t)},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b)},t.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},t.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b)},t.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},t.prototype.clone=function(){return new t(this.r,this.g,this.b)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},t.prototype.copyFromFloats=function(t,i,o){return this.r=t,this.g=i,this.b=o,this},t.FromArray=function(i,o){return void 0===o&&(o=0),new t(i[o],i[o+1],i[o+2])},t.FromInts=function(i,o,n){return new t(i/255,o/255,n/255)},t.Lerp=function(i,o,n){var r=i.r+(o.r-i.r)*n,s=i.g+(o.g-i.g)*n,e=i.b+(o.b-i.b)*n;return new t(r,s,e)},t.Red=function(){return new t(1,0,0)},t.Green=function(){return new t(0,1,0)},t.Blue=function(){return new t(0,0,1)},t.Black=function(){return new t(0,0,0)},t.White=function(){return new t(1,1,1)},t.Purple=function(){return new t(.5,0,.5)},t.Magenta=function(){return new t(1,0,1)},t.Yellow=function(){return new t(1,1,0)},t.Gray=function(){return new t(.5,.5,.5)},t}();t.Color3=i;var o=function(){function t(t,i,o,n){this.r=t,this.g=i,this.b=o,this.a=n}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.Lerp=function(i,o,n){var r=new t(0,0,0,0);return t.LerpToRef(i,o,n,r),r},t.LerpToRef=function(t,i,o,n){n.r=t.r+(i.r-t.r)*o,n.g=t.g+(i.g-t.g)*o,n.b=t.b+(i.b-t.b)*o,n.a=t.a+(i.a-t.a)*o},t.FromArray=function(i,o){return void 0===o&&(o=0),new t(i[o],i[o+1],i[o+2],i[o+3])},t.FromInts=function(i,o,n,r){return new t(i/255,o/255,n/255,r/255)},t}();t.Color4=o;var n=function(){function i(t,i){this.x=t,this.y=i}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},i.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.addVector3=function(t){return new i(this.x+t.x,this.y+t.y)},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y)},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},i.prototype.multiplyByFloats=function(t,o){return new i(this.x*t,this.y*o)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},i.prototype.negate=function(){return new i(-this.x,-this.y)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t)},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},i.prototype.equalsWithEpsilon=function(i){return i&&t.Tools.WithinEpsilon(this.x,i.x)&&t.Tools.WithinEpsilon(this.y,i.y)},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},i.prototype.clone=function(){return new i(this.x,this.y)},i.Zero=function(){return new i(0,0)},i.FromArray=function(t,o){return void 0===o&&(o=0),new i(t[o],t[o+1])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1]},i.CatmullRom=function(t,o,n,r,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-t.x+n.x)*s+(2*t.x-5*o.x+4*n.x-r.x)*e+(-t.x+3*o.x-3*n.x+r.x)*a),u=.5*(2*o.y+(-t.y+n.y)*s+(2*t.y-5*o.y+4*n.y-r.y)*e+(-t.y+3*o.y-3*n.y+r.y)*a);return new i(h,u)},i.Clamp=function(t,o,n){var r=t.x;r=r>n.x?n.x:r,r=r<o.x?o.x:r;var s=t.y;return s=s>n.y?n.y:s,s=s<o.y?o.y:s,new i(r,s)},i.Hermite=function(t,o,n,r,s){var e=s*s,a=s*e,h=2*a-3*e+1,u=-2*a+3*e,l=a-2*e+s,m=a-e,f=t.x*h+n.x*u+o.x*l+r.x*m,x=t.y*h+n.y*u+o.y*l+r.y*m;return new i(f,x)},i.Lerp=function(t,o,n){var r=t.x+(o.x-t.x)*n,s=t.y+(o.y-t.y)*n;return new i(r,s)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y},i.Normalize=function(t){var i=t.clone();return i.normalize(),i},i.Minimize=function(t,o){var n=t.x<o.x?t.x:o.x,r=t.y<o.y?t.y:o.y;return new i(n,r)},i.Maximize=function(t,o){var n=t.x>o.x?t.x:o.x,r=t.y>o.y?t.y:o.y;return new i(n,r)},i.Transform=function(t,o){var n=t.x*o.m[0]+t.y*o.m[4],r=t.x*o.m[1]+t.y*o.m[5];return new i(n,r)},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y;return o*o+n*n},i}();t.Vector2=n;var r=function(){function i(t,i,o){this.x=t,this.y=i,this.z=o}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},i.prototype.toQuaternion=function(){var t=new e(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),o=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),r=Math.sin(.5*(this.z-this.x)),s=Math.cos(.5*this.y),a=Math.sin(.5*this.y);return t.x=n*a,t.y=-r*a,t.z=o*s,t.w=i*s,t},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},i.prototype.subtractFromFloats=function(t,o,n){return new i(this.x-t,this.y-o,this.z-n)},i.prototype.subtractFromFloatsToRef=function(t,i,o,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-o,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},i.prototype.equalsWithEpsilon=function(i){return i&&t.Tools.WithinEpsilon(this.x,i.x)&&t.Tools.WithinEpsilon(this.y,i.y)&&t.Tools.WithinEpsilon(this.z,i.z)},i.prototype.equalsToFloats=function(t,i,o){return this.x===t&&this.y===i&&this.z===o},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},i.prototype.multiplyByFloats=function(t,o,n){return new i(this.x*t,this.y*o,this.z*n)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},i.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},i.prototype.copyFromFloats=function(t,i,o){return this.x=t,this.y=i,this.z=o,this},i.GetClipFactor=function(t,o,n,r){var s=i.Dot(t,n)-r,e=i.Dot(o,n)-r,a=s/(s-e);return a},i.FromArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2]},i.FromFloatArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2]},i.FromFloatsToRef=function(t,i,o,n){n.x=t,n.y=i,n.z=o},i.Zero=function(){return new i(0,0,0)},i.Up=function(){return new i(0,1,0)},i.TransformCoordinates=function(t,o){var n=i.Zero();return i.TransformCoordinatesToRef(t,o,n),n},i.TransformCoordinatesToRef=function(t,i,o){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],r=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],s=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],e=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];o.x=n/e,o.y=r/e,o.z=s/e},i.TransformCoordinatesFromFloatsToRef=function(t,i,o,n,r){var s=t*n.m[0]+i*n.m[4]+o*n.m[8]+n.m[12],e=t*n.m[1]+i*n.m[5]+o*n.m[9]+n.m[13],a=t*n.m[2]+i*n.m[6]+o*n.m[10]+n.m[14],h=t*n.m[3]+i*n.m[7]+o*n.m[11]+n.m[15];r.x=s/h,r.y=e/h,r.z=a/h},i.TransformCoordinatesToRefSIMD=function(t,i,o){var n=SIMD.float32x4.loadXYZ(t._data,0),r=SIMD.float32x4.load(i.m,0),s=SIMD.float32x4.load(i.m,4),e=SIMD.float32x4.load(i.m,8),a=SIMD.float32x4.load(i.m,12),h=SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,0,0,0,0),r),SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,1,1,1,1),s)),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(n,2,2,2,2),e),a));h=SIMD.float32x4.div(h,SIMD.float32x4.swizzle(h,3,3,3,3)),SIMD.float32x4.storeXYZ(o._data,0,h)},i.TransformCoordinatesFromFloatsToRefSIMD=function(t,i,o,n,r){var s=SIMD.float32x4.splat(t),e=SIMD.float32x4.splat(i),a=SIMD.float32x4.splat(o),h=SIMD.float32x4.load(n.m,0),u=SIMD.float32x4.load(n.m,4),l=SIMD.float32x4.load(n.m,8),m=SIMD.float32x4.load(n.m,12),f=SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(s,h),SIMD.float32x4.mul(e,u)),SIMD.float32x4.add(SIMD.float32x4.mul(a,l),m));f=SIMD.float32x4.div(f,SIMD.float32x4.swizzle(f,3,3,3,3)),SIMD.float32x4.storeXYZ(r._data,0,f)},i.TransformNormal=function(t,o){var n=i.Zero();return i.TransformNormalToRef(t,o,n),n},i.TransformNormalToRef=function(t,i,o){o.x=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o.y=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],o.z=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]},i.TransformNormalFromFloatsToRef=function(t,i,o,n,r){r.x=t*n.m[0]+i*n.m[4]+o*n.m[8],r.y=t*n.m[1]+i*n.m[5]+o*n.m[9],r.z=t*n.m[2]+i*n.m[6]+o*n.m[10]},i.CatmullRom=function(t,o,n,r,s){var e=s*s,a=s*e,h=.5*(2*o.x+(-t.x+n.x)*s+(2*t.x-5*o.x+4*n.x-r.x)*e+(-t.x+3*o.x-3*n.x+r.x)*a),u=.5*(2*o.y+(-t.y+n.y)*s+(2*t.y-5*o.y+4*n.y-r.y)*e+(-t.y+3*o.y-3*n.y+r.y)*a),l=.5*(2*o.z+(-t.z+n.z)*s+(2*t.z-5*o.z+4*n.z-r.z)*e+(-t.z+3*o.z-3*n.z+r.z)*a);return new i(h,u,l)},i.Clamp=function(t,o,n){var r=t.x;r=r>n.x?n.x:r,r=r<o.x?o.x:r;var s=t.y;s=s>n.y?n.y:s,s=s<o.y?o.y:s;var e=t.z;return e=e>n.z?n.z:e,e=e<o.z?o.z:e,new i(r,s,e)},i.Hermite=function(t,o,n,r,s){var e=s*s,a=s*e,h=2*a-3*e+1,u=-2*a+3*e,l=a-2*e+s,m=a-e,f=t.x*h+n.x*u+o.x*l+r.x*m,x=t.y*h+n.y*u+o.y*l+r.y*m,y=t.z*h+n.z*u+o.z*l+r.z*m;return new i(f,x,y)},i.Lerp=function(t,o,n){var r=t.x+(o.x-t.x)*n,s=t.y+(o.y-t.y)*n,e=t.z+(o.z-t.z)*n;return new i(r,s,e)},i.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},i.Cross=function(t,o){var n=i.Zero();return i.CrossToRef(t,o,n),n},i.CrossToRef=function(t,i,o){o.x=t.y*i.z-t.z*i.y,o.y=t.z*i.x-t.x*i.z,o.z=t.x*i.y-t.y*i.x},i.Normalize=function(t){var o=i.Zero();return i.NormalizeToRef(t,o),o},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Project=function(t,o,n,r){var s=r.width,e=r.height,h=r.x,u=r.y,l=a.FromValues(s/2,0,0,0,0,-e/2,0,0,0,0,1,0,h+s/2,e/2+u,0,1),m=o.multiply(n).multiply(l);return i.TransformCoordinates(t,m)},i.UnprojectFromTransform=function(o,n,r,s,e){var a=s.multiply(e);a.invert(),o.x=o.x/n*2-1,o.y=-(o.y/r*2-1);var h=i.TransformCoordinates(o,a),u=o.x*a.m[3]+o.y*a.m[7]+o.z*a.m[11]+a.m[15];return t.Tools.WithinEpsilon(u,1)&&(h=h.scale(1/u)),h},i.Unproject=function(o,n,r,s,e,a){var h=s.multiply(e).multiply(a);h.invert(),o.x=o.x/n*2-1,o.y=-(o.y/r*2-1);var u=i.TransformCoordinates(o,h),l=o.x*h.m[3]+o.y*h.m[7]+o.z*h.m[11]+h.m[15];return t.Tools.WithinEpsilon(l,1)&&(u=u.scale(1/l)),u},i.Minimize=function(t,i){var o=t.clone();return o.MinimizeInPlace(i),o},i.Maximize=function(t,i){var o=t.clone();return o.MaximizeInPlace(i),o},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y,r=t.z-i.z;return o*o+n*n+r*r},i.Center=function(t,i){var o=t.add(i);return o.scaleInPlace(.5),o},i.RotationFromAxis=function(t,o,n){var r,s,e,a=i.Normalize(t),h=(i.Normalize(o),i.Normalize(n)),u=f.X,l=f.Y,m=(f.Z,0),x=0,y=0,c=0,p=0,z=0,M=0,w=-1,I=(Math.PI,0),d=0;0==h.z?z=1:0==h.x?c=1:(M=h.z/h.x,c=-M*Math.sqrt(1/(1+M*M)),z=Math.sqrt(1/(1+M*M))),s=new i(c,p,z),e=i.Cross(h,s),r=i.Cross(a,s),i.Dot(h,r)<0&&(w=1),d=i.Dot(a,s),y=Math.acos(d)*w,i.Dot(s,u)<0&&(y=Math.PI+y,s=s.scaleInPlace(-1),e=e.scaleInPlace(-1),I++);var D,S;return c=0,p=0,z=0,w=-1,0==h.z?c=1:(M=s.z/s.x,c=-M*Math.sqrt(1/(1+M*M)),z=Math.sqrt(1/(1+M*M))),D=new i(c,p,z),S=i.Cross(D,s),r=i.Cross(h,D),i.Dot(s,r)<0&&(w=1),d=i.Dot(h,D),x=Math.acos(d)*w,i.Dot(S,l)<0&&(x=Math.PI+x,S=S.scaleInPlace(-1),D=D.scaleInPlace(-1),I++),w=-1,r=i.Cross(u,s),i.Dot(r,l)<0&&(w=1),d=i.Dot(s,u),m=-Math.acos(d)*w,0>d&&2>I&&(m=Math.PI+m),new i(x,m,y)},i}();t.Vector3=r;var s=function(){function i(t,i,o,n){this.x=t,this.y=i,this.z=o,this.w=n}return i.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"W:\"+this.w+\"}\"},i.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},i.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},i.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},i.prototype.add=function(t){return new i(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},i.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},i.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},i.prototype.subtract=function(t){return new i(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},i.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},i.prototype.subtractFromFloats=function(t,o,n,r){return new i(this.x-t,this.y-o,this.z-n,this.w-r)},i.prototype.subtractFromFloatsToRef=function(t,i,o,n,r){return r.x=this.x-t,r.y=this.y-i,r.z=this.z-o,r.w=this.w-n,this},i.prototype.negate=function(){return new i(-this.x,-this.y,-this.z,-this.w)},i.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},i.prototype.scale=function(t){return new i(this.x*t,this.y*t,this.z*t,this.w*t)},i.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},i.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},i.prototype.equalsWithEpsilon=function(i){return Math.abs(this.x-i.x)<t.Engine.Epsilon&&Math.abs(this.y-i.y)<t.Engine.Epsilon&&Math.abs(this.z-i.z)<t.Engine.Epsilon&&Math.abs(this.w-i.w)<t.Engine.Epsilon},i.prototype.equalsToFloats=function(t,i,o,n){return this.x===t&&this.y===i&&this.z===o&&this.w===n},i.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},i.prototype.multiply=function(t){return new i(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},i.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},i.prototype.multiplyByFloats=function(t,o,n,r){return new i(this.x*t,this.y*o,this.z*n,this.w*r)},i.prototype.divide=function(t){return new i(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},i.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},i.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},i.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},i.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},i.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},i.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},i.prototype.clone=function(){return new i(this.x,this.y,this.z,this.w)},i.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},i.prototype.copyFromFloats=function(t,i,o,n){return this.x=t,this.y=i,this.z=o,this.w=n,this},i.FromArray=function(t,o){return o||(o=0),new i(t[o],t[o+1],t[o+2],t[o+3])},i.FromArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2],o.w=t[i+3]},i.FromFloatArrayToRef=function(t,i,o){o.x=t[i],o.y=t[i+1],o.z=t[i+2],o.w=t[i+3]},i.FromFloatsToRef=function(t,i,o,n,r){r.x=t,r.y=i,r.z=o,r.w=n},i.Zero=function(){return new i(0,0,0,0)},i.Normalize=function(t){var o=i.Zero();return i.NormalizeToRef(t,o),o},i.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},i.Minimize=function(t,i){var o=t.clone();return o.MinimizeInPlace(i),o},i.Maximize=function(t,i){var o=t.clone();return o.MaximizeInPlace(i),o},i.Distance=function(t,o){return Math.sqrt(i.DistanceSquared(t,o))},i.DistanceSquared=function(t,i){var o=t.x-i.x,n=t.y-i.y,r=t.z-i.z,s=t.w-i.w;return o*o+n*n+r*r+s*s},i.Center=function(t,i){var o=t.add(i);return o.scaleInPlace(.5),o},i}();t.Vector4=s;var e=function(){function t(t,i,o,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===o&&(o=0),void 0===n&&(n=1),this.x=t,this.y=i,this.z=o,this.w=n}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,o,n){return this.x=t,this.y=i,this.z=o,this.w=n,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var o=new t(0,0,0,1);return this.multiplyToRef(i,o),o},t.prototype.multiplyToRef=function(t,i){var o=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,n=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,r=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,s=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(o,n,r,s),this},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(){var t=r.Zero();return this.toEulerAnglesToRef(t),t},t.prototype.toEulerAnglesToRef=function(t){var i=this.x,o=this.y,n=this.z,r=this.w,s=i*o,e=i*n,a=r*o,h=r*n,u=r*i,l=o*n,m=i*i,f=o*o,x=m+f;return 0!==x&&1!==x?(t.x=Math.atan2(e+a,u-l),t.y=Math.acos(1-2*x),t.z=Math.atan2(e-a,u+l)):0===x?(t.x=0,t.y=0,t.z=Math.atan2(s-h,.5-f-n*n)):(t.x=Math.atan2(s-h,.5-f-n*n),t.y=Math.PI,t.z=0),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,o=this.y*this.y,n=this.z*this.z,r=this.x*this.y,s=this.z*this.w,e=this.z*this.x,a=this.y*this.w,h=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(o+n),t.m[1]=2*(r+s),t.m[2]=2*(e-a),t.m[3]=0,t.m[4]=2*(r-s),t.m[5]=1-2*(n+i),t.m[6]=2*(h+u),t.m[7]=0,t.m[8]=2*(e+a),t.m[9]=2*(h-u),t.m[10]=1-2*(o+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var o=new t;return t.FromRotationMatrixToRef(i,o),o},t.FromRotationMatrixToRef=function(t,i){var o,n=t.m,r=n[0],s=n[4],e=n[8],a=n[1],h=n[5],u=n[9],l=n[2],m=n[6],f=n[10],x=r+h+f;x>0?(o=.5/Math.sqrt(x+1),i.w=.25/o,i.x=(m-u)*o,i.y=(e-l)*o,i.z=(a-s)*o):r>h&&r>f?(o=2*Math.sqrt(1+r-h-f),i.w=(m-u)/o,i.x=.25*o,i.y=(s+a)/o,i.z=(e+l)/o):h>f?(o=2*Math.sqrt(1+h-r-f),i.w=(e-l)/o,i.x=(s+a)/o,i.y=.25*o,i.z=(u+m)/o):(o=2*Math.sqrt(1+f-r-h),i.w=(a-s)/o,i.x=(e+l)/o,i.y=(u+m)/o,i.z=.25*o)},t.Inverse=function(i){return new t(-i.x,-i.y,-i.z,i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,o){var n=new t,r=Math.sin(o/2);return n.w=Math.cos(o/2),n.x=i.x*r,n.y=i.y*r,n.z=i.z*r,n},t.FromArray=function(i,o){return o||(o=0),new t(i[o],i[o+1],i[o+2],i[o+3])},t.RotationYawPitchRoll=function(i,o,n){var r=new t;return t.RotationYawPitchRollToRef(i,o,n,r),r},t.RotationYawPitchRollToRef=function(t,i,o,n){var r=.5*o,s=.5*i,e=.5*t,a=Math.sin(r),h=Math.cos(r),u=Math.sin(s),l=Math.cos(s),m=Math.sin(e),f=Math.cos(e);n.x=f*u*h+m*l*a,n.y=m*l*h-f*u*a,n.z=f*l*a-m*u*h,n.w=f*l*h+m*u*a},t.RotationAlphaBetaGamma=function(i,o,n){var r=new t;return t.RotationAlphaBetaGammaToRef(i,o,n,r),r},t.RotationAlphaBetaGammaToRef=function(t,i,o,n){var r=.5*(o+t),s=.5*(o-t),e=.5*i;n.x=Math.cos(s)*Math.sin(e),n.y=Math.sin(s)*Math.sin(e),n.z=Math.sin(r)*Math.cos(e),n.w=Math.cos(r)*Math.cos(e)},t.Slerp=function(i,o,n){var r,s,e=n,a=i.x*o.x+i.y*o.y+i.z*o.z+i.w*o.w,h=!1;if(0>a&&(h=!0,a=-a),a>.999999)s=1-e,r=h?-e:e;else{var u=Math.acos(a),l=1/Math.sin(u);s=Math.sin((1-e)*u)*l,r=h?-Math.sin(e*u)*l:Math.sin(e*u)*l}return new t(s*i.x+r*o.x,s*i.y+r*o.y,s*i.z+r*o.z,s*i.w+r*o.w)},t}();t.Quaternion=e;var a=function(){function i(){this.m=new Float32Array(16)}return i.prototype.isIdentity=function(){return 1!==this.m[0]||1!==this.m[5]||1!==this.m[10]||1!==this.m[15]?!1:0!==this.m[1]||0!==this.m[2]||0!==this.m[3]||0!==this.m[4]||0!==this.m[6]||0!==this.m[7]||0!==this.m[8]||0!==this.m[9]||0!==this.m[11]||0!==this.m[12]||0!==this.m[13]||0!==this.m[14]?!1:!0},i.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],o=this.m[9]*this.m[14]-this.m[10]*this.m[13],n=this.m[8]*this.m[15]-this.m[11]*this.m[12],r=this.m[8]*this.m[14]-this.m[10]*this.m[12],s=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*o)-this.m[1]*(this.m[4]*t-this.m[6]*n+this.m[7]*r)+this.m[2]*(this.m[4]*i-this.m[5]*n+this.m[7]*s)-this.m[3]*(this.m[4]*o-this.m[5]*r+this.m[6]*s)},i.prototype.toArray=function(){return this.m},i.prototype.asArray=function(){return this.toArray()},i.prototype.invert=function(){return this.invertToRef(this),this},i.prototype.invertToRef=function(t){var i=this.m[0],o=this.m[1],n=this.m[2],r=this.m[3],s=this.m[4],e=this.m[5],a=this.m[6],h=this.m[7],u=this.m[8],l=this.m[9],m=this.m[10],f=this.m[11],x=this.m[12],y=this.m[13],c=this.m[14],p=this.m[15],z=m*p-f*c,M=l*p-f*y,w=l*c-m*y,I=u*p-f*x,d=u*c-m*x,D=u*y-l*x,S=e*z-a*M+h*w,v=-(s*z-a*I+h*d),g=s*M-e*I+h*D,T=-(s*w-e*d+a*D),R=1/(i*S+o*v+n*g+r*T),_=a*p-h*c,b=e*p-h*y,A=e*c-a*y,F=s*p-h*x,P=s*c-a*x,C=s*y-e*x,L=a*f-h*m,q=e*f-h*l,E=e*m-a*l,Z=s*f-h*u,N=s*m-a*u,V=s*l-e*u;return t.m[0]=S*R,t.m[4]=v*R,t.m[8]=g*R,t.m[12]=T*R,t.m[1]=-(o*z-n*M+r*w)*R,t.m[5]=(i*z-n*I+r*d)*R,t.m[9]=-(i*M-o*I+r*D)*R,t.m[13]=(i*w-o*d+n*D)*R,t.m[2]=(o*_-n*b+r*A)*R,t.m[6]=-(i*_-n*F+r*P)*R,t.m[10]=(i*b-o*F+r*C)*R,t.m[14]=-(i*A-o*P+n*C)*R,t.m[3]=-(o*L-n*q+r*E)*R,t.m[7]=(i*L-n*Z+r*N)*R,t.m[11]=-(i*q-o*Z+r*V)*R,t.m[15]=(i*E-o*N+n*V)*R,this},i.prototype.invertToRefSIMD=function(t){var i,o,n,r,s,e,a,h,u,l,m=this.m,f=t.m,x=SIMD.float32x4.load(m,0),y=SIMD.float32x4.load(m,4),c=SIMD.float32x4.load(m,8),p=SIMD.float32x4.load(m,12);return s=SIMD.float32x4.shuffle(x,y,0,1,4,5),o=SIMD.float32x4.shuffle(c,p,0,1,4,5),i=SIMD.float32x4.shuffle(s,o,0,2,4,6),o=SIMD.float32x4.shuffle(o,s,1,3,5,7),s=SIMD.float32x4.shuffle(x,y,2,3,6,7),r=SIMD.float32x4.shuffle(c,p,2,3,6,7),n=SIMD.float32x4.shuffle(s,r,0,2,4,6),r=SIMD.float32x4.shuffle(r,s,1,3,5,7),s=SIMD.float32x4.mul(n,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.mul(o,s),a=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(SIMD.float32x4.mul(o,s),e),a=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),a),a=SIMD.float32x4.swizzle(a,2,3,0,1),s=SIMD.float32x4.mul(o,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),e=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),e),u=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(e,SIMD.float32x4.mul(r,s)),u=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),u),u=SIMD.float32x4.swizzle(u,2,3,0,1),s=SIMD.float32x4.mul(SIMD.float32x4.swizzle(o,2,3,0,1),r),s=SIMD.float32x4.swizzle(s,1,0,3,2),n=SIMD.float32x4.swizzle(n,2,3,0,1),e=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),e),h=SIMD.float32x4.mul(i,s),s=SIMD.float32x4.swizzle(s,2,3,0,1),e=SIMD.float32x4.sub(e,SIMD.float32x4.mul(n,s)),h=SIMD.float32x4.sub(SIMD.float32x4.mul(i,s),h),h=SIMD.float32x4.swizzle(h,2,3,0,1),s=SIMD.float32x4.mul(i,o),s=SIMD.float32x4.swizzle(s,1,0,3,2),h=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),h),u=SIMD.float32x4.sub(SIMD.float32x4.mul(n,s),u),s=SIMD.float32x4.swizzle(s,2,3,0,1),h=SIMD.float32x4.sub(SIMD.float32x4.mul(r,s),h),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(n,s)),s=SIMD.float32x4.mul(i,r),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(n,s)),h=SIMD.float32x4.add(SIMD.float32x4.mul(o,s),h),s=SIMD.float32x4.swizzle(s,2,3,0,1),a=SIMD.float32x4.add(SIMD.float32x4.mul(n,s),a),h=SIMD.float32x4.sub(h,SIMD.float32x4.mul(o,s)),s=SIMD.float32x4.mul(i,n),s=SIMD.float32x4.swizzle(s,1,0,3,2),a=SIMD.float32x4.add(SIMD.float32x4.mul(r,s),a),u=SIMD.float32x4.sub(u,SIMD.float32x4.mul(o,s)),s=SIMD.float32x4.swizzle(s,2,3,0,1),a=SIMD.float32x4.sub(a,SIMD.float32x4.mul(r,s)),u=SIMD.float32x4.add(SIMD.float32x4.mul(o,s),u),l=SIMD.float32x4.mul(i,e),l=SIMD.float32x4.add(SIMD.float32x4.swizzle(l,2,3,0,1),l),l=SIMD.float32x4.add(SIMD.float32x4.swizzle(l,1,0,3,2),l),s=SIMD.float32x4.reciprocalApproximation(l),l=SIMD.float32x4.sub(SIMD.float32x4.add(s,s),SIMD.float32x4.mul(l,SIMD.float32x4.mul(s,s))),l=SIMD.float32x4.swizzle(l,0,0,0,0),e=SIMD.float32x4.mul(l,e),a=SIMD.float32x4.mul(l,a),h=SIMD.float32x4.mul(l,h),u=SIMD.float32x4.mul(l,u),SIMD.float32x4.store(f,0,e),SIMD.float32x4.store(f,4,a),SIMD.float32x4.store(f,8,h),SIMD.float32x4.store(f,12,u),this},i.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},i.prototype.multiply=function(t){var o=new i;return this.multiplyToRef(t,o),o},i.prototype.copyFrom=function(t){for(var i=0;16>i;i++)this.m[i]=t.m[i];return this},i.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var o=0;16>o;o++)t[i+o]=this.m[o];return this},i.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},i.prototype.multiplyToArray=function(t,i,o){var n=this.m[0],r=this.m[1],s=this.m[2],e=this.m[3],a=this.m[4],h=this.m[5],u=this.m[6],l=this.m[7],m=this.m[8],f=this.m[9],x=this.m[10],y=this.m[11],c=this.m[12],p=this.m[13],z=this.m[14],M=this.m[15],w=t.m[0],I=t.m[1],d=t.m[2],D=t.m[3],S=t.m[4],v=t.m[5],g=t.m[6],T=t.m[7],R=t.m[8],_=t.m[9],b=t.m[10],A=t.m[11],F=t.m[12],P=t.m[13],C=t.m[14],L=t.m[15];return i[o]=n*w+r*S+s*R+e*F,i[o+1]=n*I+r*v+s*_+e*P,i[o+2]=n*d+r*g+s*b+e*C,i[o+3]=n*D+r*T+s*A+e*L,i[o+4]=a*w+h*S+u*R+l*F,i[o+5]=a*I+h*v+u*_+l*P,i[o+6]=a*d+h*g+u*b+l*C,i[o+7]=a*D+h*T+u*A+l*L,i[o+8]=m*w+f*S+x*R+y*F,i[o+9]=m*I+f*v+x*_+y*P,i[o+10]=m*d+f*g+x*b+y*C,i[o+11]=m*D+f*T+x*A+y*L,i[o+12]=c*w+p*S+z*R+M*F,i[o+13]=c*I+p*v+z*_+M*P,i[o+14]=c*d+p*g+z*b+M*C,i[o+15]=c*D+p*T+z*A+M*L,this},i.prototype.multiplyToArraySIMD=function(t,i,o){void 0===o&&(o=0);var n=this.m,r=t.m,s=SIMD.float32x4.load(r,0),e=SIMD.float32x4.load(r,4),a=SIMD.float32x4.load(r,8),h=SIMD.float32x4.load(r,12),u=SIMD.float32x4.load(n,0);SIMD.float32x4.store(i,o+0,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(u,3,3,3,3),h)))));var l=SIMD.float32x4.load(n,4);SIMD.float32x4.store(i,o+4,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,3,3,3,3),h)))));var m=SIMD.float32x4.load(n,8);SIMD.float32x4.store(i,o+8,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(m,3,3,3,3),h)))));var f=SIMD.float32x4.load(n,12);SIMD.float32x4.store(i,o+12,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,0,0,0,0),s),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,1,1,1,1),e),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,2,2,2,2),a),SIMD.float32x4.mul(SIMD.float32x4.swizzle(f,3,3,3,3),h)))))},i.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},i.prototype.clone=function(){return i.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])},i.prototype.decompose=function(o,n,r){r.x=this.m[12],\nr.y=this.m[13],r.z=this.m[14];var s=t.Tools.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,a=t.Tools.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=t.Tools.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;if(o.x=s*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),o.y=a*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),o.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===o.x||0===o.y||0===o.z)return n.x=0,n.y=0,n.z=0,n.w=1,!1;var u=i.FromValues(this.m[0]/o.x,this.m[1]/o.x,this.m[2]/o.x,0,this.m[4]/o.y,this.m[5]/o.y,this.m[6]/o.y,0,this.m[8]/o.z,this.m[9]/o.z,this.m[10]/o.z,0,0,0,0,1);return e.FromRotationMatrixToRef(u,n),!0},i.FromArray=function(t,o){var n=new i;return o||(o=0),i.FromArrayToRef(t,o,n),n},i.FromArrayToRef=function(t,i,o){for(var n=0;16>n;n++)o.m[n]=t[n+i]},i.FromValuesToRef=function(t,i,o,n,r,s,e,a,h,u,l,m,f,x,y,c,p){p.m[0]=t,p.m[1]=i,p.m[2]=o,p.m[3]=n,p.m[4]=r,p.m[5]=s,p.m[6]=e,p.m[7]=a,p.m[8]=h,p.m[9]=u,p.m[10]=l,p.m[11]=m,p.m[12]=f,p.m[13]=x,p.m[14]=y,p.m[15]=c},i.FromValues=function(t,o,n,r,s,e,a,h,u,l,m,f,x,y,c,p){var z=new i;return z.m[0]=t,z.m[1]=o,z.m[2]=n,z.m[3]=r,z.m[4]=s,z.m[5]=e,z.m[6]=a,z.m[7]=h,z.m[8]=u,z.m[9]=l,z.m[10]=m,z.m[11]=f,z.m[12]=x,z.m[13]=y,z.m[14]=c,z.m[15]=p,z},i.Compose=function(t,o,n){var r=i.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),s=i.Identity();return o.toRotationMatrix(s),r=r.multiply(s),r.setTranslation(n),r},i.Identity=function(){return i.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},i.IdentityToRef=function(t){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},i.Zero=function(){return i.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},i.RotationX=function(t){var o=new i;return i.RotationXToRef(t,o),o},i.Invert=function(t){var o=new i;return t.invertToRef(o),o},i.RotationXToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=n,i.m[10]=n,i.m[9]=-o,i.m[6]=o,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationY=function(t){var o=new i;return i.RotationYToRef(t,o),o},i.RotationYToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=n,i.m[2]=-o,i.m[8]=o,i.m[10]=n,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationZ=function(t){var o=new i;return i.RotationZToRef(t,o),o},i.RotationZToRef=function(t,i){var o=Math.sin(t),n=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=n,i.m[1]=o,i.m[4]=-o,i.m[5]=n,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},i.RotationAxis=function(t,o){var n=Math.sin(-o),r=Math.cos(-o),s=1-r;t.normalize();var e=i.Zero();return e.m[0]=t.x*t.x*s+r,e.m[1]=t.x*t.y*s-t.z*n,e.m[2]=t.x*t.z*s+t.y*n,e.m[3]=0,e.m[4]=t.y*t.x*s+t.z*n,e.m[5]=t.y*t.y*s+r,e.m[6]=t.y*t.z*s-t.x*n,e.m[7]=0,e.m[8]=t.z*t.x*s-t.y*n,e.m[9]=t.z*t.y*s+t.x*n,e.m[10]=t.z*t.z*s+r,e.m[11]=0,e.m[15]=1,e},i.RotationYawPitchRoll=function(t,o,n){var r=new i;return i.RotationYawPitchRollToRef(t,o,n,r),r},i.RotationYawPitchRollToRef=function(t,i,o,n){e.RotationYawPitchRollToRef(t,i,o,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(n)},i.Scaling=function(t,o,n){var r=i.Zero();return i.ScalingToRef(t,o,n,r),r},i.ScalingToRef=function(t,i,o,n){n.m[0]=t,n.m[1]=0,n.m[2]=0,n.m[3]=0,n.m[4]=0,n.m[5]=i,n.m[6]=0,n.m[7]=0,n.m[8]=0,n.m[9]=0,n.m[10]=o,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},i.Translation=function(t,o,n){var r=i.Identity();return i.TranslationToRef(t,o,n,r),r},i.TranslationToRef=function(t,o,n,r){i.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,o,n,1,r)},i.LookAtLH=function(t,o,n){var r=i.Zero();return i.LookAtLHToRef(t,o,n,r),r},i.LookAtLHToRef=function(t,o,n,s){o.subtractToRef(t,this._zAxis),this._zAxis.normalize(),r.CrossToRef(n,this._zAxis,this._xAxis),this._xAxis.normalize(),r.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var e=-r.Dot(this._xAxis,t),a=-r.Dot(this._yAxis,t),h=-r.Dot(this._zAxis,t);return i.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,e,a,h,1,s)},i.LookAtLHToRefSIMD=function(t,i,o,n){var r=n.m,s=SIMD.float32x4(i.x,i.y,i.z,0),e=SIMD.float32x4(t.x,t.y,t.z,0),a=SIMD.float32x4(o.x,o.y,o.z,0),h=SIMD.float32x4.sub(s,e),u=SIMD.float32x4.mul(h,h);u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),h=SIMD.float32x4.mul(h,SIMD.float32x4.reciprocalSqrtApproximation(u)),u=SIMD.float32x4.mul(a,a),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),a=SIMD.float32x4.mul(a,SIMD.float32x4.reciprocalSqrtApproximation(u));var l=SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(h,1,2,0,3),SIMD.float32x4.swizzle(a,2,0,1,3)),SIMD.float32x4.mul(SIMD.float32x4.swizzle(h,2,0,1,3),SIMD.float32x4.swizzle(a,1,2,0,3)));u=SIMD.float32x4.mul(l,l),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),l=SIMD.float32x4.mul(l,SIMD.float32x4.reciprocalSqrtApproximation(u));var m=SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,1,2,0,3),SIMD.float32x4.swizzle(h,2,0,1,3)),SIMD.float32x4.mul(SIMD.float32x4.swizzle(l,2,0,1,3),SIMD.float32x4.swizzle(h,1,2,0,3)));u=SIMD.float32x4.mul(l,l),u=SIMD.float32x4.add(u,SIMD.float32x4.add(SIMD.float32x4.swizzle(u,1,2,0,3),SIMD.float32x4.swizzle(u,2,0,1,3))),l=SIMD.float32x4.mul(l,SIMD.float32x4.reciprocalSqrtApproximation(u));var f=SIMD.float32x4.splat(0);l=SIMD.float32x4.neg(l);var x=SIMD.float32x4.shuffle(l,m,0,1,4,5),y=SIMD.float32x4.shuffle(h,f,0,1,4,5),c=SIMD.float32x4.shuffle(x,y,0,2,4,6),p=SIMD.float32x4.shuffle(x,y,1,3,5,7);x=SIMD.float32x4.shuffle(l,m,2,3,6,7),y=SIMD.float32x4.shuffle(h,f,2,3,6,7);var z=SIMD.float32x4.shuffle(x,y,0,2,4,6),M=SIMD.float32x4(0,0,0,1),w=SIMD.float32x4(1,0,0,0),I=SIMD.float32x4(0,1,0,0),d=SIMD.float32x4(0,0,1,0),D=SIMD.float32x4.neg(e);D=SIMD.float32x4.withW(D,1),SIMD.float32x4.store(r,0,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(w,3,3,3,3),M))))),SIMD.float32x4.store(r,4,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(I,3,3,3,3),M))))),SIMD.float32x4.store(r,8,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(d,3,3,3,3),M))))),SIMD.float32x4.store(r,12,SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,0,0,0,0),c),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,1,1,1,1),p),SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,2,2,2,2),z),SIMD.float32x4.mul(SIMD.float32x4.swizzle(D,3,3,3,3),M)))))},i.OrthoLH=function(t,o,n,r){var s=i.Zero();return i.OrthoLHToRef(t,o,n,r,s),s},i.OrthoLHToRef=function(t,o,n,r,s){var e=2/t,a=2/o,h=1/(r-n),u=n/(n-r);i.FromValuesToRef(e,0,0,0,0,a,0,0,0,0,h,0,0,0,u,1,s)},i.OrthoOffCenterLH=function(t,o,n,r,s,e){var a=i.Zero();return i.OrthoOffCenterLHToRef(t,o,n,r,s,e,a),a},i.OrthoOffCenterLHToRef=function(t,i,o,n,r,s,e){e.m[0]=2/(i-t),e.m[1]=e.m[2]=e.m[3]=0,e.m[5]=2/(n-o),e.m[4]=e.m[6]=e.m[7]=0,e.m[10]=-1/(r-s),e.m[8]=e.m[9]=e.m[11]=0,e.m[12]=(t+i)/(t-i),e.m[13]=(n+o)/(o-n),e.m[14]=r/(r-s),e.m[15]=1},i.PerspectiveLH=function(t,o,n,r){var s=i.Zero();return s.m[0]=2*n/t,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=2*n/o,s.m[4]=s.m[6]=s.m[7]=0,s.m[10]=-r/(n-r),s.m[8]=s.m[9]=0,s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=n*r/(n-r),s},i.PerspectiveFovLH=function(t,o,n,r){var s=i.Zero();return i.PerspectiveFovLHToRef(t,o,n,r,s),s},i.PerspectiveFovLHToRef=function(i,o,n,r,s,e){void 0===e&&(e=t.Camera.FOVMODE_VERTICAL_FIXED);var a=1/Math.tan(.5*i),h=e===t.Camera.FOVMODE_VERTICAL_FIXED;s.m[0]=h?a/o:a,s.m[1]=s.m[2]=s.m[3]=0,s.m[5]=h?a:a*o,s.m[4]=s.m[6]=s.m[7]=0,s.m[8]=s.m[9]=0,s.m[10]=-r/(n-r),s.m[11]=1,s.m[12]=s.m[13]=s.m[15]=0,s.m[14]=n*r/(n-r)},i.GetFinalMatrix=function(t,o,n,r,s,e){var a=t.width,h=t.height,u=t.x,l=t.y,m=i.FromValues(a/2,0,0,0,0,-h/2,0,0,0,0,e-s,0,u+a/2,h/2+l,s,1);return o.multiply(n).multiply(r).multiply(m)},i.Transpose=function(t){var o=new i;return o.m[0]=t.m[0],o.m[1]=t.m[4],o.m[2]=t.m[8],o.m[3]=t.m[12],o.m[4]=t.m[1],o.m[5]=t.m[5],o.m[6]=t.m[9],o.m[7]=t.m[13],o.m[8]=t.m[2],o.m[9]=t.m[6],o.m[10]=t.m[10],o.m[11]=t.m[14],o.m[12]=t.m[3],o.m[13]=t.m[7],o.m[14]=t.m[11],o.m[15]=t.m[15],o},i.Reflection=function(t){var o=new i;return i.ReflectionToRef(t,o),o},i.ReflectionToRef=function(t,i){t.normalize();var o=t.normal.x,n=t.normal.y,r=t.normal.z,s=-2*o,e=-2*n,a=-2*r;i.m[0]=s*o+1,i.m[1]=e*o,i.m[2]=a*o,i.m[3]=0,i.m[4]=s*n,i.m[5]=e*n+1,i.m[6]=a*n,i.m[7]=0,i.m[8]=s*r,i.m[9]=e*r,i.m[10]=a*r+1,i.m[11]=0,i.m[12]=s*t.d,i.m[13]=e*t.d,i.m[14]=a*t.d,i.m[15]=1},i._tempQuaternion=new e,i._xAxis=r.Zero(),i._yAxis=r.Zero(),i._zAxis=r.Zero(),i}();t.Matrix=a;var h=function(){function t(t,i,o,n){this.normal=new r(t,i,o),this.d=n}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var o=a.Transpose(i),n=this.normal.x,r=this.normal.y,s=this.normal.z,e=this.d,h=n*o.m[0]+r*o.m[1]+s*o.m[2]+e*o.m[3],u=n*o.m[4]+r*o.m[5]+s*o.m[6]+e*o.m[7],l=n*o.m[8]+r*o.m[9]+s*o.m[10]+e*o.m[11],m=n*o.m[12]+r*o.m[13]+s*o.m[14]+e*o.m[15];return new t(h,u,l,m)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,o){var n,r=i.x-t.x,s=i.y-t.y,e=i.z-t.z,a=o.x-t.x,h=o.y-t.y,u=o.z-t.z,l=s*u-e*h,m=e*a-r*u,f=r*h-s*a,x=Math.sqrt(l*l+m*m+f*f);return n=0!==x?1/x:0,this.normal.x=l*n,this.normal.y=m*n,this.normal.z=f*n,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var o=r.Dot(this.normal,t);return i>=o},t.prototype.signedDistanceTo=function(t){return r.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,o,n){var r=new t(0,0,0,0);return r.copyFromPoints(i,o,n),r},t.FromPositionAndNormal=function(i,o){var n=new t(0,0,0,0);return o.normalize(),n.normal=o,n.d=-(o.x*i.x+o.y*i.y+o.z*i.z),n},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,o){var n=-(i.x*t.x+i.y*t.y+i.z*t.z);return r.Dot(o,i)+n},t}();t.Plane=h;var u=function(){function t(t,i,o,n){this.x=t,this.y=i,this.width=o,this.height=n}return t.prototype.toGlobal=function(i){var o=i.getRenderWidth(),n=i.getRenderHeight();return new t(this.x*o,this.y*n,this.width*o,this.height*n)},t}();t.Viewport=u;var l=function(){function t(){}return t.GetPlanes=function(i){for(var o=[],n=0;6>n;n++)o.push(new h(0,0,0,0));return t.GetPlanesToRef(i,o),o},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[10]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=l;var m=function(){function i(t,i,o){void 0===o&&(o=Number.MAX_VALUE),this.origin=t,this.direction=i,this.length=o}return i.prototype.intersectsBoxMinMax=function(t,i){var o=0,n=Number.MAX_VALUE;if(Math.abs(this.direction.x)<1e-7){if(this.origin.x<t.x||this.origin.x>i.x)return!1}else{var r=1/this.direction.x,s=(t.x-this.origin.x)*r,e=(i.x-this.origin.x)*r;if(e===-(1/0)&&(e=1/0),s>e){var a=s;s=e,e=a}if(o=Math.max(s,o),n=Math.min(e,n),o>n)return!1}if(Math.abs(this.direction.y)<1e-7){if(this.origin.y<t.y||this.origin.y>i.y)return!1}else if(r=1/this.direction.y,s=(t.y-this.origin.y)*r,e=(i.y-this.origin.y)*r,e===-(1/0)&&(e=1/0),s>e&&(a=s,s=e,e=a),o=Math.max(s,o),n=Math.min(e,n),o>n)return!1;if(Math.abs(this.direction.z)<1e-7){if(this.origin.z<t.z||this.origin.z>i.z)return!1}else if(r=1/this.direction.z,s=(t.z-this.origin.z)*r,e=(i.z-this.origin.z)*r,e===-(1/0)&&(e=1/0),s>e&&(a=s,s=e,e=a),o=Math.max(s,o),n=Math.min(e,n),o>n)return!1;return!0},i.prototype.intersectsBox=function(t){return this.intersectsBoxMinMax(t.minimum,t.maximum)},i.prototype.intersectsSphere=function(t){var i=t.center.x-this.origin.x,o=t.center.y-this.origin.y,n=t.center.z-this.origin.z,r=i*i+o*o+n*n,s=t.radius*t.radius;if(s>=r)return!0;var e=i*this.direction.x+o*this.direction.y+n*this.direction.z;if(0>e)return!1;var a=r-e*e;return s>=a},i.prototype.intersectsTriangle=function(i,o,n){this._edge1||(this._edge1=r.Zero(),this._edge2=r.Zero(),this._pvec=r.Zero(),this._tvec=r.Zero(),this._qvec=r.Zero()),o.subtractToRef(i,this._edge1),n.subtractToRef(i,this._edge2),r.CrossToRef(this.direction,this._edge2,this._pvec);var s=r.Dot(this._edge1,this._pvec);if(0===s)return null;var e=1/s;this.origin.subtractToRef(i,this._tvec);var a=r.Dot(this._tvec,this._pvec)*e;if(0>a||a>1)return null;r.CrossToRef(this._tvec,this._edge1,this._qvec);var h=r.Dot(this.direction,this._qvec)*e;if(0>h||a+h>1)return null;var u=r.Dot(this._edge2,this._qvec)*e;return u>this.length?null:new t.IntersectionInfo(a,h,u)},i.CreateNew=function(t,o,n,s,e,a,h){var u=r.Unproject(new r(t,o,0),n,s,e,a,h),l=r.Unproject(new r(t,o,1),n,s,e,a,h),m=l.subtract(u);return m.normalize(),new i(u,m)},i.CreateNewFromTo=function(t,o,n){void 0===n&&(n=a.Identity());var r=o.subtract(t),s=Math.sqrt(r.x*r.x+r.y*r.y+r.z*r.z);return r.normalize(),i.Transform(new i(t,r,s),n)},i.Transform=function(t,o){var n=r.TransformCoordinates(t.origin,o),s=r.TransformNormal(t.direction,o);return new i(n,s,t.length)},i}();t.Ray=m,function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(t.Space||(t.Space={}));var f=(t.Space,function(){function t(){}return t.X=new r(1,0,0),t.Y=new r(0,1,0),t.Z=new r(0,0,1),t}());t.Axis=f;var x=function(){function t(){}return t.interpolate=function(t,i,o,n,r){for(var s=1-3*n+3*i,e=3*n-6*i,a=3*i,h=t,u=0;5>u;u++){var l=h*h,m=l*h,f=s*m+e*l+a*h,x=1/(3*s*l+2*e*h+a);h-=(f-t)*x,h=Math.min(1,Math.max(0,h))}return 3*Math.pow(1-h,2)*h*o+3*(1-h)*Math.pow(h,2)*r+Math.pow(h,3)},t}();t.BezierCurve=x,function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(t.Orientation||(t.Orientation={}));var y=t.Orientation,c=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,o){var n=o.subtract(i),r=Math.atan2(n.y,n.x);return new t(r)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=c;var p=function(){function t(t,i,o){this.startPoint=t,this.midPoint=i,this.endPoint=o;var r=Math.pow(i.x,2)+Math.pow(i.y,2),s=(Math.pow(t.x,2)+Math.pow(t.y,2)-r)/2,e=(r-Math.pow(o.x,2)-Math.pow(o.y,2))/2,a=(t.x-i.x)*(i.y-o.y)-(i.x-o.x)*(t.y-i.y);this.centerPoint=new n((s*(i.y-o.y)-e*(t.y-i.y))/a,((t.x-i.x)*e-(i.x-o.x)*s)/a),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=c.BetweenTwoPoints(this.centerPoint,this.startPoint);var h=this.startAngle.degrees(),u=c.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),l=c.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-h>180&&(u-=360),-180>u-h&&(u+=360),l-u>180&&(l-=360),-180>l-u&&(l+=360),this.orientation=0>u-h?y.CW:y.CCW,this.angle=c.FromDegrees(this.orientation===y.CW?h-l:l-h)}return t}();t.Arc2=p;var z=function(){function t(t){this.path=t,this._onchange=new Array,this.value=0,this.animations=new Array}return t.prototype.getPoint=function(){var t=this.path.getPointAtLengthPosition(this.value);return new r(t.x,0,t.y)},t.prototype.moveAhead=function(t){return void 0===t&&(t=.002),this.move(t),this},t.prototype.moveBack=function(t){return void 0===t&&(t=.002),this.move(-t),this},t.prototype.move=function(t){if(Math.abs(t)>1)throw\"step size should be less than 1.\";return this.value+=t,this.ensureLimits(),this.raiseOnChange(),this},t.prototype.ensureLimits=function(){for(;this.value>1;)this.value-=1;for(;this.value<0;)this.value+=1;return this},t.prototype.markAsDirty=function(t){return this.ensureLimits(),this.raiseOnChange(),this},t.prototype.raiseOnChange=function(){var t=this;return this._onchange.forEach(function(i){return i(t)}),this},t.prototype.onchange=function(t){return this._onchange.push(t),this},t}();t.PathCursor=z;var M=function(){function i(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new n(t,i))}return i.prototype.addLineTo=function(i,o){if(closed)return t.Tools.Error(\"cannot add lines to closed paths\"),this;var r=new n(i,o),s=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(s).length(),this},i.prototype.addArcTo=function(i,o,r,s,e){if(void 0===e&&(e=36),closed)return t.Tools.Error(\"cannot add arcs to closed paths\"),this;var a=this._points[this._points.length-1],h=new n(i,o),u=new n(r,s),l=new p(a,h,u),m=l.angle.radians()/e;l.orientation===y.CW&&(m*=-1);for(var f=l.startAngle.radians()+m,x=0;e>x;x++){var c=Math.cos(f)*l.radius+l.centerPoint.x,z=Math.sin(f)*l.radius+l.centerPoint.y;this.addLineTo(c,z),f+=m}return this},i.prototype.close=function(){return this.closed=!0,this},i.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],o=this._points[0];t+=o.subtract(i).length()}return t},i.prototype.getPoints=function(){return this._points},i.prototype.getPointAtLengthPosition=function(i){if(0>i||i>1)return t.Tools.Error(\"normalized length position should be between 0 and 1.\"),n.Zero();for(var o=i*this.length(),r=0,s=0;s<this._points.length;s++){var e=(s+1)%this._points.length,a=this._points[s],h=this._points[e],u=h.subtract(a),l=u.length()+r;if(o>=r&&l>=o){var m=u.normalize(),f=o-r;return new n(a.x+m.x*f,a.y+m.y*f)}r=l}return t.Tools.Error(\"internal error\"),n.Zero()},i.StartingAt=function(t,o){return new i(t,o)},i}();t.Path2=M;var w=function(){function t(t,i){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var o=0;o<t.length;o++)this._curve[o]=t[o].clone();this._compute(i)}return t.prototype.getCurve=function(){return this._curve},t.prototype.getTangents=function(){return this._tangents},t.prototype.getNormals=function(){return this._normals},t.prototype.getBinormals=function(){return this._binormals},t.prototype.getDistances=function(){return this._distances},t.prototype.update=function(t,i){for(var o=0;o<t.length;o++)this._curve[o].x=t[o].x,this._curve[o].y=t[o].y,this._curve[o].z=t[o].z;return this._compute(i),this},t.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._tangents[i-1].normalize();var o=this._tangents[0],n=this._normalVector(this._curve[0],o,t);this._normals[0]=n,this._normals[0].normalize(),this._binormals[0]=r.Cross(o,this._normals[0]),this._binormals[0].normalize(),this._distances[0]=0;for(var s,e,a,h,u,l=1;i>l;l++)s=this._getLastNonNullVector(l),i-1>l&&(e=this._getFirstNonNullVector(l),this._tangents[l]=s.add(e),this._tangents[l].normalize()),this._distances[l]=this._distances[l-1]+s.length(),a=this._tangents[l],h=this._normals[l-1],u=this._binormals[l-1],this._normals[l]=r.Cross(u,a),this._normals[l].normalize(),this._binormals[l]=r.Cross(a,this._normals[l]),this._binormals[l].normalize()},t.prototype._getFirstNonNullVector=function(t){for(var i=1,o=this._curve[t+i].subtract(this._curve[t]);0==o.length()&&t+i+1<this._curve.length;)i++,o=this._curve[t+i].subtract(this._curve[t]);return o},t.prototype._getLastNonNullVector=function(t){for(var i=1,o=this._curve[t].subtract(this._curve[t-i]);0==o.length()&&t>i+1;)i++,o=this._curve[t].subtract(this._curve[t-i]);return o},t.prototype._normalVector=function(t,i,o){var n;if(void 0===o||null===o){var s;1!==i.y?s=new r(0,-1,0):1!==i.x?s=new r(1,0,0):1!==i.z&&(s=new r(0,0,1)),n=r.Cross(i,s)}else n=r.Cross(i,o),r.CrossToRef(n,i,n);return n.normalize(),n},t}();t.Path3D=w;var I=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,o,n,s){s=s>2?s:3;for(var e=new Array,a=function(t,i,o,n){var r=(1-t)*(1-t)*i+2*t*(1-t)*o+t*t*n;return r},h=0;s>=h;h++)e.push(new r(a(h/s,i.x,o.x,n.x),a(h/s,i.y,o.y,n.y),a(h/s,i.z,o.z,n.z)));return new t(e)},t.CreateCubicBezier=function(i,o,n,s,e){e=e>3?e:4;for(var a=new Array,h=function(t,i,o,n,r){var s=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*o+3*t*t*(1-t)*n+t*t*t*r;return s},u=0;e>=u;u++)a.push(new r(h(u/e,i.x,o.x,n.x,s.x),h(u/e,i.y,o.y,n.y,s.y),h(u/e,i.z,o.z,n.z,s.z)));return new t(a)},t.CreateHermiteSpline=function(i,o,n,s,e){for(var a=new Array,h=1/e,u=0;e>=u;u++)a.push(r.Hermite(i,o,n,s,u*h));return new t(a)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var o=this._points[this._points.length-1],n=this._points.slice(),r=i.getPoints(),s=1;s<r.length;s++)n.push(r[s].subtract(r[0]).add(o));var e=new t(n);return e},t.prototype._computeLength=function(t){for(var i=0,o=1;o<t.length;o++)i+=t[o].subtract(t[o-1]).length();return i},t}();t.Curve3=I;var d=function(){function t(t,i){void 0===t&&(t=r.Zero()),void 0===i&&(i=r.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=d;var D=function(){function t(t,i,o){void 0===t&&(t=r.Zero()),void 0===i&&(i=r.Up()),void 0===o&&(o=n.Zero()),this.position=t,this.normal=i,this.uv=o}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=D;var S=a.prototype.multiplyToArray,v=a.prototype.invertToRef,g=a.LookAtLHToRef,T=r.TransformCoordinatesToRef,R=r.TransformCoordinatesFromFloatsToRef,_=function(){function t(){}return Object.defineProperty(t,\"IsEnabled\",{get:function(){return t._isEnabled},enumerable:!0,configurable:!0}),t.DisableSIMD=function(){a.prototype.multiplyToArray=S,a.prototype.invertToRef=v,a.LookAtLHToRef=g,r.TransformCoordinatesToRef=T,r.TransformCoordinatesFromFloatsToRef=R,t._isEnabled=!1},t.EnableSIMD=function(){void 0!==window.SIMD&&(a.prototype.multiplyToArray=a.prototype.multiplyToArraySIMD,a.prototype.invertToRef=a.prototype.invertToRefSIMD,a.LookAtLHToRef=a.LookAtLHToRefSIMD,r.TransformCoordinatesToRef=r.TransformCoordinatesToRefSIMD,r.TransformCoordinatesFromFloatsToRef=r.TransformCoordinatesFromFloatsToRefSIMD,Object.defineProperty(r.prototype,\"x\",{get:function(){return this._data[0]},set:function(t){this._data||(this._data=new Float32Array(3)),this._data[0]=t}}),Object.defineProperty(r.prototype,\"y\",{get:function(){return this._data[1]},set:function(t){this._data[1]=t}}),Object.defineProperty(r.prototype,\"z\",{get:function(){return this._data[2]},set:function(t){this._data[2]=t}}),t._isEnabled=!0)},t._isEnabled=!1,t}();t.SIMDHelper=_,void 0!==window.SIMD&&window.SIMD.float32x4&&window.SIMD.float32x4.swizzle&&_.EnableSIMD()}(BABYLON||(BABYLON={}));";
  31744. if (window.module && module.exports) {
  31745. module.exports = BABYLON;
  31746. };