babylon.2.1.debug.js 1.6 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858
  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. })(BABYLON || (BABYLON = {}));
  3013. //# sourceMappingURL=babylon.math.js.map
  3014. var BABYLON;
  3015. (function (BABYLON) {
  3016. var Database = (function () {
  3017. function Database(urlToScene, callbackManifestChecked) {
  3018. // Handling various flavors of prefixed version of IndexedDB
  3019. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3020. this.callbackManifestChecked = callbackManifestChecked;
  3021. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3022. this.db = null;
  3023. this.enableSceneOffline = false;
  3024. this.enableTexturesOffline = false;
  3025. this.manifestVersionFound = 0;
  3026. this.mustUpdateRessources = false;
  3027. this.hasReachedQuota = false;
  3028. if (!Database.IDBStorageEnabled) {
  3029. this.callbackManifestChecked(true);
  3030. }
  3031. else {
  3032. this.checkManifestFile();
  3033. }
  3034. }
  3035. Database.prototype.checkManifestFile = function () {
  3036. var _this = this;
  3037. function noManifestFile() {
  3038. that.enableSceneOffline = false;
  3039. that.enableTexturesOffline = false;
  3040. that.callbackManifestChecked(false);
  3041. }
  3042. var that = this;
  3043. var manifestURL = this.currentSceneUrl + ".manifest";
  3044. var xhr = new XMLHttpRequest();
  3045. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3046. xhr.open("GET", manifestURLTimeStamped, true);
  3047. xhr.addEventListener("load", function () {
  3048. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3049. try {
  3050. var manifestFile = JSON.parse(xhr.response);
  3051. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3052. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3053. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3054. _this.manifestVersionFound = manifestFile.version;
  3055. }
  3056. if (_this.callbackManifestChecked) {
  3057. _this.callbackManifestChecked(true);
  3058. }
  3059. }
  3060. catch (ex) {
  3061. noManifestFile();
  3062. }
  3063. }
  3064. else {
  3065. noManifestFile();
  3066. }
  3067. }, false);
  3068. xhr.addEventListener("error", function (event) {
  3069. noManifestFile();
  3070. }, false);
  3071. try {
  3072. xhr.send();
  3073. }
  3074. catch (ex) {
  3075. BABYLON.Tools.Error("Error on XHR send request.");
  3076. that.callbackManifestChecked(false);
  3077. }
  3078. };
  3079. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3080. var _this = this;
  3081. function handleError() {
  3082. that.isSupported = false;
  3083. if (errorCallback)
  3084. errorCallback();
  3085. }
  3086. var that = this;
  3087. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3088. // Your browser doesn't support IndexedDB
  3089. this.isSupported = false;
  3090. if (errorCallback)
  3091. errorCallback();
  3092. }
  3093. else {
  3094. // If the DB hasn't been opened or created yet
  3095. if (!this.db) {
  3096. this.hasReachedQuota = false;
  3097. this.isSupported = true;
  3098. var request = this.idbFactory.open("babylonjs", 1);
  3099. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3100. request.onerror = function (event) {
  3101. handleError();
  3102. };
  3103. // executes when a version change transaction cannot complete due to other active transactions
  3104. request.onblocked = function (event) {
  3105. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3106. handleError();
  3107. };
  3108. // DB has been opened successfully
  3109. request.onsuccess = function (event) {
  3110. _this.db = request.result;
  3111. successCallback();
  3112. };
  3113. // Initialization of the DB. Creating Scenes & Textures stores
  3114. request.onupgradeneeded = function (event) {
  3115. _this.db = (event.target).result;
  3116. try {
  3117. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3118. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3119. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3120. }
  3121. catch (ex) {
  3122. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3123. handleError();
  3124. }
  3125. };
  3126. }
  3127. else {
  3128. if (successCallback)
  3129. successCallback();
  3130. }
  3131. }
  3132. };
  3133. Database.prototype.loadImageFromDB = function (url, image) {
  3134. var _this = this;
  3135. var completeURL = Database.ReturnFullUrlLocation(url);
  3136. var saveAndLoadImage = function () {
  3137. if (!_this.hasReachedQuota && _this.db !== null) {
  3138. // the texture is not yet in the DB, let's try to save it
  3139. _this._saveImageIntoDBAsync(completeURL, image);
  3140. }
  3141. else {
  3142. image.src = url;
  3143. }
  3144. };
  3145. if (!this.mustUpdateRessources) {
  3146. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3147. }
  3148. else {
  3149. saveAndLoadImage();
  3150. }
  3151. };
  3152. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3153. if (this.isSupported && this.db !== null) {
  3154. var texture;
  3155. var transaction = this.db.transaction(["textures"]);
  3156. transaction.onabort = function (event) {
  3157. image.src = url;
  3158. };
  3159. transaction.oncomplete = function (event) {
  3160. var blobTextureURL;
  3161. if (texture) {
  3162. var URL = window.URL || window.webkitURL;
  3163. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3164. image.onerror = function () {
  3165. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3166. image.src = url;
  3167. };
  3168. image.src = blobTextureURL;
  3169. }
  3170. else {
  3171. notInDBCallback();
  3172. }
  3173. };
  3174. var getRequest = transaction.objectStore("textures").get(url);
  3175. getRequest.onsuccess = function (event) {
  3176. texture = (event.target).result;
  3177. };
  3178. getRequest.onerror = function (event) {
  3179. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3180. image.src = url;
  3181. };
  3182. }
  3183. else {
  3184. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3185. image.src = url;
  3186. }
  3187. };
  3188. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3189. var _this = this;
  3190. if (this.isSupported) {
  3191. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3192. var generateBlobUrl = function () {
  3193. var blobTextureURL;
  3194. if (blob) {
  3195. var URL = window.URL || window.webkitURL;
  3196. try {
  3197. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3198. }
  3199. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3200. catch (ex) {
  3201. blobTextureURL = URL.createObjectURL(blob);
  3202. }
  3203. }
  3204. image.src = blobTextureURL;
  3205. };
  3206. if (Database.IsUASupportingBlobStorage) {
  3207. var xhr = new XMLHttpRequest(), blob;
  3208. xhr.open("GET", url, true);
  3209. xhr.responseType = "blob";
  3210. xhr.addEventListener("load", function () {
  3211. if (xhr.status === 200) {
  3212. // Blob as response (XHR2)
  3213. blob = xhr.response;
  3214. var transaction = _this.db.transaction(["textures"], "readwrite");
  3215. // the transaction could abort because of a QuotaExceededError error
  3216. transaction.onabort = function (event) {
  3217. try {
  3218. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3219. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3220. this.hasReachedQuota = true;
  3221. }
  3222. }
  3223. catch (ex) { }
  3224. generateBlobUrl();
  3225. };
  3226. transaction.oncomplete = function (event) {
  3227. generateBlobUrl();
  3228. };
  3229. var newTexture = { textureUrl: url, data: blob };
  3230. try {
  3231. // Put the blob into the dabase
  3232. var addRequest = transaction.objectStore("textures").put(newTexture);
  3233. addRequest.onsuccess = function (event) {
  3234. };
  3235. addRequest.onerror = function (event) {
  3236. generateBlobUrl();
  3237. };
  3238. }
  3239. catch (ex) {
  3240. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3241. if (ex.code === 25) {
  3242. Database.IsUASupportingBlobStorage = false;
  3243. }
  3244. image.src = url;
  3245. }
  3246. }
  3247. else {
  3248. image.src = url;
  3249. }
  3250. }, false);
  3251. xhr.addEventListener("error", function (event) {
  3252. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3253. image.src = url;
  3254. }, false);
  3255. xhr.send();
  3256. }
  3257. else {
  3258. image.src = url;
  3259. }
  3260. }
  3261. else {
  3262. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3263. image.src = url;
  3264. }
  3265. };
  3266. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3267. var _this = this;
  3268. var updateVersion = function (event) {
  3269. // the version is not yet in the DB or we need to update it
  3270. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3271. };
  3272. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3273. };
  3274. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3275. var _this = this;
  3276. if (this.isSupported) {
  3277. var version;
  3278. try {
  3279. var transaction = this.db.transaction(["versions"]);
  3280. transaction.oncomplete = function (event) {
  3281. if (version) {
  3282. // If the version in the JSON file is > than the version in DB
  3283. if (_this.manifestVersionFound > version.data) {
  3284. _this.mustUpdateRessources = true;
  3285. updateInDBCallback();
  3286. }
  3287. else {
  3288. callback(version.data);
  3289. }
  3290. }
  3291. else {
  3292. _this.mustUpdateRessources = true;
  3293. updateInDBCallback();
  3294. }
  3295. };
  3296. transaction.onabort = function (event) {
  3297. callback(-1);
  3298. };
  3299. var getRequest = transaction.objectStore("versions").get(url);
  3300. getRequest.onsuccess = function (event) {
  3301. version = (event.target).result;
  3302. };
  3303. getRequest.onerror = function (event) {
  3304. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3305. callback(-1);
  3306. };
  3307. }
  3308. catch (ex) {
  3309. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3310. callback(-1);
  3311. }
  3312. }
  3313. else {
  3314. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3315. callback(-1);
  3316. }
  3317. };
  3318. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3319. var _this = this;
  3320. if (this.isSupported && !this.hasReachedQuota) {
  3321. try {
  3322. // Open a transaction to the database
  3323. var transaction = this.db.transaction(["versions"], "readwrite");
  3324. // the transaction could abort because of a QuotaExceededError error
  3325. transaction.onabort = function (event) {
  3326. try {
  3327. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3328. _this.hasReachedQuota = true;
  3329. }
  3330. }
  3331. catch (ex) { }
  3332. callback(-1);
  3333. };
  3334. transaction.oncomplete = function (event) {
  3335. callback(_this.manifestVersionFound);
  3336. };
  3337. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3338. // Put the scene into the database
  3339. var addRequest = transaction.objectStore("versions").put(newVersion);
  3340. addRequest.onsuccess = function (event) {
  3341. };
  3342. addRequest.onerror = function (event) {
  3343. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3344. };
  3345. }
  3346. catch (ex) {
  3347. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3348. callback(-1);
  3349. }
  3350. }
  3351. else {
  3352. callback(-1);
  3353. }
  3354. };
  3355. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3356. var _this = this;
  3357. var completeUrl = Database.ReturnFullUrlLocation(url);
  3358. var saveAndLoadFile = function (event) {
  3359. // the scene is not yet in the DB, let's try to save it
  3360. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3361. };
  3362. this._checkVersionFromDB(completeUrl, function (version) {
  3363. if (version !== -1) {
  3364. if (!_this.mustUpdateRessources) {
  3365. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3366. }
  3367. else {
  3368. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3369. }
  3370. }
  3371. else {
  3372. errorCallback();
  3373. }
  3374. });
  3375. };
  3376. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3377. if (this.isSupported) {
  3378. var targetStore;
  3379. if (url.indexOf(".babylon") !== -1) {
  3380. targetStore = "scenes";
  3381. }
  3382. else {
  3383. targetStore = "textures";
  3384. }
  3385. var file;
  3386. var transaction = this.db.transaction([targetStore]);
  3387. transaction.oncomplete = function (event) {
  3388. if (file) {
  3389. callback(file.data);
  3390. }
  3391. else {
  3392. notInDBCallback();
  3393. }
  3394. };
  3395. transaction.onabort = function (event) {
  3396. notInDBCallback();
  3397. };
  3398. var getRequest = transaction.objectStore(targetStore).get(url);
  3399. getRequest.onsuccess = function (event) {
  3400. file = (event.target).result;
  3401. };
  3402. getRequest.onerror = function (event) {
  3403. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3404. notInDBCallback();
  3405. };
  3406. }
  3407. else {
  3408. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3409. callback();
  3410. }
  3411. };
  3412. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3413. var _this = this;
  3414. if (this.isSupported) {
  3415. var targetStore;
  3416. if (url.indexOf(".babylon") !== -1) {
  3417. targetStore = "scenes";
  3418. }
  3419. else {
  3420. targetStore = "textures";
  3421. }
  3422. // Create XHR
  3423. var xhr = new XMLHttpRequest(), fileData;
  3424. xhr.open("GET", url, true);
  3425. if (useArrayBuffer) {
  3426. xhr.responseType = "arraybuffer";
  3427. }
  3428. xhr.onprogress = progressCallback;
  3429. xhr.addEventListener("load", function () {
  3430. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3431. // Blob as response (XHR2)
  3432. //fileData = xhr.responseText;
  3433. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3434. if (!_this.hasReachedQuota) {
  3435. // Open a transaction to the database
  3436. var transaction = _this.db.transaction([targetStore], "readwrite");
  3437. // the transaction could abort because of a QuotaExceededError error
  3438. transaction.onabort = function (event) {
  3439. try {
  3440. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3441. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3442. this.hasReachedQuota = true;
  3443. }
  3444. }
  3445. catch (ex) { }
  3446. callback(fileData);
  3447. };
  3448. transaction.oncomplete = function (event) {
  3449. callback(fileData);
  3450. };
  3451. var newFile;
  3452. if (targetStore === "scenes") {
  3453. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  3454. }
  3455. else {
  3456. newFile = { textureUrl: url, data: fileData };
  3457. }
  3458. try {
  3459. // Put the scene into the database
  3460. var addRequest = transaction.objectStore(targetStore).put(newFile);
  3461. addRequest.onsuccess = function (event) {
  3462. };
  3463. addRequest.onerror = function (event) {
  3464. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  3465. };
  3466. }
  3467. catch (ex) {
  3468. callback(fileData);
  3469. }
  3470. }
  3471. else {
  3472. callback(fileData);
  3473. }
  3474. }
  3475. else {
  3476. callback();
  3477. }
  3478. }, false);
  3479. xhr.addEventListener("error", function (event) {
  3480. BABYLON.Tools.Error("error on XHR request.");
  3481. callback();
  3482. }, false);
  3483. xhr.send();
  3484. }
  3485. else {
  3486. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3487. callback();
  3488. }
  3489. };
  3490. Database.IsUASupportingBlobStorage = true;
  3491. Database.IDBStorageEnabled = true;
  3492. Database.parseURL = function (url) {
  3493. var a = document.createElement('a');
  3494. a.href = url;
  3495. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  3496. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  3497. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  3498. return absLocation;
  3499. };
  3500. Database.ReturnFullUrlLocation = function (url) {
  3501. if (url.indexOf("http:/") === -1) {
  3502. return (Database.parseURL(window.location.href) + url);
  3503. }
  3504. else {
  3505. return url;
  3506. }
  3507. };
  3508. return Database;
  3509. })();
  3510. BABYLON.Database = Database;
  3511. })(BABYLON || (BABYLON = {}));
  3512. //# sourceMappingURL=babylon.database.js.map
  3513. var BABYLON;
  3514. (function (BABYLON) {
  3515. var Internals;
  3516. (function (Internals) {
  3517. /*
  3518. * Based on jsTGALoader - Javascript loader for TGA file
  3519. * By Vincent Thibault
  3520. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  3521. */
  3522. var TGATools = (function () {
  3523. function TGATools() {
  3524. }
  3525. TGATools.GetTGAHeader = function (data) {
  3526. var offset = 0;
  3527. var header = {
  3528. id_length: data[offset++],
  3529. colormap_type: data[offset++],
  3530. image_type: data[offset++],
  3531. colormap_index: data[offset++] | data[offset++] << 8,
  3532. colormap_length: data[offset++] | data[offset++] << 8,
  3533. colormap_size: data[offset++],
  3534. origin: [
  3535. data[offset++] | data[offset++] << 8,
  3536. data[offset++] | data[offset++] << 8
  3537. ],
  3538. width: data[offset++] | data[offset++] << 8,
  3539. height: data[offset++] | data[offset++] << 8,
  3540. pixel_size: data[offset++],
  3541. flags: data[offset++]
  3542. };
  3543. return header;
  3544. };
  3545. TGATools.UploadContent = function (gl, data) {
  3546. // Not enough data to contain header ?
  3547. if (data.length < 19) {
  3548. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  3549. return;
  3550. }
  3551. // Read Header
  3552. var offset = 18;
  3553. var header = TGATools.GetTGAHeader(data);
  3554. // Assume it's a valid Targa file.
  3555. if (header.id_length + offset > data.length) {
  3556. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  3557. return;
  3558. }
  3559. // Skip not needed data
  3560. offset += header.id_length;
  3561. var use_rle = false;
  3562. var use_pal = false;
  3563. var use_rgb = false;
  3564. var use_grey = false;
  3565. // Get some informations.
  3566. switch (header.image_type) {
  3567. case TGATools._TYPE_RLE_INDEXED:
  3568. use_rle = true;
  3569. case TGATools._TYPE_INDEXED:
  3570. use_pal = true;
  3571. break;
  3572. case TGATools._TYPE_RLE_RGB:
  3573. use_rle = true;
  3574. case TGATools._TYPE_RGB:
  3575. use_rgb = true;
  3576. break;
  3577. case TGATools._TYPE_RLE_GREY:
  3578. use_rle = true;
  3579. case TGATools._TYPE_GREY:
  3580. use_grey = true;
  3581. break;
  3582. }
  3583. var pixel_data;
  3584. var numAlphaBits = header.flags & 0xf;
  3585. var pixel_size = header.pixel_size >> 3;
  3586. var pixel_total = header.width * header.height * pixel_size;
  3587. // Read palettes
  3588. var palettes;
  3589. if (use_pal) {
  3590. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  3591. }
  3592. // Read LRE
  3593. if (use_rle) {
  3594. pixel_data = new Uint8Array(pixel_total);
  3595. var c, count, i;
  3596. var localOffset = 0;
  3597. var pixels = new Uint8Array(pixel_size);
  3598. while (offset < pixel_total && localOffset < pixel_total) {
  3599. c = data[offset++];
  3600. count = (c & 0x7f) + 1;
  3601. // RLE pixels
  3602. if (c & 0x80) {
  3603. // Bind pixel tmp array
  3604. for (i = 0; i < pixel_size; ++i) {
  3605. pixels[i] = data[offset++];
  3606. }
  3607. // Copy pixel array
  3608. for (i = 0; i < count; ++i) {
  3609. pixel_data.set(pixels, localOffset + i * pixel_size);
  3610. }
  3611. localOffset += pixel_size * count;
  3612. }
  3613. else {
  3614. count *= pixel_size;
  3615. for (i = 0; i < count; ++i) {
  3616. pixel_data[localOffset + i] = data[offset++];
  3617. }
  3618. localOffset += count;
  3619. }
  3620. }
  3621. }
  3622. else {
  3623. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  3624. }
  3625. // Load to texture
  3626. var x_start, y_start, x_step, y_step, y_end, x_end;
  3627. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  3628. default:
  3629. case TGATools._ORIGIN_UL:
  3630. x_start = 0;
  3631. x_step = 1;
  3632. x_end = header.width;
  3633. y_start = 0;
  3634. y_step = 1;
  3635. y_end = header.height;
  3636. break;
  3637. case TGATools._ORIGIN_BL:
  3638. x_start = 0;
  3639. x_step = 1;
  3640. x_end = header.width;
  3641. y_start = header.height - 1;
  3642. y_step = -1;
  3643. y_end = -1;
  3644. break;
  3645. case TGATools._ORIGIN_UR:
  3646. x_start = header.width - 1;
  3647. x_step = -1;
  3648. x_end = -1;
  3649. y_start = 0;
  3650. y_step = 1;
  3651. y_end = header.height;
  3652. break;
  3653. case TGATools._ORIGIN_BR:
  3654. x_start = header.width - 1;
  3655. x_step = -1;
  3656. x_end = -1;
  3657. y_start = header.height - 1;
  3658. y_step = -1;
  3659. y_end = -1;
  3660. break;
  3661. }
  3662. // Load the specify method
  3663. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  3664. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  3665. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  3666. };
  3667. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3668. var image = pixel_data, colormap = palettes;
  3669. var width = header.width, height = header.height;
  3670. var color, i = 0, x, y;
  3671. var imageData = new Uint8Array(width * height * 4);
  3672. for (y = y_start; y !== y_end; y += y_step) {
  3673. for (x = x_start; x !== x_end; x += x_step, i++) {
  3674. color = image[i];
  3675. imageData[(x + width * y) * 4 + 3] = 255;
  3676. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  3677. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  3678. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  3679. }
  3680. }
  3681. return imageData;
  3682. };
  3683. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3684. var image = pixel_data;
  3685. var width = header.width, height = header.height;
  3686. var color, i = 0, x, y;
  3687. var imageData = new Uint8Array(width * height * 4);
  3688. for (y = y_start; y !== y_end; y += y_step) {
  3689. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3690. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  3691. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  3692. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  3693. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  3694. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  3695. }
  3696. }
  3697. return imageData;
  3698. };
  3699. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3700. var image = pixel_data;
  3701. var width = header.width, height = header.height;
  3702. var i = 0, x, y;
  3703. var imageData = new Uint8Array(width * height * 4);
  3704. for (y = y_start; y !== y_end; y += y_step) {
  3705. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  3706. imageData[(x + width * y) * 4 + 3] = 255;
  3707. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3708. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3709. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3710. }
  3711. }
  3712. return imageData;
  3713. };
  3714. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3715. var image = pixel_data;
  3716. var width = header.width, height = header.height;
  3717. var i = 0, x, y;
  3718. var imageData = new Uint8Array(width * height * 4);
  3719. for (y = y_start; y !== y_end; y += y_step) {
  3720. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  3721. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3722. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  3723. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  3724. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  3725. }
  3726. }
  3727. return imageData;
  3728. };
  3729. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3730. var image = pixel_data;
  3731. var width = header.width, height = header.height;
  3732. var color, i = 0, x, y;
  3733. var imageData = new Uint8Array(width * height * 4);
  3734. for (y = y_start; y !== y_end; y += y_step) {
  3735. for (x = x_start; x !== x_end; x += x_step, i++) {
  3736. color = image[i];
  3737. imageData[(x + width * y) * 4 + 0] = color;
  3738. imageData[(x + width * y) * 4 + 1] = color;
  3739. imageData[(x + width * y) * 4 + 2] = color;
  3740. imageData[(x + width * y) * 4 + 3] = 255;
  3741. }
  3742. }
  3743. return imageData;
  3744. };
  3745. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  3746. var image = pixel_data;
  3747. var width = header.width, height = header.height;
  3748. var i = 0, x, y;
  3749. var imageData = new Uint8Array(width * height * 4);
  3750. for (y = y_start; y !== y_end; y += y_step) {
  3751. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  3752. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  3753. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  3754. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  3755. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  3756. }
  3757. }
  3758. return imageData;
  3759. };
  3760. TGATools._TYPE_NO_DATA = 0;
  3761. TGATools._TYPE_INDEXED = 1;
  3762. TGATools._TYPE_RGB = 2;
  3763. TGATools._TYPE_GREY = 3;
  3764. TGATools._TYPE_RLE_INDEXED = 9;
  3765. TGATools._TYPE_RLE_RGB = 10;
  3766. TGATools._TYPE_RLE_GREY = 11;
  3767. TGATools._ORIGIN_MASK = 0x30;
  3768. TGATools._ORIGIN_SHIFT = 0x04;
  3769. TGATools._ORIGIN_BL = 0x00;
  3770. TGATools._ORIGIN_BR = 0x01;
  3771. TGATools._ORIGIN_UL = 0x02;
  3772. TGATools._ORIGIN_UR = 0x03;
  3773. return TGATools;
  3774. })();
  3775. Internals.TGATools = TGATools;
  3776. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3777. })(BABYLON || (BABYLON = {}));
  3778. //# sourceMappingURL=babylon.tools.tga.js.map
  3779. var BABYLON;
  3780. (function (BABYLON) {
  3781. var Internals;
  3782. (function (Internals) {
  3783. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  3784. // All values and structures referenced from:
  3785. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  3786. var DDS_MAGIC = 0x20534444;
  3787. 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;
  3788. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  3789. 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;
  3790. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  3791. function FourCCToInt32(value) {
  3792. return value.charCodeAt(0) +
  3793. (value.charCodeAt(1) << 8) +
  3794. (value.charCodeAt(2) << 16) +
  3795. (value.charCodeAt(3) << 24);
  3796. }
  3797. function Int32ToFourCC(value) {
  3798. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  3799. }
  3800. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  3801. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  3802. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  3803. var headerLengthInt = 31; // The header length in 32 bit ints
  3804. // Offsets into the header array
  3805. var off_magic = 0;
  3806. var off_size = 1;
  3807. var off_flags = 2;
  3808. var off_height = 3;
  3809. var off_width = 4;
  3810. var off_mipmapCount = 7;
  3811. var off_pfFlags = 20;
  3812. var off_pfFourCC = 21;
  3813. var off_RGBbpp = 22;
  3814. var off_RMask = 23;
  3815. var off_GMask = 24;
  3816. var off_BMask = 25;
  3817. var off_AMask = 26;
  3818. var off_caps1 = 27;
  3819. var off_caps2 = 28;
  3820. ;
  3821. var DDSTools = (function () {
  3822. function DDSTools() {
  3823. }
  3824. DDSTools.GetDDSInfo = function (arrayBuffer) {
  3825. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  3826. var mipmapCount = 1;
  3827. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  3828. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3829. }
  3830. return {
  3831. width: header[off_width],
  3832. height: header[off_height],
  3833. mipmapCount: mipmapCount,
  3834. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  3835. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  3836. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  3837. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  3838. };
  3839. };
  3840. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3841. var byteArray = new Uint8Array(dataLength);
  3842. var srcData = new Uint8Array(arrayBuffer);
  3843. var index = 0;
  3844. for (var y = height - 1; y >= 0; y--) {
  3845. for (var x = 0; x < width; x++) {
  3846. var srcPos = dataOffset + (x + y * width) * 4;
  3847. byteArray[index + 2] = srcData[srcPos];
  3848. byteArray[index + 1] = srcData[srcPos + 1];
  3849. byteArray[index] = srcData[srcPos + 2];
  3850. byteArray[index + 3] = srcData[srcPos + 3];
  3851. index += 4;
  3852. }
  3853. }
  3854. return byteArray;
  3855. };
  3856. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3857. var byteArray = new Uint8Array(dataLength);
  3858. var srcData = new Uint8Array(arrayBuffer);
  3859. var index = 0;
  3860. for (var y = height - 1; y >= 0; y--) {
  3861. for (var x = 0; x < width; x++) {
  3862. var srcPos = dataOffset + (x + y * width) * 3;
  3863. byteArray[index + 2] = srcData[srcPos];
  3864. byteArray[index + 1] = srcData[srcPos + 1];
  3865. byteArray[index] = srcData[srcPos + 2];
  3866. index += 3;
  3867. }
  3868. }
  3869. return byteArray;
  3870. };
  3871. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  3872. var byteArray = new Uint8Array(dataLength);
  3873. var srcData = new Uint8Array(arrayBuffer);
  3874. var index = 0;
  3875. for (var y = height - 1; y >= 0; y--) {
  3876. for (var x = 0; x < width; x++) {
  3877. var srcPos = dataOffset + (x + y * width);
  3878. byteArray[index] = srcData[srcPos];
  3879. index++;
  3880. }
  3881. }
  3882. return byteArray;
  3883. };
  3884. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  3885. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  3886. if (header[off_magic] != DDS_MAGIC) {
  3887. BABYLON.Tools.Error("Invalid magic number in DDS header");
  3888. return;
  3889. }
  3890. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  3891. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  3892. return;
  3893. }
  3894. if (info.isFourCC) {
  3895. fourCC = header[off_pfFourCC];
  3896. switch (fourCC) {
  3897. case FOURCC_DXT1:
  3898. blockBytes = 8;
  3899. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  3900. break;
  3901. case FOURCC_DXT3:
  3902. blockBytes = 16;
  3903. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  3904. break;
  3905. case FOURCC_DXT5:
  3906. blockBytes = 16;
  3907. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  3908. break;
  3909. default:
  3910. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  3911. return;
  3912. }
  3913. }
  3914. mipmapCount = 1;
  3915. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  3916. mipmapCount = Math.max(1, header[off_mipmapCount]);
  3917. }
  3918. var bpp = header[off_RGBbpp];
  3919. for (var face = 0; face < faces; face++) {
  3920. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  3921. width = header[off_width];
  3922. height = header[off_height];
  3923. dataOffset = header[off_size] + 4;
  3924. for (i = 0; i < mipmapCount; ++i) {
  3925. if (info.isRGB) {
  3926. if (bpp == 24) {
  3927. dataLength = width * height * 3;
  3928. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3929. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  3930. }
  3931. else {
  3932. dataLength = width * height * 4;
  3933. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3934. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  3935. }
  3936. }
  3937. else if (info.isLuminance) {
  3938. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  3939. var unpaddedRowSize = width;
  3940. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  3941. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  3942. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  3943. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  3944. }
  3945. else {
  3946. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  3947. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  3948. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  3949. }
  3950. dataOffset += dataLength;
  3951. width *= 0.5;
  3952. height *= 0.5;
  3953. width = Math.max(1.0, width);
  3954. height = Math.max(1.0, height);
  3955. }
  3956. }
  3957. };
  3958. return DDSTools;
  3959. })();
  3960. Internals.DDSTools = DDSTools;
  3961. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  3962. })(BABYLON || (BABYLON = {}));
  3963. //# sourceMappingURL=babylon.tools.dds.js.map
  3964. var BABYLON;
  3965. (function (BABYLON) {
  3966. var SmartArray = (function () {
  3967. function SmartArray(capacity) {
  3968. this.length = 0;
  3969. this._duplicateId = 0;
  3970. this.data = new Array(capacity);
  3971. this._id = SmartArray._GlobalId++;
  3972. }
  3973. SmartArray.prototype.push = function (value) {
  3974. this.data[this.length++] = value;
  3975. if (this.length > this.data.length) {
  3976. this.data.length *= 2;
  3977. }
  3978. if (!value.__smartArrayFlags) {
  3979. value.__smartArrayFlags = {};
  3980. }
  3981. value.__smartArrayFlags[this._id] = this._duplicateId;
  3982. };
  3983. SmartArray.prototype.pushNoDuplicate = function (value) {
  3984. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  3985. return;
  3986. }
  3987. this.push(value);
  3988. };
  3989. SmartArray.prototype.sort = function (compareFn) {
  3990. this.data.sort(compareFn);
  3991. };
  3992. SmartArray.prototype.reset = function () {
  3993. this.length = 0;
  3994. this._duplicateId++;
  3995. };
  3996. SmartArray.prototype.concat = function (array) {
  3997. if (array.length === 0) {
  3998. return;
  3999. }
  4000. if (this.length + array.length > this.data.length) {
  4001. this.data.length = (this.length + array.length) * 2;
  4002. }
  4003. for (var index = 0; index < array.length; index++) {
  4004. this.data[this.length++] = (array.data || array)[index];
  4005. }
  4006. };
  4007. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4008. if (array.length === 0) {
  4009. return;
  4010. }
  4011. if (this.length + array.length > this.data.length) {
  4012. this.data.length = (this.length + array.length) * 2;
  4013. }
  4014. for (var index = 0; index < array.length; index++) {
  4015. var item = (array.data || array)[index];
  4016. this.pushNoDuplicate(item);
  4017. }
  4018. };
  4019. SmartArray.prototype.indexOf = function (value) {
  4020. var position = this.data.indexOf(value);
  4021. if (position >= this.length) {
  4022. return -1;
  4023. }
  4024. return position;
  4025. };
  4026. // Statics
  4027. SmartArray._GlobalId = 0;
  4028. return SmartArray;
  4029. })();
  4030. BABYLON.SmartArray = SmartArray;
  4031. })(BABYLON || (BABYLON = {}));
  4032. //# sourceMappingURL=babylon.smartArray.js.map
  4033. var BABYLON;
  4034. (function (BABYLON) {
  4035. var SmartCollection = (function () {
  4036. function SmartCollection(capacity) {
  4037. if (capacity === void 0) { capacity = 10; }
  4038. this.count = 0;
  4039. this._initialCapacity = capacity;
  4040. this.items = {};
  4041. this._keys = new Array(this._initialCapacity);
  4042. }
  4043. SmartCollection.prototype.add = function (key, item) {
  4044. if (this.items[key] != undefined) {
  4045. return -1;
  4046. }
  4047. this.items[key] = item;
  4048. //literal keys are always strings, but we keep source type of key in _keys array
  4049. this._keys[this.count++] = key;
  4050. if (this.count > this._keys.length) {
  4051. this._keys.length *= 2;
  4052. }
  4053. return this.count;
  4054. };
  4055. SmartCollection.prototype.remove = function (key) {
  4056. if (this.items[key] == undefined) {
  4057. return -1;
  4058. }
  4059. return this.removeItemOfIndex(this.indexOf(key));
  4060. };
  4061. SmartCollection.prototype.removeItemOfIndex = function (index) {
  4062. if (index < this.count && index > -1) {
  4063. delete this.items[this._keys[index]];
  4064. //here, shifting by hand is better optimised than .splice
  4065. while (index < this.count) {
  4066. this._keys[index] = this._keys[index + 1];
  4067. index++;
  4068. }
  4069. }
  4070. else {
  4071. return -1;
  4072. }
  4073. return --this.count;
  4074. };
  4075. SmartCollection.prototype.indexOf = function (key) {
  4076. for (var i = 0; i !== this.count; i++) {
  4077. if (this._keys[i] === key) {
  4078. return i;
  4079. }
  4080. }
  4081. return -1;
  4082. };
  4083. SmartCollection.prototype.item = function (key) {
  4084. return this.items[key];
  4085. };
  4086. SmartCollection.prototype.getAllKeys = function () {
  4087. if (this.count > 0) {
  4088. var keys = new Array(this.count);
  4089. for (var i = 0; i < this.count; i++) {
  4090. keys[i] = this._keys[i];
  4091. }
  4092. return keys;
  4093. }
  4094. else {
  4095. return undefined;
  4096. }
  4097. };
  4098. SmartCollection.prototype.getKeyByIndex = function (index) {
  4099. if (index < this.count && index > -1) {
  4100. return this._keys[index];
  4101. }
  4102. else {
  4103. return undefined;
  4104. }
  4105. };
  4106. SmartCollection.prototype.getItemByIndex = function (index) {
  4107. if (index < this.count && index > -1) {
  4108. return this.items[this._keys[index]];
  4109. }
  4110. else {
  4111. return undefined;
  4112. }
  4113. };
  4114. SmartCollection.prototype.empty = function () {
  4115. if (this.count > 0) {
  4116. this.count = 0;
  4117. this.items = {};
  4118. this._keys = new Array(this._initialCapacity);
  4119. }
  4120. };
  4121. SmartCollection.prototype.forEach = function (block) {
  4122. var key;
  4123. for (key in this.items) {
  4124. if (this.items.hasOwnProperty(key)) {
  4125. block(this.items[key]);
  4126. }
  4127. }
  4128. };
  4129. return SmartCollection;
  4130. })();
  4131. BABYLON.SmartCollection = SmartCollection;
  4132. })(BABYLON || (BABYLON = {}));
  4133. //# sourceMappingURL=babylon.smartCollection.js.map
  4134. var BABYLON;
  4135. (function (BABYLON) {
  4136. // Screenshots
  4137. var screenshotCanvas;
  4138. var cloneValue = function (source, destinationObject) {
  4139. if (!source)
  4140. return null;
  4141. if (source instanceof BABYLON.Mesh) {
  4142. return null;
  4143. }
  4144. if (source instanceof BABYLON.SubMesh) {
  4145. return source.clone(destinationObject);
  4146. }
  4147. else if (source.clone) {
  4148. return source.clone();
  4149. }
  4150. return null;
  4151. };
  4152. var Tools = (function () {
  4153. function Tools() {
  4154. }
  4155. Tools.SetImmediate = function (action) {
  4156. if (window.setImmediate) {
  4157. window.setImmediate(action);
  4158. }
  4159. else {
  4160. setTimeout(action, 1);
  4161. }
  4162. };
  4163. Tools.IsExponantOfTwo = function (value) {
  4164. var count = 1;
  4165. do {
  4166. count *= 2;
  4167. } while (count < value);
  4168. return count === value;
  4169. };
  4170. Tools.GetExponantOfTwo = function (value, max) {
  4171. var count = 1;
  4172. do {
  4173. count *= 2;
  4174. } while (count < value);
  4175. if (count > max)
  4176. count = max;
  4177. return count;
  4178. };
  4179. Tools.GetFilename = function (path) {
  4180. var index = path.lastIndexOf("/");
  4181. if (index < 0)
  4182. return path;
  4183. return path.substring(index + 1);
  4184. };
  4185. Tools.GetDOMTextContent = function (element) {
  4186. var result = "";
  4187. var child = element.firstChild;
  4188. while (child) {
  4189. if (child.nodeType === 3) {
  4190. result += child.textContent;
  4191. }
  4192. child = child.nextSibling;
  4193. }
  4194. return result;
  4195. };
  4196. Tools.ToDegrees = function (angle) {
  4197. return angle * 180 / Math.PI;
  4198. };
  4199. Tools.ToRadians = function (angle) {
  4200. return angle * Math.PI / 180;
  4201. };
  4202. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  4203. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4204. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4205. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4206. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4207. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4208. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4209. }
  4210. return {
  4211. minimum: minimum,
  4212. maximum: maximum
  4213. };
  4214. };
  4215. Tools.ExtractMinAndMax = function (positions, start, count) {
  4216. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4217. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4218. for (var index = start; index < start + count; index++) {
  4219. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  4220. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4221. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4222. }
  4223. return {
  4224. minimum: minimum,
  4225. maximum: maximum
  4226. };
  4227. };
  4228. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4229. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4230. return undefined;
  4231. return Array.isArray(obj) ? obj : [obj];
  4232. };
  4233. // Misc.
  4234. Tools.GetPointerPrefix = function () {
  4235. var eventPrefix = "pointer";
  4236. // Check if hand.js is referenced or if the browser natively supports pointer events
  4237. if (!navigator.pointerEnabled) {
  4238. eventPrefix = "mouse";
  4239. }
  4240. return eventPrefix;
  4241. };
  4242. Tools.QueueNewFrame = function (func) {
  4243. if (window.requestAnimationFrame)
  4244. window.requestAnimationFrame(func);
  4245. else if (window.msRequestAnimationFrame)
  4246. window.msRequestAnimationFrame(func);
  4247. else if (window.webkitRequestAnimationFrame)
  4248. window.webkitRequestAnimationFrame(func);
  4249. else if (window.mozRequestAnimationFrame)
  4250. window.mozRequestAnimationFrame(func);
  4251. else if (window.oRequestAnimationFrame)
  4252. window.oRequestAnimationFrame(func);
  4253. else {
  4254. window.setTimeout(func, 16);
  4255. }
  4256. };
  4257. Tools.RequestFullscreen = function (element) {
  4258. if (element.requestFullscreen)
  4259. element.requestFullscreen();
  4260. else if (element.msRequestFullscreen)
  4261. element.msRequestFullscreen();
  4262. else if (element.webkitRequestFullscreen)
  4263. element.webkitRequestFullscreen();
  4264. else if (element.mozRequestFullScreen)
  4265. element.mozRequestFullScreen();
  4266. };
  4267. Tools.ExitFullscreen = function () {
  4268. if (document.exitFullscreen) {
  4269. document.exitFullscreen();
  4270. }
  4271. else if (document.mozCancelFullScreen) {
  4272. document.mozCancelFullScreen();
  4273. }
  4274. else if (document.webkitCancelFullScreen) {
  4275. document.webkitCancelFullScreen();
  4276. }
  4277. else if (document.msCancelFullScreen) {
  4278. document.msCancelFullScreen();
  4279. }
  4280. };
  4281. // External files
  4282. Tools.CleanUrl = function (url) {
  4283. url = url.replace(/#/mg, "%23");
  4284. return url;
  4285. };
  4286. Tools.LoadImage = function (url, onload, onerror, database) {
  4287. url = Tools.CleanUrl(url);
  4288. var img = new Image();
  4289. if (url.substr(0, 5) !== "data:")
  4290. img.crossOrigin = 'anonymous';
  4291. img.onload = function () {
  4292. onload(img);
  4293. };
  4294. img.onerror = function (err) {
  4295. onerror(img, err);
  4296. };
  4297. var noIndexedDB = function () {
  4298. img.src = url;
  4299. };
  4300. var loadFromIndexedDB = function () {
  4301. database.loadImageFromDB(url, img);
  4302. };
  4303. //ANY database to do!
  4304. if (database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4305. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4306. }
  4307. else {
  4308. if (url.indexOf("file:") === -1) {
  4309. noIndexedDB();
  4310. }
  4311. else {
  4312. try {
  4313. var textureName = url.substring(5);
  4314. var blobURL;
  4315. try {
  4316. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4317. }
  4318. catch (ex) {
  4319. // Chrome doesn't support oneTimeOnly parameter
  4320. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4321. }
  4322. img.src = blobURL;
  4323. }
  4324. catch (e) {
  4325. Tools.Log("Error while trying to load texture: " + textureName);
  4326. img.src = null;
  4327. }
  4328. }
  4329. }
  4330. return img;
  4331. };
  4332. //ANY
  4333. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4334. url = Tools.CleanUrl(url);
  4335. var noIndexedDB = function () {
  4336. var request = new XMLHttpRequest();
  4337. var loadUrl = Tools.BaseUrl + url;
  4338. request.open('GET', loadUrl, true);
  4339. if (useArrayBuffer) {
  4340. request.responseType = "arraybuffer";
  4341. }
  4342. request.onprogress = progressCallBack;
  4343. request.onreadystatechange = function () {
  4344. if (request.readyState === 4) {
  4345. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  4346. callback(!useArrayBuffer ? request.responseText : request.response);
  4347. }
  4348. else {
  4349. if (onError) {
  4350. onError();
  4351. }
  4352. else {
  4353. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4354. }
  4355. }
  4356. }
  4357. };
  4358. request.send(null);
  4359. };
  4360. var loadFromIndexedDB = function () {
  4361. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4362. };
  4363. if (url.indexOf("file:") !== -1) {
  4364. var fileName = url.substring(5);
  4365. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  4366. }
  4367. else {
  4368. // Caching all files
  4369. if (database && database.enableSceneOffline) {
  4370. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4371. }
  4372. else {
  4373. noIndexedDB();
  4374. }
  4375. }
  4376. };
  4377. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4378. var reader = new FileReader();
  4379. reader.onload = function (e) {
  4380. //target doesn't have result from ts 1.3
  4381. callback(e.target['result']);
  4382. };
  4383. reader.onprogress = progressCallback;
  4384. reader.readAsDataURL(fileToLoad);
  4385. };
  4386. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4387. var reader = new FileReader();
  4388. reader.onerror = function (e) {
  4389. Tools.Log("Error while reading file: " + fileToLoad.name);
  4390. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4391. };
  4392. reader.onload = function (e) {
  4393. //target doesn't have result from ts 1.3
  4394. callback(e.target['result']);
  4395. };
  4396. reader.onprogress = progressCallBack;
  4397. if (!useArrayBuffer) {
  4398. // Asynchronous read
  4399. reader.readAsText(fileToLoad);
  4400. }
  4401. else {
  4402. reader.readAsArrayBuffer(fileToLoad);
  4403. }
  4404. };
  4405. // Misc.
  4406. Tools.Clamp = function (value, min, max) {
  4407. if (min === void 0) { min = 0; }
  4408. if (max === void 0) { max = 1; }
  4409. return Math.min(max, Math.max(min, value));
  4410. };
  4411. // Returns -1 when value is a negative number and
  4412. // +1 when value is a positive number.
  4413. Tools.Sign = function (value) {
  4414. value = +value; // convert to a number
  4415. if (value === 0 || isNaN(value))
  4416. return value;
  4417. return value > 0 ? 1 : -1;
  4418. };
  4419. Tools.Format = function (value, decimals) {
  4420. if (decimals === void 0) { decimals = 2; }
  4421. return value.toFixed(decimals);
  4422. };
  4423. Tools.CheckExtends = function (v, min, max) {
  4424. if (v.x < min.x)
  4425. min.x = v.x;
  4426. if (v.y < min.y)
  4427. min.y = v.y;
  4428. if (v.z < min.z)
  4429. min.z = v.z;
  4430. if (v.x > max.x)
  4431. max.x = v.x;
  4432. if (v.y > max.y)
  4433. max.y = v.y;
  4434. if (v.z > max.z)
  4435. max.z = v.z;
  4436. };
  4437. Tools.WithinEpsilon = function (a, b, epsilon) {
  4438. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4439. var num = a - b;
  4440. return -epsilon <= num && num <= epsilon;
  4441. };
  4442. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4443. for (var prop in source) {
  4444. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4445. continue;
  4446. }
  4447. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4448. continue;
  4449. }
  4450. var sourceValue = source[prop];
  4451. var typeOfSourceValue = typeof sourceValue;
  4452. if (typeOfSourceValue === "function") {
  4453. continue;
  4454. }
  4455. if (typeOfSourceValue === "object") {
  4456. if (sourceValue instanceof Array) {
  4457. destination[prop] = [];
  4458. if (sourceValue.length > 0) {
  4459. if (typeof sourceValue[0] == "object") {
  4460. for (var index = 0; index < sourceValue.length; index++) {
  4461. var clonedValue = cloneValue(sourceValue[index], destination);
  4462. if (destination[prop].indexOf(clonedValue) === -1) {
  4463. destination[prop].push(clonedValue);
  4464. }
  4465. }
  4466. }
  4467. else {
  4468. destination[prop] = sourceValue.slice(0);
  4469. }
  4470. }
  4471. }
  4472. else {
  4473. destination[prop] = cloneValue(sourceValue, destination);
  4474. }
  4475. }
  4476. else {
  4477. destination[prop] = sourceValue;
  4478. }
  4479. }
  4480. };
  4481. Tools.IsEmpty = function (obj) {
  4482. for (var i in obj) {
  4483. return false;
  4484. }
  4485. return true;
  4486. };
  4487. Tools.RegisterTopRootEvents = function (events) {
  4488. for (var index = 0; index < events.length; index++) {
  4489. var event = events[index];
  4490. window.addEventListener(event.name, event.handler, false);
  4491. try {
  4492. if (window.parent) {
  4493. window.parent.addEventListener(event.name, event.handler, false);
  4494. }
  4495. }
  4496. catch (e) {
  4497. }
  4498. }
  4499. };
  4500. Tools.UnregisterTopRootEvents = function (events) {
  4501. for (var index = 0; index < events.length; index++) {
  4502. var event = events[index];
  4503. window.removeEventListener(event.name, event.handler);
  4504. try {
  4505. if (window.parent) {
  4506. window.parent.removeEventListener(event.name, event.handler);
  4507. }
  4508. }
  4509. catch (e) {
  4510. }
  4511. }
  4512. };
  4513. Tools.DumpFramebuffer = function (width, height, engine) {
  4514. // Read the contents of the framebuffer
  4515. var numberOfChannelsByLine = width * 4;
  4516. var halfHeight = height / 2;
  4517. //Reading datas from WebGL
  4518. var data = engine.readPixels(0, 0, width, height);
  4519. //To flip image on Y axis.
  4520. for (var i = 0; i < halfHeight; i++) {
  4521. for (var j = 0; j < numberOfChannelsByLine; j++) {
  4522. var currentCell = j + i * numberOfChannelsByLine;
  4523. var targetLine = height - i - 1;
  4524. var targetCell = j + targetLine * numberOfChannelsByLine;
  4525. var temp = data[currentCell];
  4526. data[currentCell] = data[targetCell];
  4527. data[targetCell] = temp;
  4528. }
  4529. }
  4530. // Create a 2D canvas to store the result
  4531. if (!screenshotCanvas) {
  4532. screenshotCanvas = document.createElement('canvas');
  4533. }
  4534. screenshotCanvas.width = width;
  4535. screenshotCanvas.height = height;
  4536. var context = screenshotCanvas.getContext('2d');
  4537. // Copy the pixels to a 2D canvas
  4538. var imageData = context.createImageData(width, height);
  4539. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  4540. var castData = imageData.data;
  4541. castData.set(data);
  4542. context.putImageData(imageData, 0, 0);
  4543. var base64Image = screenshotCanvas.toDataURL();
  4544. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  4545. if (("download" in document.createElement("a"))) {
  4546. var a = window.document.createElement("a");
  4547. a.href = base64Image;
  4548. var date = new Date();
  4549. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  4550. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  4551. window.document.body.appendChild(a);
  4552. a.addEventListener("click", function () {
  4553. a.parentElement.removeChild(a);
  4554. });
  4555. a.click();
  4556. }
  4557. else {
  4558. var newWindow = window.open("");
  4559. var img = newWindow.document.createElement("img");
  4560. img.src = base64Image;
  4561. newWindow.document.body.appendChild(img);
  4562. }
  4563. };
  4564. Tools.CreateScreenshot = function (engine, camera, size) {
  4565. var width;
  4566. var height;
  4567. var scene = camera.getScene();
  4568. var previousCamera = null;
  4569. if (scene.activeCamera !== camera) {
  4570. previousCamera = scene.activeCamera;
  4571. scene.activeCamera = camera;
  4572. }
  4573. //If a precision value is specified
  4574. if (size.precision) {
  4575. width = Math.round(engine.getRenderWidth() * size.precision);
  4576. height = Math.round(width / engine.getAspectRatio(camera));
  4577. size = { width: width, height: height };
  4578. }
  4579. else if (size.width && size.height) {
  4580. width = size.width;
  4581. height = size.height;
  4582. }
  4583. else if (size.width && !size.height) {
  4584. width = size.width;
  4585. height = Math.round(width / engine.getAspectRatio(camera));
  4586. size = { width: width, height: height };
  4587. }
  4588. else if (size.height && !size.width) {
  4589. height = size.height;
  4590. width = Math.round(height * engine.getAspectRatio(camera));
  4591. size = { width: width, height: height };
  4592. }
  4593. else if (!isNaN(size)) {
  4594. height = size;
  4595. width = size;
  4596. }
  4597. else {
  4598. Tools.Error("Invalid 'size' parameter !");
  4599. return;
  4600. }
  4601. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  4602. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  4603. texture.renderList = scene.meshes;
  4604. texture.onAfterRender = function () {
  4605. Tools.DumpFramebuffer(width, height, engine);
  4606. };
  4607. scene.incrementRenderId();
  4608. texture.render(true);
  4609. texture.dispose();
  4610. if (previousCamera) {
  4611. scene.activeCamera = previousCamera;
  4612. }
  4613. };
  4614. // XHR response validator for local file scenario
  4615. Tools.ValidateXHRData = function (xhr, dataType) {
  4616. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  4617. if (dataType === void 0) { dataType = 7; }
  4618. try {
  4619. if (dataType & 1) {
  4620. if (xhr.responseText && xhr.responseText.length > 0) {
  4621. return true;
  4622. }
  4623. else if (dataType === 1) {
  4624. return false;
  4625. }
  4626. }
  4627. if (dataType & 2) {
  4628. // Check header width and height since there is no "TGA" magic number
  4629. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  4630. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  4631. return true;
  4632. }
  4633. else if (dataType === 2) {
  4634. return false;
  4635. }
  4636. }
  4637. if (dataType & 4) {
  4638. // Check for the "DDS" magic number
  4639. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  4640. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  4641. return true;
  4642. }
  4643. else {
  4644. return false;
  4645. }
  4646. }
  4647. }
  4648. catch (e) {
  4649. }
  4650. return false;
  4651. };
  4652. Object.defineProperty(Tools, "NoneLogLevel", {
  4653. get: function () {
  4654. return Tools._NoneLogLevel;
  4655. },
  4656. enumerable: true,
  4657. configurable: true
  4658. });
  4659. Object.defineProperty(Tools, "MessageLogLevel", {
  4660. get: function () {
  4661. return Tools._MessageLogLevel;
  4662. },
  4663. enumerable: true,
  4664. configurable: true
  4665. });
  4666. Object.defineProperty(Tools, "WarningLogLevel", {
  4667. get: function () {
  4668. return Tools._WarningLogLevel;
  4669. },
  4670. enumerable: true,
  4671. configurable: true
  4672. });
  4673. Object.defineProperty(Tools, "ErrorLogLevel", {
  4674. get: function () {
  4675. return Tools._ErrorLogLevel;
  4676. },
  4677. enumerable: true,
  4678. configurable: true
  4679. });
  4680. Object.defineProperty(Tools, "AllLogLevel", {
  4681. get: function () {
  4682. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  4683. },
  4684. enumerable: true,
  4685. configurable: true
  4686. });
  4687. Tools._AddLogEntry = function (entry) {
  4688. Tools._LogCache = entry + Tools._LogCache;
  4689. if (Tools.OnNewCacheEntry) {
  4690. Tools.OnNewCacheEntry(entry);
  4691. }
  4692. };
  4693. Tools._FormatMessage = function (message) {
  4694. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  4695. var date = new Date();
  4696. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  4697. };
  4698. Tools._LogDisabled = function (message) {
  4699. // nothing to do
  4700. };
  4701. Tools._LogEnabled = function (message) {
  4702. var formattedMessage = Tools._FormatMessage(message);
  4703. console.log("BJS - " + formattedMessage);
  4704. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  4705. Tools._AddLogEntry(entry);
  4706. };
  4707. Tools._WarnDisabled = function (message) {
  4708. // nothing to do
  4709. };
  4710. Tools._WarnEnabled = function (message) {
  4711. var formattedMessage = Tools._FormatMessage(message);
  4712. console.warn("BJS - " + formattedMessage);
  4713. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  4714. Tools._AddLogEntry(entry);
  4715. };
  4716. Tools._ErrorDisabled = function (message) {
  4717. // nothing to do
  4718. };
  4719. Tools._ErrorEnabled = function (message) {
  4720. var formattedMessage = Tools._FormatMessage(message);
  4721. console.error("BJS - " + formattedMessage);
  4722. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  4723. Tools._AddLogEntry(entry);
  4724. };
  4725. Object.defineProperty(Tools, "LogCache", {
  4726. get: function () {
  4727. return Tools._LogCache;
  4728. },
  4729. enumerable: true,
  4730. configurable: true
  4731. });
  4732. Object.defineProperty(Tools, "LogLevels", {
  4733. set: function (level) {
  4734. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  4735. Tools.Log = Tools._LogEnabled;
  4736. }
  4737. else {
  4738. Tools.Log = Tools._LogDisabled;
  4739. }
  4740. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  4741. Tools.Warn = Tools._WarnEnabled;
  4742. }
  4743. else {
  4744. Tools.Warn = Tools._WarnDisabled;
  4745. }
  4746. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  4747. Tools.Error = Tools._ErrorEnabled;
  4748. }
  4749. else {
  4750. Tools.Error = Tools._ErrorDisabled;
  4751. }
  4752. },
  4753. enumerable: true,
  4754. configurable: true
  4755. });
  4756. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  4757. get: function () {
  4758. return Tools._PerformanceNoneLogLevel;
  4759. },
  4760. enumerable: true,
  4761. configurable: true
  4762. });
  4763. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  4764. get: function () {
  4765. return Tools._PerformanceUserMarkLogLevel;
  4766. },
  4767. enumerable: true,
  4768. configurable: true
  4769. });
  4770. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  4771. get: function () {
  4772. return Tools._PerformanceConsoleLogLevel;
  4773. },
  4774. enumerable: true,
  4775. configurable: true
  4776. });
  4777. Object.defineProperty(Tools, "PerformanceLogLevel", {
  4778. set: function (level) {
  4779. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  4780. Tools.StartPerformanceCounter = Tools._StartUserMark;
  4781. Tools.EndPerformanceCounter = Tools._EndUserMark;
  4782. return;
  4783. }
  4784. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  4785. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  4786. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  4787. return;
  4788. }
  4789. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4790. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4791. },
  4792. enumerable: true,
  4793. configurable: true
  4794. });
  4795. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  4796. };
  4797. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  4798. };
  4799. Tools._StartUserMark = function (counterName, condition) {
  4800. if (condition === void 0) { condition = true; }
  4801. if (!condition || !Tools._performance.mark) {
  4802. return;
  4803. }
  4804. Tools._performance.mark(counterName + "-Begin");
  4805. };
  4806. Tools._EndUserMark = function (counterName, condition) {
  4807. if (condition === void 0) { condition = true; }
  4808. if (!condition || !Tools._performance.mark) {
  4809. return;
  4810. }
  4811. Tools._performance.mark(counterName + "-End");
  4812. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  4813. };
  4814. Tools._StartPerformanceConsole = function (counterName, condition) {
  4815. if (condition === void 0) { condition = true; }
  4816. if (!condition) {
  4817. return;
  4818. }
  4819. Tools._StartUserMark(counterName, condition);
  4820. if (console.time) {
  4821. console.time(counterName);
  4822. }
  4823. };
  4824. Tools._EndPerformanceConsole = function (counterName, condition) {
  4825. if (condition === void 0) { condition = true; }
  4826. if (!condition) {
  4827. return;
  4828. }
  4829. Tools._EndUserMark(counterName, condition);
  4830. if (console.time) {
  4831. console.timeEnd(counterName);
  4832. }
  4833. };
  4834. Object.defineProperty(Tools, "Now", {
  4835. get: function () {
  4836. if (window.performance && window.performance.now) {
  4837. return window.performance.now();
  4838. }
  4839. return new Date().getTime();
  4840. },
  4841. enumerable: true,
  4842. configurable: true
  4843. });
  4844. // Deprecated
  4845. Tools.GetFps = function () {
  4846. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  4847. return 0;
  4848. };
  4849. Tools.BaseUrl = "";
  4850. // Logs
  4851. Tools._NoneLogLevel = 0;
  4852. Tools._MessageLogLevel = 1;
  4853. Tools._WarningLogLevel = 2;
  4854. Tools._ErrorLogLevel = 4;
  4855. Tools._LogCache = "";
  4856. Tools.Log = Tools._LogEnabled;
  4857. Tools.Warn = Tools._WarnEnabled;
  4858. Tools.Error = Tools._ErrorEnabled;
  4859. // Performances
  4860. Tools._PerformanceNoneLogLevel = 0;
  4861. Tools._PerformanceUserMarkLogLevel = 1;
  4862. Tools._PerformanceConsoleLogLevel = 2;
  4863. Tools._performance = window.performance;
  4864. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  4865. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  4866. return Tools;
  4867. })();
  4868. BABYLON.Tools = Tools;
  4869. /**
  4870. * An implementation of a loop for asynchronous functions.
  4871. */
  4872. var AsyncLoop = (function () {
  4873. /**
  4874. * Constroctor.
  4875. * @param iterations the number of iterations.
  4876. * @param _fn the function to run each iteration
  4877. * @param _successCallback the callback that will be called upon succesful execution
  4878. * @param offset starting offset.
  4879. */
  4880. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  4881. if (offset === void 0) { offset = 0; }
  4882. this.iterations = iterations;
  4883. this._fn = _fn;
  4884. this._successCallback = _successCallback;
  4885. this.index = offset - 1;
  4886. this._done = false;
  4887. }
  4888. /**
  4889. * Execute the next iteration. Must be called after the last iteration was finished.
  4890. */
  4891. AsyncLoop.prototype.executeNext = function () {
  4892. if (!this._done) {
  4893. if (this.index + 1 < this.iterations) {
  4894. ++this.index;
  4895. this._fn(this);
  4896. }
  4897. else {
  4898. this.breakLoop();
  4899. }
  4900. }
  4901. };
  4902. /**
  4903. * Break the loop and run the success callback.
  4904. */
  4905. AsyncLoop.prototype.breakLoop = function () {
  4906. this._done = true;
  4907. this._successCallback();
  4908. };
  4909. /**
  4910. * Helper function
  4911. */
  4912. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  4913. if (offset === void 0) { offset = 0; }
  4914. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  4915. loop.executeNext();
  4916. return loop;
  4917. };
  4918. /**
  4919. * A for-loop that will run a given number of iterations synchronous and the rest async.
  4920. * @param iterations total number of iterations
  4921. * @param syncedIterations number of synchronous iterations in each async iteration.
  4922. * @param fn the function to call each iteration.
  4923. * @param callback a success call back that will be called when iterating stops.
  4924. * @param breakFunction a break condition (optional)
  4925. * @param timeout timeout settings for the setTimeout function. default - 0.
  4926. * @constructor
  4927. */
  4928. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  4929. if (timeout === void 0) { timeout = 0; }
  4930. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  4931. if (breakFunction && breakFunction())
  4932. loop.breakLoop();
  4933. else {
  4934. setTimeout(function () {
  4935. for (var i = 0; i < syncedIterations; ++i) {
  4936. var iteration = (loop.index * syncedIterations) + i;
  4937. if (iteration >= iterations)
  4938. break;
  4939. fn(iteration);
  4940. if (breakFunction && breakFunction()) {
  4941. loop.breakLoop();
  4942. break;
  4943. }
  4944. }
  4945. loop.executeNext();
  4946. }, timeout);
  4947. }
  4948. }, callback);
  4949. };
  4950. return AsyncLoop;
  4951. })();
  4952. BABYLON.AsyncLoop = AsyncLoop;
  4953. })(BABYLON || (BABYLON = {}));
  4954. //# sourceMappingURL=babylon.tools.js.map
  4955. var BABYLON;
  4956. (function (BABYLON) {
  4957. var _DepthCullingState = (function () {
  4958. function _DepthCullingState() {
  4959. this._isDepthTestDirty = false;
  4960. this._isDepthMaskDirty = false;
  4961. this._isDepthFuncDirty = false;
  4962. this._isCullFaceDirty = false;
  4963. this._isCullDirty = false;
  4964. this._isZOffsetDirty = false;
  4965. }
  4966. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  4967. get: function () {
  4968. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  4969. },
  4970. enumerable: true,
  4971. configurable: true
  4972. });
  4973. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  4974. get: function () {
  4975. return this._zOffset;
  4976. },
  4977. set: function (value) {
  4978. if (this._zOffset === value) {
  4979. return;
  4980. }
  4981. this._zOffset = value;
  4982. this._isZOffsetDirty = true;
  4983. },
  4984. enumerable: true,
  4985. configurable: true
  4986. });
  4987. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  4988. get: function () {
  4989. return this._cullFace;
  4990. },
  4991. set: function (value) {
  4992. if (this._cullFace === value) {
  4993. return;
  4994. }
  4995. this._cullFace = value;
  4996. this._isCullFaceDirty = true;
  4997. },
  4998. enumerable: true,
  4999. configurable: true
  5000. });
  5001. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5002. get: function () {
  5003. return this._cull;
  5004. },
  5005. set: function (value) {
  5006. if (this._cull === value) {
  5007. return;
  5008. }
  5009. this._cull = value;
  5010. this._isCullDirty = true;
  5011. },
  5012. enumerable: true,
  5013. configurable: true
  5014. });
  5015. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5016. get: function () {
  5017. return this._depthFunc;
  5018. },
  5019. set: function (value) {
  5020. if (this._depthFunc === value) {
  5021. return;
  5022. }
  5023. this._depthFunc = value;
  5024. this._isDepthFuncDirty = true;
  5025. },
  5026. enumerable: true,
  5027. configurable: true
  5028. });
  5029. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5030. get: function () {
  5031. return this._depthMask;
  5032. },
  5033. set: function (value) {
  5034. if (this._depthMask === value) {
  5035. return;
  5036. }
  5037. this._depthMask = value;
  5038. this._isDepthMaskDirty = true;
  5039. },
  5040. enumerable: true,
  5041. configurable: true
  5042. });
  5043. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5044. get: function () {
  5045. return this._depthTest;
  5046. },
  5047. set: function (value) {
  5048. if (this._depthTest === value) {
  5049. return;
  5050. }
  5051. this._depthTest = value;
  5052. this._isDepthTestDirty = true;
  5053. },
  5054. enumerable: true,
  5055. configurable: true
  5056. });
  5057. _DepthCullingState.prototype.reset = function () {
  5058. this._depthMask = true;
  5059. this._depthTest = true;
  5060. this._depthFunc = null;
  5061. this._cull = null;
  5062. this._cullFace = null;
  5063. this._zOffset = 0;
  5064. this._isDepthTestDirty = true;
  5065. this._isDepthMaskDirty = true;
  5066. this._isDepthFuncDirty = false;
  5067. this._isCullFaceDirty = false;
  5068. this._isCullDirty = false;
  5069. this._isZOffsetDirty = false;
  5070. };
  5071. _DepthCullingState.prototype.apply = function (gl) {
  5072. if (!this.isDirty) {
  5073. return;
  5074. }
  5075. // Cull
  5076. if (this._isCullDirty) {
  5077. if (this.cull) {
  5078. gl.enable(gl.CULL_FACE);
  5079. }
  5080. else {
  5081. gl.disable(gl.CULL_FACE);
  5082. }
  5083. this._isCullDirty = false;
  5084. }
  5085. // Cull face
  5086. if (this._isCullFaceDirty) {
  5087. gl.cullFace(this.cullFace);
  5088. this._isCullFaceDirty = false;
  5089. }
  5090. // Depth mask
  5091. if (this._isDepthMaskDirty) {
  5092. gl.depthMask(this.depthMask);
  5093. this._isDepthMaskDirty = false;
  5094. }
  5095. // Depth test
  5096. if (this._isDepthTestDirty) {
  5097. if (this.depthTest) {
  5098. gl.enable(gl.DEPTH_TEST);
  5099. }
  5100. else {
  5101. gl.disable(gl.DEPTH_TEST);
  5102. }
  5103. this._isDepthTestDirty = false;
  5104. }
  5105. // Depth func
  5106. if (this._isDepthFuncDirty) {
  5107. gl.depthFunc(this.depthFunc);
  5108. this._isDepthFuncDirty = false;
  5109. }
  5110. // zOffset
  5111. if (this._isZOffsetDirty) {
  5112. if (this.zOffset) {
  5113. gl.enable(gl.POLYGON_OFFSET_FILL);
  5114. gl.polygonOffset(this.zOffset, 0);
  5115. }
  5116. else {
  5117. gl.disable(gl.POLYGON_OFFSET_FILL);
  5118. }
  5119. this._isZOffsetDirty = false;
  5120. }
  5121. };
  5122. return _DepthCullingState;
  5123. })();
  5124. BABYLON._DepthCullingState = _DepthCullingState;
  5125. var _AlphaState = (function () {
  5126. function _AlphaState() {
  5127. this._isAlphaBlendDirty = false;
  5128. this._isBlendFunctionParametersDirty = false;
  5129. this._alphaBlend = false;
  5130. this._blendFunctionParameters = new Array(4);
  5131. }
  5132. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5133. get: function () {
  5134. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5135. },
  5136. enumerable: true,
  5137. configurable: true
  5138. });
  5139. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5140. get: function () {
  5141. return this._alphaBlend;
  5142. },
  5143. set: function (value) {
  5144. if (this._alphaBlend === value) {
  5145. return;
  5146. }
  5147. this._alphaBlend = value;
  5148. this._isAlphaBlendDirty = true;
  5149. },
  5150. enumerable: true,
  5151. configurable: true
  5152. });
  5153. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5154. if (this._blendFunctionParameters[0] === value0 &&
  5155. this._blendFunctionParameters[1] === value1 &&
  5156. this._blendFunctionParameters[2] === value2 &&
  5157. this._blendFunctionParameters[3] === value3) {
  5158. return;
  5159. }
  5160. this._blendFunctionParameters[0] = value0;
  5161. this._blendFunctionParameters[1] = value1;
  5162. this._blendFunctionParameters[2] = value2;
  5163. this._blendFunctionParameters[3] = value3;
  5164. this._isBlendFunctionParametersDirty = true;
  5165. };
  5166. _AlphaState.prototype.reset = function () {
  5167. this._alphaBlend = false;
  5168. this._blendFunctionParameters[0] = null;
  5169. this._blendFunctionParameters[1] = null;
  5170. this._blendFunctionParameters[2] = null;
  5171. this._blendFunctionParameters[3] = null;
  5172. this._isAlphaBlendDirty = true;
  5173. this._isBlendFunctionParametersDirty = false;
  5174. };
  5175. _AlphaState.prototype.apply = function (gl) {
  5176. if (!this.isDirty) {
  5177. return;
  5178. }
  5179. // Alpha blend
  5180. if (this._isAlphaBlendDirty) {
  5181. if (this._alphaBlend) {
  5182. gl.enable(gl.BLEND);
  5183. }
  5184. else {
  5185. gl.disable(gl.BLEND);
  5186. }
  5187. this._isAlphaBlendDirty = false;
  5188. }
  5189. // Alpha function
  5190. if (this._isBlendFunctionParametersDirty) {
  5191. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5192. this._isBlendFunctionParametersDirty = false;
  5193. }
  5194. };
  5195. return _AlphaState;
  5196. })();
  5197. BABYLON._AlphaState = _AlphaState;
  5198. var compileShader = function (gl, source, type, defines) {
  5199. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  5200. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  5201. gl.compileShader(shader);
  5202. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  5203. throw new Error(gl.getShaderInfoLog(shader));
  5204. }
  5205. return shader;
  5206. };
  5207. var getWebGLTextureType = function (gl, type) {
  5208. var textureType = gl.UNSIGNED_BYTE;
  5209. if (type === Engine.TEXTURETYPE_FLOAT)
  5210. textureType = gl.FLOAT;
  5211. return textureType;
  5212. };
  5213. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  5214. var magFilter = gl.NEAREST;
  5215. var minFilter = gl.NEAREST;
  5216. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  5217. magFilter = gl.LINEAR;
  5218. if (generateMipMaps) {
  5219. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  5220. }
  5221. else {
  5222. minFilter = gl.LINEAR;
  5223. }
  5224. }
  5225. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  5226. magFilter = gl.LINEAR;
  5227. if (generateMipMaps) {
  5228. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  5229. }
  5230. else {
  5231. minFilter = gl.LINEAR;
  5232. }
  5233. }
  5234. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5235. magFilter = gl.NEAREST;
  5236. if (generateMipMaps) {
  5237. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  5238. }
  5239. else {
  5240. minFilter = gl.NEAREST;
  5241. }
  5242. }
  5243. return {
  5244. min: minFilter,
  5245. mag: magFilter
  5246. };
  5247. };
  5248. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  5249. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  5250. var engine = scene.getEngine();
  5251. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  5252. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  5253. gl.bindTexture(gl.TEXTURE_2D, texture);
  5254. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  5255. texture._baseWidth = width;
  5256. texture._baseHeight = height;
  5257. texture._width = potWidth;
  5258. texture._height = potHeight;
  5259. texture.isReady = true;
  5260. processFunction(potWidth, potHeight);
  5261. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  5262. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5263. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5264. if (!noMipmap && !isCompressed) {
  5265. gl.generateMipmap(gl.TEXTURE_2D);
  5266. }
  5267. gl.bindTexture(gl.TEXTURE_2D, null);
  5268. engine._activeTexturesCache = [];
  5269. scene._removePendingData(texture);
  5270. };
  5271. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  5272. var onload = function () {
  5273. loadedImages[index] = img;
  5274. loadedImages._internalCount++;
  5275. scene._removePendingData(img);
  5276. if (loadedImages._internalCount === 6) {
  5277. onfinish(loadedImages);
  5278. }
  5279. };
  5280. var onerror = function () {
  5281. scene._removePendingData(img);
  5282. };
  5283. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  5284. scene._addPendingData(img);
  5285. };
  5286. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  5287. var loadedImages = [];
  5288. loadedImages._internalCount = 0;
  5289. for (var index = 0; index < 6; index++) {
  5290. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  5291. }
  5292. };
  5293. var EngineCapabilities = (function () {
  5294. function EngineCapabilities() {
  5295. }
  5296. return EngineCapabilities;
  5297. })();
  5298. BABYLON.EngineCapabilities = EngineCapabilities;
  5299. /**
  5300. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  5301. */
  5302. var Engine = (function () {
  5303. /**
  5304. * @constructor
  5305. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  5306. * @param {boolean} [antialias] - enable antialias
  5307. * @param options - further options to be sent to the getContext function
  5308. */
  5309. function Engine(canvas, antialias, options) {
  5310. var _this = this;
  5311. // Public members
  5312. this.isFullscreen = false;
  5313. this.isPointerLock = false;
  5314. this.cullBackFaces = true;
  5315. this.renderEvenInBackground = true;
  5316. this.scenes = new Array();
  5317. this._windowIsBackground = false;
  5318. this._loadingDivBackgroundColor = "black";
  5319. this._drawCalls = 0;
  5320. this._renderingQueueLaunched = false;
  5321. this._activeRenderLoops = [];
  5322. // FPS
  5323. this.fpsRange = 60;
  5324. this.previousFramesDuration = [];
  5325. this.fps = 60;
  5326. this.deltaTime = 0;
  5327. // States
  5328. this._depthCullingState = new _DepthCullingState();
  5329. this._alphaState = new _AlphaState();
  5330. this._alphaMode = Engine.ALPHA_DISABLE;
  5331. // Cache
  5332. this._loadedTexturesCache = new Array();
  5333. this._activeTexturesCache = new Array();
  5334. this._compiledEffects = {};
  5335. this._uintIndicesCurrentlySet = false;
  5336. this._renderingCanvas = canvas;
  5337. options = options || {};
  5338. options.antialias = antialias;
  5339. // GL
  5340. try {
  5341. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  5342. }
  5343. catch (e) {
  5344. throw new Error("WebGL not supported");
  5345. }
  5346. if (!this._gl) {
  5347. throw new Error("WebGL not supported");
  5348. }
  5349. this._onBlur = function () {
  5350. _this._windowIsBackground = true;
  5351. };
  5352. this._onFocus = function () {
  5353. _this._windowIsBackground = false;
  5354. };
  5355. window.addEventListener("blur", this._onBlur);
  5356. window.addEventListener("focus", this._onFocus);
  5357. // Viewport
  5358. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  5359. this.resize();
  5360. // Caps
  5361. this._caps = new EngineCapabilities();
  5362. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  5363. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  5364. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  5365. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  5366. // Infos
  5367. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  5368. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  5369. if (rendererInfo != null) {
  5370. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  5371. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  5372. }
  5373. if (!this._glVendor) {
  5374. this._glVendor = "Unknown vendor";
  5375. }
  5376. if (!this._glRenderer) {
  5377. this._glRenderer = "Unknown renderer";
  5378. }
  5379. // Extensions
  5380. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  5381. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  5382. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  5383. 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');
  5384. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  5385. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  5386. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  5387. this._caps.highPrecisionShaderSupported = true;
  5388. if (this._gl.getShaderPrecisionFormat) {
  5389. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  5390. this._caps.highPrecisionShaderSupported = highp.precision != 0;
  5391. }
  5392. // Depth buffer
  5393. this.setDepthBuffer(true);
  5394. this.setDepthFunctionToLessOrEqual();
  5395. this.setDepthWrite(true);
  5396. // Fullscreen
  5397. this._onFullscreenChange = function () {
  5398. if (document.fullscreen !== undefined) {
  5399. _this.isFullscreen = document.fullscreen;
  5400. }
  5401. else if (document.mozFullScreen !== undefined) {
  5402. _this.isFullscreen = document.mozFullScreen;
  5403. }
  5404. else if (document.webkitIsFullScreen !== undefined) {
  5405. _this.isFullscreen = document.webkitIsFullScreen;
  5406. }
  5407. else if (document.msIsFullScreen !== undefined) {
  5408. _this.isFullscreen = document.msIsFullScreen;
  5409. }
  5410. // Pointer lock
  5411. if (_this.isFullscreen && _this._pointerLockRequested) {
  5412. canvas.requestPointerLock = canvas.requestPointerLock ||
  5413. canvas.msRequestPointerLock ||
  5414. canvas.mozRequestPointerLock ||
  5415. canvas.webkitRequestPointerLock;
  5416. if (canvas.requestPointerLock) {
  5417. canvas.requestPointerLock();
  5418. }
  5419. }
  5420. };
  5421. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  5422. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  5423. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  5424. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  5425. // Pointer lock
  5426. this._onPointerLockChange = function () {
  5427. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  5428. document.webkitPointerLockElement === canvas ||
  5429. document.msPointerLockElement === canvas ||
  5430. document.pointerLockElement === canvas);
  5431. };
  5432. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  5433. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  5434. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  5435. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  5436. if (!Engine.audioEngine) {
  5437. Engine.audioEngine = new BABYLON.AudioEngine();
  5438. }
  5439. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  5440. }
  5441. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  5442. get: function () {
  5443. return Engine._ALPHA_DISABLE;
  5444. },
  5445. enumerable: true,
  5446. configurable: true
  5447. });
  5448. Object.defineProperty(Engine, "ALPHA_ADD", {
  5449. get: function () {
  5450. return Engine._ALPHA_ADD;
  5451. },
  5452. enumerable: true,
  5453. configurable: true
  5454. });
  5455. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  5456. get: function () {
  5457. return Engine._ALPHA_COMBINE;
  5458. },
  5459. enumerable: true,
  5460. configurable: true
  5461. });
  5462. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  5463. get: function () {
  5464. return Engine._DELAYLOADSTATE_NONE;
  5465. },
  5466. enumerable: true,
  5467. configurable: true
  5468. });
  5469. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  5470. get: function () {
  5471. return Engine._DELAYLOADSTATE_LOADED;
  5472. },
  5473. enumerable: true,
  5474. configurable: true
  5475. });
  5476. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  5477. get: function () {
  5478. return Engine._DELAYLOADSTATE_LOADING;
  5479. },
  5480. enumerable: true,
  5481. configurable: true
  5482. });
  5483. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  5484. get: function () {
  5485. return Engine._DELAYLOADSTATE_NOTLOADED;
  5486. },
  5487. enumerable: true,
  5488. configurable: true
  5489. });
  5490. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  5491. get: function () {
  5492. return Engine._TEXTUREFORMAT_ALPHA;
  5493. },
  5494. enumerable: true,
  5495. configurable: true
  5496. });
  5497. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  5498. get: function () {
  5499. return Engine._TEXTUREFORMAT_LUMINANCE;
  5500. },
  5501. enumerable: true,
  5502. configurable: true
  5503. });
  5504. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  5505. get: function () {
  5506. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  5507. },
  5508. enumerable: true,
  5509. configurable: true
  5510. });
  5511. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  5512. get: function () {
  5513. return Engine._TEXTUREFORMAT_RGB;
  5514. },
  5515. enumerable: true,
  5516. configurable: true
  5517. });
  5518. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  5519. get: function () {
  5520. return Engine._TEXTUREFORMAT_RGBA;
  5521. },
  5522. enumerable: true,
  5523. configurable: true
  5524. });
  5525. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  5526. get: function () {
  5527. return Engine._TEXTURETYPE_UNSIGNED_INT;
  5528. },
  5529. enumerable: true,
  5530. configurable: true
  5531. });
  5532. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  5533. get: function () {
  5534. return Engine._TEXTURETYPE_FLOAT;
  5535. },
  5536. enumerable: true,
  5537. configurable: true
  5538. });
  5539. Object.defineProperty(Engine, "Version", {
  5540. get: function () {
  5541. return "2.1.0";
  5542. },
  5543. enumerable: true,
  5544. configurable: true
  5545. });
  5546. Engine.prototype._prepareWorkingCanvas = function () {
  5547. if (this._workingCanvas) {
  5548. return;
  5549. }
  5550. this._workingCanvas = document.createElement("canvas");
  5551. this._workingContext = this._workingCanvas.getContext("2d");
  5552. };
  5553. Engine.prototype.getGlInfo = function () {
  5554. return {
  5555. vendor: this._glVendor,
  5556. renderer: this._glRenderer,
  5557. version: this._glVersion
  5558. };
  5559. };
  5560. Engine.prototype.getAspectRatio = function (camera) {
  5561. var viewport = camera.viewport;
  5562. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  5563. };
  5564. Engine.prototype.getRenderWidth = function () {
  5565. if (this._currentRenderTarget) {
  5566. return this._currentRenderTarget._width;
  5567. }
  5568. return this._renderingCanvas.width;
  5569. };
  5570. Engine.prototype.getRenderHeight = function () {
  5571. if (this._currentRenderTarget) {
  5572. return this._currentRenderTarget._height;
  5573. }
  5574. return this._renderingCanvas.height;
  5575. };
  5576. Engine.prototype.getRenderingCanvas = function () {
  5577. return this._renderingCanvas;
  5578. };
  5579. Engine.prototype.getRenderingCanvasClientRect = function () {
  5580. return this._renderingCanvas.getBoundingClientRect();
  5581. };
  5582. Engine.prototype.setHardwareScalingLevel = function (level) {
  5583. this._hardwareScalingLevel = level;
  5584. this.resize();
  5585. };
  5586. Engine.prototype.getHardwareScalingLevel = function () {
  5587. return this._hardwareScalingLevel;
  5588. };
  5589. Engine.prototype.getLoadedTexturesCache = function () {
  5590. return this._loadedTexturesCache;
  5591. };
  5592. Engine.prototype.getCaps = function () {
  5593. return this._caps;
  5594. };
  5595. Object.defineProperty(Engine.prototype, "drawCalls", {
  5596. get: function () {
  5597. return this._drawCalls;
  5598. },
  5599. enumerable: true,
  5600. configurable: true
  5601. });
  5602. // Methods
  5603. Engine.prototype.resetDrawCalls = function () {
  5604. this._drawCalls = 0;
  5605. };
  5606. Engine.prototype.setDepthFunctionToGreater = function () {
  5607. this._depthCullingState.depthFunc = this._gl.GREATER;
  5608. };
  5609. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  5610. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  5611. };
  5612. Engine.prototype.setDepthFunctionToLess = function () {
  5613. this._depthCullingState.depthFunc = this._gl.LESS;
  5614. };
  5615. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  5616. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  5617. };
  5618. /**
  5619. * stop executing a render loop function and remove it from the execution array
  5620. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  5621. */
  5622. Engine.prototype.stopRenderLoop = function (renderFunction) {
  5623. if (!renderFunction) {
  5624. this._activeRenderLoops = [];
  5625. return;
  5626. }
  5627. var index = this._activeRenderLoops.indexOf(renderFunction);
  5628. if (index >= 0) {
  5629. this._activeRenderLoops.splice(index, 1);
  5630. }
  5631. };
  5632. Engine.prototype._renderLoop = function () {
  5633. var _this = this;
  5634. var shouldRender = true;
  5635. if (!this.renderEvenInBackground && this._windowIsBackground) {
  5636. shouldRender = false;
  5637. }
  5638. if (shouldRender) {
  5639. // Start new frame
  5640. this.beginFrame();
  5641. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  5642. var renderFunction = this._activeRenderLoops[index];
  5643. renderFunction();
  5644. }
  5645. // Present
  5646. this.endFrame();
  5647. }
  5648. if (this._activeRenderLoops.length > 0) {
  5649. // Register new frame
  5650. BABYLON.Tools.QueueNewFrame(function () {
  5651. _this._renderLoop();
  5652. });
  5653. }
  5654. else {
  5655. this._renderingQueueLaunched = false;
  5656. }
  5657. };
  5658. /**
  5659. * Register and execute a render loop. The engine can have more than one render function.
  5660. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  5661. * @example
  5662. * engine.runRenderLoop(function () {
  5663. * scene.render()
  5664. * })
  5665. */
  5666. Engine.prototype.runRenderLoop = function (renderFunction) {
  5667. var _this = this;
  5668. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  5669. return;
  5670. }
  5671. this._activeRenderLoops.push(renderFunction);
  5672. if (!this._renderingQueueLaunched) {
  5673. this._renderingQueueLaunched = true;
  5674. BABYLON.Tools.QueueNewFrame(function () {
  5675. _this._renderLoop();
  5676. });
  5677. }
  5678. };
  5679. /**
  5680. * Toggle full screen mode.
  5681. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  5682. */
  5683. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  5684. if (this.isFullscreen) {
  5685. BABYLON.Tools.ExitFullscreen();
  5686. }
  5687. else {
  5688. this._pointerLockRequested = requestPointerLock;
  5689. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  5690. }
  5691. };
  5692. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  5693. this.applyStates();
  5694. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  5695. if (this._depthCullingState.depthMask) {
  5696. this._gl.clearDepth(1.0);
  5697. }
  5698. var mode = 0;
  5699. if (backBuffer)
  5700. mode |= this._gl.COLOR_BUFFER_BIT;
  5701. if (depthStencil && this._depthCullingState.depthMask)
  5702. mode |= this._gl.DEPTH_BUFFER_BIT;
  5703. this._gl.clear(mode);
  5704. };
  5705. /**
  5706. * Set the WebGL's viewport
  5707. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  5708. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  5709. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  5710. */
  5711. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  5712. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  5713. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  5714. var x = viewport.x || 0;
  5715. var y = viewport.y || 0;
  5716. this._cachedViewport = viewport;
  5717. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  5718. };
  5719. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  5720. this._cachedViewport = null;
  5721. this._gl.viewport(x, y, width, height);
  5722. };
  5723. Engine.prototype.beginFrame = function () {
  5724. this._measureFps();
  5725. };
  5726. Engine.prototype.endFrame = function () {
  5727. //this.flushFramebuffer();
  5728. };
  5729. /**
  5730. * resize the view according to the canvas' size.
  5731. * @example
  5732. * window.addEventListener("resize", function () {
  5733. * engine.resize();
  5734. * });
  5735. */
  5736. Engine.prototype.resize = function () {
  5737. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  5738. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  5739. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  5740. };
  5741. /**
  5742. * force a specific size of the canvas
  5743. * @param {number} width - the new canvas' width
  5744. * @param {number} height - the new canvas' height
  5745. */
  5746. Engine.prototype.setSize = function (width, height) {
  5747. this._renderingCanvas.width = width;
  5748. this._renderingCanvas.height = height;
  5749. for (var index = 0; index < this.scenes.length; index++) {
  5750. var scene = this.scenes[index];
  5751. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  5752. var cam = scene.cameras[camIndex];
  5753. cam._currentRenderId = 0;
  5754. }
  5755. }
  5756. };
  5757. Engine.prototype.bindFramebuffer = function (texture) {
  5758. this._currentRenderTarget = texture;
  5759. var gl = this._gl;
  5760. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  5761. this._gl.viewport(0, 0, texture._width, texture._height);
  5762. this.wipeCaches();
  5763. };
  5764. Engine.prototype.unBindFramebuffer = function (texture) {
  5765. this._currentRenderTarget = null;
  5766. if (texture.generateMipMaps) {
  5767. var gl = this._gl;
  5768. gl.bindTexture(gl.TEXTURE_2D, texture);
  5769. gl.generateMipmap(gl.TEXTURE_2D);
  5770. gl.bindTexture(gl.TEXTURE_2D, null);
  5771. }
  5772. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5773. };
  5774. Engine.prototype.flushFramebuffer = function () {
  5775. this._gl.flush();
  5776. };
  5777. Engine.prototype.restoreDefaultFramebuffer = function () {
  5778. this._currentRenderTarget = null;
  5779. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  5780. this.setViewport(this._cachedViewport);
  5781. this.wipeCaches();
  5782. };
  5783. // VBOs
  5784. Engine.prototype._resetVertexBufferBinding = function () {
  5785. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  5786. this._cachedVertexBuffers = null;
  5787. };
  5788. Engine.prototype.createVertexBuffer = function (vertices) {
  5789. var vbo = this._gl.createBuffer();
  5790. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5791. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  5792. this._resetVertexBufferBinding();
  5793. vbo.references = 1;
  5794. return vbo;
  5795. };
  5796. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  5797. var vbo = this._gl.createBuffer();
  5798. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  5799. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5800. this._resetVertexBufferBinding();
  5801. vbo.references = 1;
  5802. return vbo;
  5803. };
  5804. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  5805. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5806. if (offset === undefined) {
  5807. offset = 0;
  5808. }
  5809. if (vertices instanceof Float32Array) {
  5810. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  5811. }
  5812. else {
  5813. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  5814. }
  5815. this._resetVertexBufferBinding();
  5816. };
  5817. Engine.prototype._resetIndexBufferBinding = function () {
  5818. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  5819. this._cachedIndexBuffer = null;
  5820. };
  5821. Engine.prototype.createIndexBuffer = function (indices) {
  5822. var vbo = this._gl.createBuffer();
  5823. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  5824. // Check for 32 bits indices
  5825. var arrayBuffer;
  5826. var need32Bits = false;
  5827. if (this._caps.uintIndices) {
  5828. for (var index = 0; index < indices.length; index++) {
  5829. if (indices[index] > 65535) {
  5830. need32Bits = true;
  5831. break;
  5832. }
  5833. }
  5834. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  5835. }
  5836. else {
  5837. arrayBuffer = new Uint16Array(indices);
  5838. }
  5839. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  5840. this._resetIndexBufferBinding();
  5841. vbo.references = 1;
  5842. vbo.is32Bits = need32Bits;
  5843. return vbo;
  5844. };
  5845. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  5846. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  5847. this._cachedVertexBuffers = vertexBuffer;
  5848. this._cachedEffectForVertexBuffers = effect;
  5849. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  5850. var offset = 0;
  5851. for (var index = 0; index < vertexDeclaration.length; index++) {
  5852. var order = effect.getAttributeLocation(index);
  5853. if (order >= 0) {
  5854. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  5855. }
  5856. offset += vertexDeclaration[index] * 4;
  5857. }
  5858. }
  5859. if (this._cachedIndexBuffer !== indexBuffer) {
  5860. this._cachedIndexBuffer = indexBuffer;
  5861. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5862. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5863. }
  5864. };
  5865. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  5866. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  5867. this._cachedVertexBuffers = vertexBuffers;
  5868. this._cachedEffectForVertexBuffers = effect;
  5869. var attributes = effect.getAttributesNames();
  5870. for (var index = 0; index < attributes.length; index++) {
  5871. var order = effect.getAttributeLocation(index);
  5872. if (order >= 0) {
  5873. var vertexBuffer = vertexBuffers[attributes[index]];
  5874. if (!vertexBuffer) {
  5875. continue;
  5876. }
  5877. var stride = vertexBuffer.getStrideSize();
  5878. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  5879. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  5880. }
  5881. }
  5882. }
  5883. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  5884. this._cachedIndexBuffer = indexBuffer;
  5885. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  5886. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  5887. }
  5888. };
  5889. Engine.prototype._releaseBuffer = function (buffer) {
  5890. buffer.references--;
  5891. if (buffer.references === 0) {
  5892. this._gl.deleteBuffer(buffer);
  5893. return true;
  5894. }
  5895. return false;
  5896. };
  5897. Engine.prototype.createInstancesBuffer = function (capacity) {
  5898. var buffer = this._gl.createBuffer();
  5899. buffer.capacity = capacity;
  5900. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  5901. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  5902. return buffer;
  5903. };
  5904. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  5905. this._gl.deleteBuffer(buffer);
  5906. };
  5907. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  5908. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5909. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  5910. for (var index = 0; index < 4; index++) {
  5911. var offsetLocation = offsetLocations[index];
  5912. this._gl.enableVertexAttribArray(offsetLocation);
  5913. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  5914. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  5915. }
  5916. };
  5917. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  5918. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  5919. for (var index = 0; index < 4; index++) {
  5920. var offsetLocation = offsetLocations[index];
  5921. this._gl.disableVertexAttribArray(offsetLocation);
  5922. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  5923. }
  5924. };
  5925. Engine.prototype.applyStates = function () {
  5926. this._depthCullingState.apply(this._gl);
  5927. this._alphaState.apply(this._gl);
  5928. };
  5929. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  5930. // Apply states
  5931. this.applyStates();
  5932. this._drawCalls++;
  5933. // Render
  5934. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  5935. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  5936. if (instancesCount) {
  5937. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  5938. return;
  5939. }
  5940. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  5941. };
  5942. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  5943. // Apply states
  5944. this.applyStates();
  5945. this._drawCalls++;
  5946. if (instancesCount) {
  5947. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  5948. return;
  5949. }
  5950. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  5951. };
  5952. // Shaders
  5953. Engine.prototype._releaseEffect = function (effect) {
  5954. if (this._compiledEffects[effect._key]) {
  5955. delete this._compiledEffects[effect._key];
  5956. if (effect.getProgram()) {
  5957. this._gl.deleteProgram(effect.getProgram());
  5958. }
  5959. }
  5960. };
  5961. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5962. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  5963. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  5964. var name = vertex + "+" + fragment + "@" + defines;
  5965. if (this._compiledEffects[name]) {
  5966. return this._compiledEffects[name];
  5967. }
  5968. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  5969. effect._key = name;
  5970. this._compiledEffects[name] = effect;
  5971. return effect;
  5972. };
  5973. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  5974. if (uniformsNames === void 0) { uniformsNames = []; }
  5975. if (samplers === void 0) { samplers = []; }
  5976. if (defines === void 0) { defines = ""; }
  5977. return this.createEffect({
  5978. vertex: "particles",
  5979. fragmentElement: fragmentName
  5980. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  5981. };
  5982. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  5983. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  5984. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  5985. var shaderProgram = this._gl.createProgram();
  5986. this._gl.attachShader(shaderProgram, vertexShader);
  5987. this._gl.attachShader(shaderProgram, fragmentShader);
  5988. this._gl.linkProgram(shaderProgram);
  5989. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  5990. if (!linked) {
  5991. var error = this._gl.getProgramInfoLog(shaderProgram);
  5992. if (error) {
  5993. throw new Error(error);
  5994. }
  5995. }
  5996. this._gl.deleteShader(vertexShader);
  5997. this._gl.deleteShader(fragmentShader);
  5998. return shaderProgram;
  5999. };
  6000. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  6001. var results = [];
  6002. for (var index = 0; index < uniformsNames.length; index++) {
  6003. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  6004. }
  6005. return results;
  6006. };
  6007. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  6008. var results = [];
  6009. for (var index = 0; index < attributesNames.length; index++) {
  6010. try {
  6011. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  6012. }
  6013. catch (e) {
  6014. results.push(-1);
  6015. }
  6016. }
  6017. return results;
  6018. };
  6019. Engine.prototype.enableEffect = function (effect) {
  6020. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  6021. if (effect && effect.onBind) {
  6022. effect.onBind(effect);
  6023. }
  6024. return;
  6025. }
  6026. this._vertexAttribArrays = this._vertexAttribArrays || [];
  6027. // Use program
  6028. this._gl.useProgram(effect.getProgram());
  6029. for (var i in this._vertexAttribArrays) {
  6030. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6031. continue;
  6032. }
  6033. this._vertexAttribArrays[i] = false;
  6034. this._gl.disableVertexAttribArray(i);
  6035. }
  6036. var attributesCount = effect.getAttributesCount();
  6037. for (var index = 0; index < attributesCount; index++) {
  6038. // Attributes
  6039. var order = effect.getAttributeLocation(index);
  6040. if (order >= 0) {
  6041. this._vertexAttribArrays[order] = true;
  6042. this._gl.enableVertexAttribArray(order);
  6043. }
  6044. }
  6045. this._currentEffect = effect;
  6046. if (effect.onBind) {
  6047. effect.onBind(effect);
  6048. }
  6049. };
  6050. Engine.prototype.setArray = function (uniform, array) {
  6051. if (!uniform)
  6052. return;
  6053. this._gl.uniform1fv(uniform, array);
  6054. };
  6055. Engine.prototype.setArray2 = function (uniform, array) {
  6056. if (!uniform || array.length % 2 !== 0)
  6057. return;
  6058. this._gl.uniform2fv(uniform, array);
  6059. };
  6060. Engine.prototype.setArray3 = function (uniform, array) {
  6061. if (!uniform || array.length % 3 !== 0)
  6062. return;
  6063. this._gl.uniform3fv(uniform, array);
  6064. };
  6065. Engine.prototype.setArray4 = function (uniform, array) {
  6066. if (!uniform || array.length % 4 !== 0)
  6067. return;
  6068. this._gl.uniform4fv(uniform, array);
  6069. };
  6070. Engine.prototype.setMatrices = function (uniform, matrices) {
  6071. if (!uniform)
  6072. return;
  6073. this._gl.uniformMatrix4fv(uniform, false, matrices);
  6074. };
  6075. Engine.prototype.setMatrix = function (uniform, matrix) {
  6076. if (!uniform)
  6077. return;
  6078. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  6079. };
  6080. Engine.prototype.setFloat = function (uniform, value) {
  6081. if (!uniform)
  6082. return;
  6083. this._gl.uniform1f(uniform, value);
  6084. };
  6085. Engine.prototype.setFloat2 = function (uniform, x, y) {
  6086. if (!uniform)
  6087. return;
  6088. this._gl.uniform2f(uniform, x, y);
  6089. };
  6090. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  6091. if (!uniform)
  6092. return;
  6093. this._gl.uniform3f(uniform, x, y, z);
  6094. };
  6095. Engine.prototype.setBool = function (uniform, bool) {
  6096. if (!uniform)
  6097. return;
  6098. this._gl.uniform1i(uniform, bool);
  6099. };
  6100. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  6101. if (!uniform)
  6102. return;
  6103. this._gl.uniform4f(uniform, x, y, z, w);
  6104. };
  6105. Engine.prototype.setColor3 = function (uniform, color3) {
  6106. if (!uniform)
  6107. return;
  6108. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  6109. };
  6110. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  6111. if (!uniform)
  6112. return;
  6113. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  6114. };
  6115. // States
  6116. Engine.prototype.setState = function (culling, zOffset, force) {
  6117. if (zOffset === void 0) { zOffset = 0; }
  6118. // Culling
  6119. if (this._depthCullingState.cull !== culling || force) {
  6120. if (culling) {
  6121. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  6122. this._depthCullingState.cull = true;
  6123. }
  6124. else {
  6125. this._depthCullingState.cull = false;
  6126. }
  6127. }
  6128. // Z offset
  6129. this._depthCullingState.zOffset = zOffset;
  6130. };
  6131. Engine.prototype.setDepthBuffer = function (enable) {
  6132. this._depthCullingState.depthTest = enable;
  6133. };
  6134. Engine.prototype.getDepthWrite = function () {
  6135. return this._depthCullingState.depthMask;
  6136. };
  6137. Engine.prototype.setDepthWrite = function (enable) {
  6138. this._depthCullingState.depthMask = enable;
  6139. };
  6140. Engine.prototype.setColorWrite = function (enable) {
  6141. this._gl.colorMask(enable, enable, enable, enable);
  6142. };
  6143. Engine.prototype.setAlphaMode = function (mode) {
  6144. switch (mode) {
  6145. case Engine.ALPHA_DISABLE:
  6146. this.setDepthWrite(true);
  6147. this._alphaState.alphaBlend = false;
  6148. break;
  6149. case Engine.ALPHA_COMBINE:
  6150. this.setDepthWrite(false);
  6151. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  6152. this._alphaState.alphaBlend = true;
  6153. break;
  6154. case Engine.ALPHA_ADD:
  6155. this.setDepthWrite(false);
  6156. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  6157. this._alphaState.alphaBlend = true;
  6158. break;
  6159. }
  6160. this._alphaMode = mode;
  6161. };
  6162. Engine.prototype.getAlphaMode = function () {
  6163. return this._alphaMode;
  6164. };
  6165. Engine.prototype.setAlphaTesting = function (enable) {
  6166. this._alphaTest = enable;
  6167. };
  6168. Engine.prototype.getAlphaTesting = function () {
  6169. return this._alphaTest;
  6170. };
  6171. // Textures
  6172. Engine.prototype.wipeCaches = function () {
  6173. this._activeTexturesCache = [];
  6174. this._currentEffect = null;
  6175. this._depthCullingState.reset();
  6176. this._alphaState.reset();
  6177. this._cachedVertexBuffers = null;
  6178. this._cachedIndexBuffer = null;
  6179. this._cachedEffectForVertexBuffers = null;
  6180. };
  6181. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  6182. var gl = this._gl;
  6183. gl.bindTexture(gl.TEXTURE_2D, texture);
  6184. var magFilter = gl.NEAREST;
  6185. var minFilter = gl.NEAREST;
  6186. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6187. magFilter = gl.LINEAR;
  6188. minFilter = gl.LINEAR;
  6189. }
  6190. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6191. magFilter = gl.LINEAR;
  6192. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6193. }
  6194. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  6195. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  6196. gl.bindTexture(gl.TEXTURE_2D, null);
  6197. texture.samplingMode = samplingMode;
  6198. };
  6199. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  6200. var _this = this;
  6201. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6202. if (onLoad === void 0) { onLoad = null; }
  6203. if (onError === void 0) { onError = null; }
  6204. if (buffer === void 0) { buffer = null; }
  6205. var texture = this._gl.createTexture();
  6206. var extension;
  6207. var fromData = false;
  6208. if (url.substr(0, 5) === "data:") {
  6209. fromData = true;
  6210. }
  6211. if (!fromData)
  6212. extension = url.substr(url.length - 4, 4).toLowerCase();
  6213. else {
  6214. var oldUrl = url;
  6215. fromData = oldUrl.split(':');
  6216. url = oldUrl;
  6217. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  6218. }
  6219. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6220. var isTGA = (extension === ".tga");
  6221. scene._addPendingData(texture);
  6222. texture.url = url;
  6223. texture.noMipmap = noMipmap;
  6224. texture.references = 1;
  6225. texture.samplingMode = samplingMode;
  6226. this._loadedTexturesCache.push(texture);
  6227. var onerror = function () {
  6228. scene._removePendingData(texture);
  6229. if (onError) {
  6230. onError();
  6231. }
  6232. };
  6233. if (isTGA) {
  6234. var callback = function (arrayBuffer) {
  6235. var data = new Uint8Array(arrayBuffer);
  6236. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  6237. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  6238. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  6239. if (onLoad) {
  6240. onLoad();
  6241. }
  6242. }, samplingMode);
  6243. };
  6244. if (!(fromData instanceof Array))
  6245. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  6246. callback(arrayBuffer);
  6247. }, onerror, scene.database, true);
  6248. else
  6249. callback(buffer);
  6250. }
  6251. else if (isDDS) {
  6252. callback = function (data) {
  6253. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6254. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  6255. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  6256. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  6257. if (onLoad) {
  6258. onLoad();
  6259. }
  6260. }, samplingMode);
  6261. };
  6262. if (!(fromData instanceof Array))
  6263. BABYLON.Tools.LoadFile(url, function (data) {
  6264. callback(data);
  6265. }, onerror, scene.database, true);
  6266. else
  6267. callback(buffer);
  6268. }
  6269. else {
  6270. var onload = function (img) {
  6271. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  6272. var isPot = (img.width === potWidth && img.height === potHeight);
  6273. if (!isPot) {
  6274. _this._prepareWorkingCanvas();
  6275. _this._workingCanvas.width = potWidth;
  6276. _this._workingCanvas.height = potHeight;
  6277. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6278. _this._workingContext.imageSmoothingEnabled = false;
  6279. _this._workingContext.mozImageSmoothingEnabled = false;
  6280. _this._workingContext.oImageSmoothingEnabled = false;
  6281. _this._workingContext.webkitImageSmoothingEnabled = false;
  6282. _this._workingContext.msImageSmoothingEnabled = false;
  6283. }
  6284. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  6285. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6286. _this._workingContext.imageSmoothingEnabled = true;
  6287. _this._workingContext.mozImageSmoothingEnabled = true;
  6288. _this._workingContext.oImageSmoothingEnabled = true;
  6289. _this._workingContext.webkitImageSmoothingEnabled = true;
  6290. _this._workingContext.msImageSmoothingEnabled = true;
  6291. }
  6292. }
  6293. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  6294. if (onLoad) {
  6295. onLoad();
  6296. }
  6297. }, samplingMode);
  6298. };
  6299. if (!(fromData instanceof Array))
  6300. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6301. else
  6302. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  6303. }
  6304. return texture;
  6305. };
  6306. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  6307. var texture = this._gl.createTexture();
  6308. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6309. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6310. // Format
  6311. var internalFormat = this._gl.RGBA;
  6312. switch (format) {
  6313. case Engine.TEXTUREFORMAT_ALPHA:
  6314. internalFormat = this._gl.ALPHA;
  6315. break;
  6316. case Engine.TEXTUREFORMAT_LUMINANCE:
  6317. internalFormat = this._gl.LUMINANCE;
  6318. break;
  6319. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  6320. internalFormat = this._gl.LUMINANCE_ALPHA;
  6321. break;
  6322. case Engine.TEXTUREFORMAT_RGB:
  6323. internalFormat = this._gl.RGB;
  6324. break;
  6325. case Engine.TEXTUREFORMAT_RGBA:
  6326. internalFormat = this._gl.RGBA;
  6327. break;
  6328. }
  6329. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  6330. if (generateMipMaps) {
  6331. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6332. }
  6333. // Filters
  6334. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  6335. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6336. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6337. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6338. this._activeTexturesCache = [];
  6339. texture._baseWidth = width;
  6340. texture._baseHeight = height;
  6341. texture._width = width;
  6342. texture._height = height;
  6343. texture.isReady = true;
  6344. texture.references = 1;
  6345. texture.samplingMode = samplingMode;
  6346. this._loadedTexturesCache.push(texture);
  6347. return texture;
  6348. };
  6349. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode, forceExponantOfTwo) {
  6350. if (forceExponantOfTwo === void 0) { forceExponantOfTwo = true; }
  6351. var texture = this._gl.createTexture();
  6352. texture._baseWidth = width;
  6353. texture._baseHeight = height;
  6354. if (forceExponantOfTwo) {
  6355. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  6356. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  6357. }
  6358. this._activeTexturesCache = [];
  6359. texture._width = width;
  6360. texture._height = height;
  6361. texture.isReady = false;
  6362. texture.generateMipMaps = generateMipMaps;
  6363. texture.references = 1;
  6364. texture.samplingMode = samplingMode;
  6365. this.updateTextureSamplingMode(samplingMode, texture);
  6366. this._loadedTexturesCache.push(texture);
  6367. return texture;
  6368. };
  6369. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  6370. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  6371. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6372. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  6373. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  6374. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6375. };
  6376. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  6377. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6378. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  6379. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  6380. if (texture.generateMipMaps) {
  6381. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6382. }
  6383. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6384. this._activeTexturesCache = [];
  6385. texture.isReady = true;
  6386. };
  6387. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  6388. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6389. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  6390. // Testing video texture support
  6391. if (this._videoTextureSupported === undefined) {
  6392. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6393. if (this._gl.getError() !== 0) {
  6394. this._videoTextureSupported = false;
  6395. }
  6396. else {
  6397. this._videoTextureSupported = true;
  6398. }
  6399. }
  6400. // Copy video through the current working canvas if video texture is not supported
  6401. if (!this._videoTextureSupported) {
  6402. if (!texture._workingCanvas) {
  6403. texture._workingCanvas = document.createElement("canvas");
  6404. texture._workingContext = texture._workingCanvas.getContext("2d");
  6405. texture._workingCanvas.width = texture._width;
  6406. texture._workingCanvas.height = texture._height;
  6407. }
  6408. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  6409. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  6410. }
  6411. else {
  6412. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  6413. }
  6414. if (texture.generateMipMaps) {
  6415. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6416. }
  6417. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6418. this._activeTexturesCache = [];
  6419. texture.isReady = true;
  6420. };
  6421. Engine.prototype.createRenderTargetTexture = function (size, options) {
  6422. // old version had a "generateMipMaps" arg instead of options.
  6423. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  6424. // in the same way, generateDepthBuffer is defaulted to true
  6425. var generateMipMaps = false;
  6426. var generateDepthBuffer = true;
  6427. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6428. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  6429. if (options !== undefined) {
  6430. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  6431. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  6432. type = options.type === undefined ? type : options.type;
  6433. if (options.samplingMode !== undefined) {
  6434. samplingMode = options.samplingMode;
  6435. }
  6436. if (type === Engine.TEXTURETYPE_FLOAT) {
  6437. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  6438. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  6439. }
  6440. }
  6441. var gl = this._gl;
  6442. var texture = gl.createTexture();
  6443. gl.bindTexture(gl.TEXTURE_2D, texture);
  6444. var width = size.width || size;
  6445. var height = size.height || size;
  6446. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  6447. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  6448. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  6449. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  6450. }
  6451. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6452. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6453. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6454. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6455. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  6456. var depthBuffer;
  6457. // Create the depth buffer
  6458. if (generateDepthBuffer) {
  6459. depthBuffer = gl.createRenderbuffer();
  6460. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  6461. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  6462. }
  6463. // Create the framebuffer
  6464. var framebuffer = gl.createFramebuffer();
  6465. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  6466. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  6467. if (generateDepthBuffer) {
  6468. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  6469. }
  6470. if (generateMipMaps) {
  6471. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  6472. }
  6473. // Unbind
  6474. gl.bindTexture(gl.TEXTURE_2D, null);
  6475. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  6476. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  6477. texture._framebuffer = framebuffer;
  6478. if (generateDepthBuffer) {
  6479. texture._depthBuffer = depthBuffer;
  6480. }
  6481. texture._width = width;
  6482. texture._height = height;
  6483. texture.isReady = true;
  6484. texture.generateMipMaps = generateMipMaps;
  6485. texture.references = 1;
  6486. texture.samplingMode = samplingMode;
  6487. this._activeTexturesCache = [];
  6488. this._loadedTexturesCache.push(texture);
  6489. return texture;
  6490. };
  6491. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  6492. var _this = this;
  6493. var gl = this._gl;
  6494. var texture = gl.createTexture();
  6495. texture.isCube = true;
  6496. texture.url = rootUrl;
  6497. texture.references = 1;
  6498. this._loadedTexturesCache.push(texture);
  6499. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  6500. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  6501. if (isDDS) {
  6502. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  6503. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  6504. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  6505. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6506. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  6507. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  6508. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  6509. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6510. }
  6511. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6512. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  6513. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6514. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6515. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6516. _this._activeTexturesCache = [];
  6517. texture._width = info.width;
  6518. texture._height = info.height;
  6519. texture.isReady = true;
  6520. }, null, null, true);
  6521. }
  6522. else {
  6523. cascadeLoad(rootUrl, scene, function (imgs) {
  6524. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  6525. var height = width;
  6526. _this._prepareWorkingCanvas();
  6527. _this._workingCanvas.width = width;
  6528. _this._workingCanvas.height = height;
  6529. var faces = [
  6530. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  6531. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  6532. ];
  6533. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  6534. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  6535. for (var index = 0; index < faces.length; index++) {
  6536. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  6537. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  6538. }
  6539. if (!noMipmap) {
  6540. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  6541. }
  6542. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  6543. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  6544. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  6545. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  6546. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  6547. _this._activeTexturesCache = [];
  6548. texture._width = width;
  6549. texture._height = height;
  6550. texture.isReady = true;
  6551. }, extensions);
  6552. }
  6553. return texture;
  6554. };
  6555. Engine.prototype._releaseTexture = function (texture) {
  6556. var gl = this._gl;
  6557. if (texture._framebuffer) {
  6558. gl.deleteFramebuffer(texture._framebuffer);
  6559. }
  6560. if (texture._depthBuffer) {
  6561. gl.deleteRenderbuffer(texture._depthBuffer);
  6562. }
  6563. gl.deleteTexture(texture);
  6564. // Unbind channels
  6565. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  6566. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6567. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6568. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6569. this._activeTexturesCache[channel] = null;
  6570. }
  6571. var index = this._loadedTexturesCache.indexOf(texture);
  6572. if (index !== -1) {
  6573. this._loadedTexturesCache.splice(index, 1);
  6574. }
  6575. };
  6576. Engine.prototype.bindSamplers = function (effect) {
  6577. this._gl.useProgram(effect.getProgram());
  6578. var samplers = effect.getSamplers();
  6579. for (var index = 0; index < samplers.length; index++) {
  6580. var uniform = effect.getUniform(samplers[index]);
  6581. this._gl.uniform1i(uniform, index);
  6582. }
  6583. this._currentEffect = null;
  6584. };
  6585. Engine.prototype._bindTexture = function (channel, texture) {
  6586. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6587. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  6588. this._activeTexturesCache[channel] = null;
  6589. };
  6590. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  6591. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  6592. };
  6593. Engine.prototype.setTexture = function (channel, texture) {
  6594. if (channel < 0) {
  6595. return;
  6596. }
  6597. // Not ready?
  6598. if (!texture || !texture.isReady()) {
  6599. if (this._activeTexturesCache[channel] != null) {
  6600. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6601. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  6602. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  6603. this._activeTexturesCache[channel] = null;
  6604. }
  6605. return;
  6606. }
  6607. // Video
  6608. if (texture instanceof BABYLON.VideoTexture) {
  6609. if (texture.update()) {
  6610. this._activeTexturesCache[channel] = null;
  6611. }
  6612. }
  6613. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  6614. texture.delayLoad();
  6615. return;
  6616. }
  6617. if (this._activeTexturesCache[channel] === texture) {
  6618. return;
  6619. }
  6620. this._activeTexturesCache[channel] = texture;
  6621. var internalTexture = texture.getInternalTexture();
  6622. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  6623. if (internalTexture.isCube) {
  6624. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  6625. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  6626. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  6627. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  6628. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  6629. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  6630. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  6631. }
  6632. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  6633. }
  6634. else {
  6635. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  6636. if (internalTexture._cachedWrapU !== texture.wrapU) {
  6637. internalTexture._cachedWrapU = texture.wrapU;
  6638. switch (texture.wrapU) {
  6639. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6640. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  6641. break;
  6642. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6643. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  6644. break;
  6645. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6646. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  6647. break;
  6648. }
  6649. }
  6650. if (internalTexture._cachedWrapV !== texture.wrapV) {
  6651. internalTexture._cachedWrapV = texture.wrapV;
  6652. switch (texture.wrapV) {
  6653. case BABYLON.Texture.WRAP_ADDRESSMODE:
  6654. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  6655. break;
  6656. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  6657. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  6658. break;
  6659. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  6660. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  6661. break;
  6662. }
  6663. }
  6664. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  6665. }
  6666. };
  6667. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  6668. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  6669. var value = texture.anisotropicFilteringLevel;
  6670. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6671. value = 1;
  6672. }
  6673. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  6674. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  6675. texture._cachedAnisotropicFilteringLevel = value;
  6676. }
  6677. };
  6678. Engine.prototype.readPixels = function (x, y, width, height) {
  6679. var data = new Uint8Array(height * width * 4);
  6680. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  6681. return data;
  6682. };
  6683. // Dispose
  6684. Engine.prototype.dispose = function () {
  6685. this.hideLoadingUI();
  6686. this.stopRenderLoop();
  6687. // Release scenes
  6688. while (this.scenes.length) {
  6689. this.scenes[0].dispose();
  6690. }
  6691. // Release audio engine
  6692. Engine.audioEngine.dispose();
  6693. // Release effects
  6694. for (var name in this._compiledEffects) {
  6695. this._gl.deleteProgram(this._compiledEffects[name]._program);
  6696. }
  6697. // Unbind
  6698. for (var i in this._vertexAttribArrays) {
  6699. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  6700. continue;
  6701. }
  6702. this._gl.disableVertexAttribArray(i);
  6703. }
  6704. this._gl = null;
  6705. // Events
  6706. window.removeEventListener("blur", this._onBlur);
  6707. window.removeEventListener("focus", this._onFocus);
  6708. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  6709. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  6710. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  6711. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  6712. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  6713. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  6714. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  6715. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  6716. };
  6717. // Loading screen
  6718. Engine.prototype.displayLoadingUI = function () {
  6719. var _this = this;
  6720. this._loadingDiv = document.createElement("div");
  6721. this._loadingDiv.style.opacity = "0";
  6722. this._loadingDiv.style.transition = "opacity 1.5s ease";
  6723. // Loading text
  6724. this._loadingTextDiv = document.createElement("div");
  6725. this._loadingTextDiv.style.position = "absolute";
  6726. this._loadingTextDiv.style.left = "0";
  6727. this._loadingTextDiv.style.top = "50%";
  6728. this._loadingTextDiv.style.marginTop = "80px";
  6729. this._loadingTextDiv.style.width = "100%";
  6730. this._loadingTextDiv.style.height = "20px";
  6731. this._loadingTextDiv.style.fontFamily = "Arial";
  6732. this._loadingTextDiv.style.fontSize = "14px";
  6733. this._loadingTextDiv.style.color = "white";
  6734. this._loadingTextDiv.style.textAlign = "center";
  6735. this._loadingTextDiv.innerHTML = "Loading";
  6736. this._loadingDiv.appendChild(this._loadingTextDiv);
  6737. // Loading img
  6738. var imgBack = new Image();
  6739. 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==";
  6740. imgBack.style.position = "absolute";
  6741. imgBack.style.left = "50%";
  6742. imgBack.style.top = "50%";
  6743. imgBack.style.marginLeft = "-50px";
  6744. imgBack.style.marginTop = "-50px";
  6745. imgBack.style.transition = "transform 1.0s ease";
  6746. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  6747. var deg = 360;
  6748. var onTransitionEnd = function () {
  6749. deg += 360;
  6750. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  6751. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  6752. };
  6753. imgBack.addEventListener("transitionend", onTransitionEnd);
  6754. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  6755. this._loadingDiv.appendChild(imgBack);
  6756. // front image
  6757. var imgFront = new Image();
  6758. 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=";
  6759. imgFront.style.position = "absolute";
  6760. imgFront.style.left = "50%";
  6761. imgFront.style.top = "50%";
  6762. imgFront.style.marginLeft = "-50px";
  6763. imgFront.style.marginTop = "-50px";
  6764. this._loadingDiv.appendChild(imgFront);
  6765. // Resize
  6766. this._resizeLoadingUI = function () {
  6767. var canvasRect = _this.getRenderingCanvasClientRect();
  6768. _this._loadingDiv.style.position = "absolute";
  6769. _this._loadingDiv.style.left = canvasRect.left + "px";
  6770. _this._loadingDiv.style.top = canvasRect.top + "px";
  6771. _this._loadingDiv.style.width = canvasRect.width + "px";
  6772. _this._loadingDiv.style.height = canvasRect.height + "px";
  6773. };
  6774. this._resizeLoadingUI();
  6775. window.addEventListener("resize", this._resizeLoadingUI);
  6776. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6777. document.body.appendChild(this._loadingDiv);
  6778. setTimeout(function () {
  6779. _this._loadingDiv.style.opacity = "1";
  6780. imgBack.style.transform = "rotateZ(360deg)";
  6781. imgBack.style.webkitTransform = "rotateZ(360deg)";
  6782. }, 0);
  6783. };
  6784. Object.defineProperty(Engine.prototype, "loadingUIText", {
  6785. set: function (text) {
  6786. if (!this._loadingDiv) {
  6787. return;
  6788. }
  6789. this._loadingTextDiv.innerHTML = text;
  6790. },
  6791. enumerable: true,
  6792. configurable: true
  6793. });
  6794. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  6795. get: function () {
  6796. return this._loadingDivBackgroundColor;
  6797. },
  6798. set: function (color) {
  6799. this._loadingDivBackgroundColor = color;
  6800. if (!this._loadingDiv) {
  6801. return;
  6802. }
  6803. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  6804. },
  6805. enumerable: true,
  6806. configurable: true
  6807. });
  6808. Engine.prototype.hideLoadingUI = function () {
  6809. var _this = this;
  6810. if (!this._loadingDiv) {
  6811. return;
  6812. }
  6813. var onTransitionEnd = function () {
  6814. if (!_this._loadingDiv) {
  6815. return;
  6816. }
  6817. document.body.removeChild(_this._loadingDiv);
  6818. window.removeEventListener("resize", _this._resizeLoadingUI);
  6819. _this._loadingDiv = null;
  6820. };
  6821. this._loadingDiv.style.opacity = "0";
  6822. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  6823. };
  6824. // FPS
  6825. Engine.prototype.getFps = function () {
  6826. return this.fps;
  6827. };
  6828. Engine.prototype.getDeltaTime = function () {
  6829. return this.deltaTime;
  6830. };
  6831. Engine.prototype._measureFps = function () {
  6832. this.previousFramesDuration.push(BABYLON.Tools.Now);
  6833. var length = this.previousFramesDuration.length;
  6834. if (length >= 2) {
  6835. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  6836. }
  6837. if (length >= this.fpsRange) {
  6838. if (length > this.fpsRange) {
  6839. this.previousFramesDuration.splice(0, 1);
  6840. length = this.previousFramesDuration.length;
  6841. }
  6842. var sum = 0;
  6843. for (var id = 0; id < length - 1; id++) {
  6844. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  6845. }
  6846. this.fps = 1000.0 / (sum / (length - 1));
  6847. }
  6848. };
  6849. // Statics
  6850. Engine.isSupported = function () {
  6851. try {
  6852. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  6853. if (navigator.isCocoonJS) {
  6854. return true;
  6855. }
  6856. var tempcanvas = document.createElement("canvas");
  6857. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  6858. return gl != null && !!window.WebGLRenderingContext;
  6859. }
  6860. catch (e) {
  6861. return false;
  6862. }
  6863. };
  6864. // Const statics
  6865. Engine._ALPHA_DISABLE = 0;
  6866. Engine._ALPHA_ADD = 1;
  6867. Engine._ALPHA_COMBINE = 2;
  6868. Engine._DELAYLOADSTATE_NONE = 0;
  6869. Engine._DELAYLOADSTATE_LOADED = 1;
  6870. Engine._DELAYLOADSTATE_LOADING = 2;
  6871. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  6872. Engine._TEXTUREFORMAT_ALPHA = 0;
  6873. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  6874. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  6875. Engine._TEXTUREFORMAT_RGB = 4;
  6876. Engine._TEXTUREFORMAT_RGBA = 4;
  6877. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  6878. Engine._TEXTURETYPE_FLOAT = 1;
  6879. // Updatable statics so stick with vars here
  6880. Engine.Epsilon = 0.001;
  6881. Engine.CollisionsEpsilon = 0.001;
  6882. Engine.CodeRepository = "Babylon/";
  6883. Engine.ShadersRepository = "Babylon/Shaders/";
  6884. return Engine;
  6885. })();
  6886. BABYLON.Engine = Engine;
  6887. })(BABYLON || (BABYLON = {}));
  6888. //# sourceMappingURL=babylon.engine.js.map
  6889. var BABYLON;
  6890. (function (BABYLON) {
  6891. /**
  6892. * Node is the basic class for all scene objects (Mesh, Light Camera).
  6893. */
  6894. var Node = (function () {
  6895. /**
  6896. * @constructor
  6897. * @param {string} name - the name and id to be given to this node
  6898. * @param {BABYLON.Scene} the scene this node will be added to
  6899. */
  6900. function Node(name, scene) {
  6901. this.state = "";
  6902. this.animations = new Array();
  6903. this._childrenFlag = -1;
  6904. this._isEnabled = true;
  6905. this._isReady = true;
  6906. this._currentRenderId = -1;
  6907. this._parentRenderId = -1;
  6908. this.name = name;
  6909. this.id = name;
  6910. this._scene = scene;
  6911. this._initCache();
  6912. }
  6913. Node.prototype.getScene = function () {
  6914. return this._scene;
  6915. };
  6916. Node.prototype.getEngine = function () {
  6917. return this._scene.getEngine();
  6918. };
  6919. // override it in derived class
  6920. Node.prototype.getWorldMatrix = function () {
  6921. return BABYLON.Matrix.Identity();
  6922. };
  6923. // override it in derived class if you add new variables to the cache
  6924. // and call the parent class method
  6925. Node.prototype._initCache = function () {
  6926. this._cache = {};
  6927. this._cache.parent = undefined;
  6928. };
  6929. Node.prototype.updateCache = function (force) {
  6930. if (!force && this.isSynchronized())
  6931. return;
  6932. this._cache.parent = this.parent;
  6933. this._updateCache();
  6934. };
  6935. // override it in derived class if you add new variables to the cache
  6936. // and call the parent class method if !ignoreParentClass
  6937. Node.prototype._updateCache = function (ignoreParentClass) {
  6938. };
  6939. // override it in derived class if you add new variables to the cache
  6940. Node.prototype._isSynchronized = function () {
  6941. return true;
  6942. };
  6943. Node.prototype._markSyncedWithParent = function () {
  6944. this._parentRenderId = this.parent._currentRenderId;
  6945. };
  6946. Node.prototype.isSynchronizedWithParent = function () {
  6947. if (!this.parent) {
  6948. return true;
  6949. }
  6950. if (this._parentRenderId !== this.parent._currentRenderId) {
  6951. return false;
  6952. }
  6953. return this.parent.isSynchronized();
  6954. };
  6955. Node.prototype.isSynchronized = function (updateCache) {
  6956. var check = this.hasNewParent();
  6957. check = check || !this.isSynchronizedWithParent();
  6958. check = check || !this._isSynchronized();
  6959. if (updateCache)
  6960. this.updateCache(true);
  6961. return !check;
  6962. };
  6963. Node.prototype.hasNewParent = function (update) {
  6964. if (this._cache.parent === this.parent)
  6965. return false;
  6966. if (update)
  6967. this._cache.parent = this.parent;
  6968. return true;
  6969. };
  6970. /**
  6971. * Is this node ready to be used/rendered
  6972. * @return {boolean} is it ready
  6973. */
  6974. Node.prototype.isReady = function () {
  6975. return this._isReady;
  6976. };
  6977. /**
  6978. * Is this node enabled.
  6979. * If the node has a parent and is enabled, the parent will be inspected as well.
  6980. * @return {boolean} whether this node (and its parent) is enabled.
  6981. * @see setEnabled
  6982. */
  6983. Node.prototype.isEnabled = function () {
  6984. if (!this._isEnabled) {
  6985. return false;
  6986. }
  6987. if (this.parent) {
  6988. return this.parent.isEnabled();
  6989. }
  6990. return true;
  6991. };
  6992. /**
  6993. * Set the enabled state of this node.
  6994. * @param {boolean} value - the new enabled state
  6995. * @see isEnabled
  6996. */
  6997. Node.prototype.setEnabled = function (value) {
  6998. this._isEnabled = value;
  6999. };
  7000. /**
  7001. * Is this node a descendant of the given node.
  7002. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  7003. * @param {BABYLON.Node} ancestor - The parent node to inspect
  7004. * @see parent
  7005. */
  7006. Node.prototype.isDescendantOf = function (ancestor) {
  7007. if (this.parent) {
  7008. if (this.parent === ancestor) {
  7009. return true;
  7010. }
  7011. return this.parent.isDescendantOf(ancestor);
  7012. }
  7013. return false;
  7014. };
  7015. Node.prototype._getDescendants = function (list, results) {
  7016. for (var index = 0; index < list.length; index++) {
  7017. var item = list[index];
  7018. if (item.isDescendantOf(this)) {
  7019. results.push(item);
  7020. }
  7021. }
  7022. };
  7023. /**
  7024. * Will return all nodes that have this node as parent.
  7025. * @return {BABYLON.Node[]} all children nodes of all types.
  7026. */
  7027. Node.prototype.getDescendants = function () {
  7028. var results = [];
  7029. this._getDescendants(this._scene.meshes, results);
  7030. this._getDescendants(this._scene.lights, results);
  7031. this._getDescendants(this._scene.cameras, results);
  7032. return results;
  7033. };
  7034. Node.prototype._setReady = function (state) {
  7035. if (state == this._isReady) {
  7036. return;
  7037. }
  7038. if (!state) {
  7039. this._isReady = false;
  7040. return;
  7041. }
  7042. this._isReady = true;
  7043. if (this.onReady) {
  7044. this.onReady(this);
  7045. }
  7046. };
  7047. return Node;
  7048. })();
  7049. BABYLON.Node = Node;
  7050. })(BABYLON || (BABYLON = {}));
  7051. //# sourceMappingURL=babylon.node.js.map
  7052. var BABYLON;
  7053. (function (BABYLON) {
  7054. var FilesInput = (function () {
  7055. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  7056. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  7057. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  7058. this._engine = p_engine;
  7059. this._canvas = p_canvas;
  7060. this._currentScene = p_scene;
  7061. this._sceneLoadedCallback = p_sceneLoadedCallback;
  7062. this._progressCallback = p_progressCallback;
  7063. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  7064. this._textureLoadingCallback = p_textureLoadingCallback;
  7065. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  7066. }
  7067. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  7068. var _this = this;
  7069. if (p_elementToMonitor) {
  7070. this._elementToMonitor = p_elementToMonitor;
  7071. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  7072. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  7073. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  7074. }
  7075. };
  7076. FilesInput.prototype.renderFunction = function () {
  7077. if (this._additionnalRenderLoopLogicCallback) {
  7078. this._additionnalRenderLoopLogicCallback();
  7079. }
  7080. if (this._currentScene) {
  7081. if (this._textureLoadingCallback) {
  7082. var remaining = this._currentScene.getWaitingItemsCount();
  7083. if (remaining > 0) {
  7084. this._textureLoadingCallback(remaining);
  7085. }
  7086. }
  7087. this._currentScene.render();
  7088. }
  7089. };
  7090. FilesInput.prototype.drag = function (e) {
  7091. e.stopPropagation();
  7092. e.preventDefault();
  7093. };
  7094. FilesInput.prototype.drop = function (eventDrop) {
  7095. eventDrop.stopPropagation();
  7096. eventDrop.preventDefault();
  7097. this.loadFiles(eventDrop);
  7098. };
  7099. FilesInput.prototype.loadFiles = function (event) {
  7100. if (this._startingProcessingFilesCallback)
  7101. this._startingProcessingFilesCallback();
  7102. // Handling data transfer via drag'n'drop
  7103. if (event && event.dataTransfer && event.dataTransfer.files) {
  7104. this._filesToLoad = event.dataTransfer.files;
  7105. }
  7106. // Handling files from input files
  7107. if (event && event.target && event.target.files) {
  7108. this._filesToLoad = event.target.files;
  7109. }
  7110. if (this._filesToLoad && this._filesToLoad.length > 0) {
  7111. for (var i = 0; i < this._filesToLoad.length; i++) {
  7112. switch (this._filesToLoad[i].type) {
  7113. case "image/jpeg":
  7114. case "image/png":
  7115. case "image/bmp":
  7116. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  7117. break;
  7118. case "image/targa":
  7119. case "image/vnd.ms-dds":
  7120. case "audio/wav":
  7121. case "audio/x-wav":
  7122. case "audio/mp3":
  7123. case "audio/mpeg":
  7124. case "audio/mpeg3":
  7125. case "audio/x-mpeg-3":
  7126. case "audio/ogg":
  7127. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  7128. break;
  7129. default:
  7130. if (this._filesToLoad[i].name.indexOf(".babylon") !== -1 && this._filesToLoad[i].name.indexOf(".manifest") === -1
  7131. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  7132. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  7133. this._sceneFileToLoad = this._filesToLoad[i];
  7134. }
  7135. break;
  7136. }
  7137. }
  7138. this.reload();
  7139. }
  7140. };
  7141. FilesInput.prototype.reload = function () {
  7142. var _this = this;
  7143. var that = this;
  7144. // If a ".babylon" file has been provided
  7145. if (this._sceneFileToLoad) {
  7146. if (this._currentScene) {
  7147. this._engine.stopRenderLoop();
  7148. this._currentScene.dispose();
  7149. }
  7150. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  7151. that._currentScene = newScene;
  7152. // Wait for textures and shaders to be ready
  7153. that._currentScene.executeWhenReady(function () {
  7154. // Attach camera to canvas inputs
  7155. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  7156. that._currentScene.createDefaultCameraOrLight();
  7157. }
  7158. that._currentScene.activeCamera.attachControl(that._canvas);
  7159. if (that._sceneLoadedCallback) {
  7160. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  7161. }
  7162. that._engine.runRenderLoop(function () { that.renderFunction(); });
  7163. });
  7164. }, function (progress) {
  7165. if (_this._progressCallback) {
  7166. _this._progressCallback(progress);
  7167. }
  7168. });
  7169. }
  7170. else {
  7171. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  7172. }
  7173. };
  7174. FilesInput.FilesTextures = new Array();
  7175. FilesInput.FilesToLoad = new Array();
  7176. return FilesInput;
  7177. })();
  7178. BABYLON.FilesInput = FilesInput;
  7179. })(BABYLON || (BABYLON = {}));
  7180. //# sourceMappingURL=babylon.filesInput.js.map
  7181. var BABYLON;
  7182. (function (BABYLON) {
  7183. var IntersectionInfo = (function () {
  7184. function IntersectionInfo(bu, bv, distance) {
  7185. this.bu = bu;
  7186. this.bv = bv;
  7187. this.distance = distance;
  7188. this.faceId = 0;
  7189. this.subMeshId = 0;
  7190. }
  7191. return IntersectionInfo;
  7192. })();
  7193. BABYLON.IntersectionInfo = IntersectionInfo;
  7194. var PickingInfo = (function () {
  7195. function PickingInfo() {
  7196. this.hit = false;
  7197. this.distance = 0;
  7198. this.pickedPoint = null;
  7199. this.pickedMesh = null;
  7200. this.bu = 0;
  7201. this.bv = 0;
  7202. this.faceId = -1;
  7203. this.subMeshId = 0;
  7204. }
  7205. // Methods
  7206. PickingInfo.prototype.getNormal = function (useWorldCoordinates) {
  7207. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  7208. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  7209. return null;
  7210. }
  7211. var indices = this.pickedMesh.getIndices();
  7212. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  7213. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  7214. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  7215. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  7216. normal0 = normal0.scale(this.bu);
  7217. normal1 = normal1.scale(this.bv);
  7218. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  7219. var result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  7220. if (useWorldCoordinates) {
  7221. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  7222. }
  7223. return result;
  7224. };
  7225. PickingInfo.prototype.getTextureCoordinates = function () {
  7226. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  7227. return null;
  7228. }
  7229. var indices = this.pickedMesh.getIndices();
  7230. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  7231. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  7232. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  7233. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  7234. uv0 = uv0.scale(this.bu);
  7235. uv1 = uv1.scale(this.bv);
  7236. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  7237. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  7238. };
  7239. return PickingInfo;
  7240. })();
  7241. BABYLON.PickingInfo = PickingInfo;
  7242. })(BABYLON || (BABYLON = {}));
  7243. //# sourceMappingURL=babylon.pickingInfo.js.map
  7244. var BABYLON;
  7245. (function (BABYLON) {
  7246. var BoundingSphere = (function () {
  7247. function BoundingSphere(minimum, maximum) {
  7248. this.minimum = minimum;
  7249. this.maximum = maximum;
  7250. this._tempRadiusVector = BABYLON.Vector3.Zero();
  7251. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  7252. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  7253. this.radius = distance * 0.5;
  7254. this.centerWorld = BABYLON.Vector3.Zero();
  7255. this._update(BABYLON.Matrix.Identity());
  7256. }
  7257. // Methods
  7258. BoundingSphere.prototype._update = function (world) {
  7259. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  7260. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  7261. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  7262. };
  7263. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  7264. for (var i = 0; i < 6; i++) {
  7265. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  7266. return false;
  7267. }
  7268. return true;
  7269. };
  7270. BoundingSphere.prototype.intersectsPoint = function (point) {
  7271. var x = this.centerWorld.x - point.x;
  7272. var y = this.centerWorld.y - point.y;
  7273. var z = this.centerWorld.z - point.z;
  7274. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7275. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  7276. return false;
  7277. return true;
  7278. };
  7279. // Statics
  7280. BoundingSphere.Intersects = function (sphere0, sphere1) {
  7281. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  7282. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  7283. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  7284. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  7285. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  7286. return false;
  7287. return true;
  7288. };
  7289. return BoundingSphere;
  7290. })();
  7291. BABYLON.BoundingSphere = BoundingSphere;
  7292. })(BABYLON || (BABYLON = {}));
  7293. //# sourceMappingURL=babylon.boundingSphere.js.map
  7294. var BABYLON;
  7295. (function (BABYLON) {
  7296. var BoundingBox = (function () {
  7297. function BoundingBox(minimum, maximum) {
  7298. this.minimum = minimum;
  7299. this.maximum = maximum;
  7300. this.vectors = new Array();
  7301. this.vectorsWorld = new Array();
  7302. // Bounding vectors
  7303. this.vectors.push(this.minimum.clone());
  7304. this.vectors.push(this.maximum.clone());
  7305. this.vectors.push(this.minimum.clone());
  7306. this.vectors[2].x = this.maximum.x;
  7307. this.vectors.push(this.minimum.clone());
  7308. this.vectors[3].y = this.maximum.y;
  7309. this.vectors.push(this.minimum.clone());
  7310. this.vectors[4].z = this.maximum.z;
  7311. this.vectors.push(this.maximum.clone());
  7312. this.vectors[5].z = this.minimum.z;
  7313. this.vectors.push(this.maximum.clone());
  7314. this.vectors[6].x = this.minimum.x;
  7315. this.vectors.push(this.maximum.clone());
  7316. this.vectors[7].y = this.minimum.y;
  7317. // OBB
  7318. this.center = this.maximum.add(this.minimum).scale(0.5);
  7319. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  7320. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  7321. // World
  7322. for (var index = 0; index < this.vectors.length; index++) {
  7323. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  7324. }
  7325. this.minimumWorld = BABYLON.Vector3.Zero();
  7326. this.maximumWorld = BABYLON.Vector3.Zero();
  7327. this._update(BABYLON.Matrix.Identity());
  7328. }
  7329. // Methods
  7330. BoundingBox.prototype.getWorldMatrix = function () {
  7331. return this._worldMatrix;
  7332. };
  7333. BoundingBox.prototype._update = function (world) {
  7334. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  7335. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  7336. for (var index = 0; index < this.vectors.length; index++) {
  7337. var v = this.vectorsWorld[index];
  7338. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  7339. if (v.x < this.minimumWorld.x)
  7340. this.minimumWorld.x = v.x;
  7341. if (v.y < this.minimumWorld.y)
  7342. this.minimumWorld.y = v.y;
  7343. if (v.z < this.minimumWorld.z)
  7344. this.minimumWorld.z = v.z;
  7345. if (v.x > this.maximumWorld.x)
  7346. this.maximumWorld.x = v.x;
  7347. if (v.y > this.maximumWorld.y)
  7348. this.maximumWorld.y = v.y;
  7349. if (v.z > this.maximumWorld.z)
  7350. this.maximumWorld.z = v.z;
  7351. }
  7352. // OBB
  7353. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  7354. this.center.scaleInPlace(0.5);
  7355. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  7356. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  7357. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  7358. this._worldMatrix = world;
  7359. };
  7360. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  7361. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  7362. };
  7363. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7364. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  7365. };
  7366. BoundingBox.prototype.intersectsPoint = function (point) {
  7367. var delta = -BABYLON.Engine.Epsilon;
  7368. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  7369. return false;
  7370. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  7371. return false;
  7372. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  7373. return false;
  7374. return true;
  7375. };
  7376. BoundingBox.prototype.intersectsSphere = function (sphere) {
  7377. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  7378. };
  7379. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  7380. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  7381. return false;
  7382. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  7383. return false;
  7384. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  7385. return false;
  7386. return true;
  7387. };
  7388. // Statics
  7389. BoundingBox.Intersects = function (box0, box1) {
  7390. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  7391. return false;
  7392. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  7393. return false;
  7394. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  7395. return false;
  7396. return true;
  7397. };
  7398. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  7399. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  7400. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  7401. return (num <= (sphereRadius * sphereRadius));
  7402. };
  7403. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  7404. for (var p = 0; p < 6; p++) {
  7405. for (var i = 0; i < 8; i++) {
  7406. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7407. return false;
  7408. }
  7409. }
  7410. }
  7411. return true;
  7412. };
  7413. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  7414. for (var p = 0; p < 6; p++) {
  7415. var inCount = 8;
  7416. for (var i = 0; i < 8; i++) {
  7417. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  7418. --inCount;
  7419. }
  7420. else {
  7421. break;
  7422. }
  7423. }
  7424. if (inCount === 0)
  7425. return false;
  7426. }
  7427. return true;
  7428. };
  7429. return BoundingBox;
  7430. })();
  7431. BABYLON.BoundingBox = BoundingBox;
  7432. })(BABYLON || (BABYLON = {}));
  7433. //# sourceMappingURL=babylon.boundingBox.js.map
  7434. var BABYLON;
  7435. (function (BABYLON) {
  7436. var computeBoxExtents = function (axis, box) {
  7437. var p = BABYLON.Vector3.Dot(box.center, axis);
  7438. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  7439. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  7440. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  7441. var r = r0 + r1 + r2;
  7442. return {
  7443. min: p - r,
  7444. max: p + r
  7445. };
  7446. };
  7447. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  7448. var axisOverlap = function (axis, box0, box1) {
  7449. var result0 = computeBoxExtents(axis, box0);
  7450. var result1 = computeBoxExtents(axis, box1);
  7451. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  7452. };
  7453. var BoundingInfo = (function () {
  7454. function BoundingInfo(minimum, maximum) {
  7455. this.minimum = minimum;
  7456. this.maximum = maximum;
  7457. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  7458. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  7459. }
  7460. // Methods
  7461. BoundingInfo.prototype._update = function (world) {
  7462. this.boundingBox._update(world);
  7463. this.boundingSphere._update(world);
  7464. };
  7465. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  7466. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  7467. return false;
  7468. return this.boundingBox.isInFrustum(frustumPlanes);
  7469. };
  7470. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  7471. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  7472. };
  7473. BoundingInfo.prototype._checkCollision = function (collider) {
  7474. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  7475. };
  7476. BoundingInfo.prototype.intersectsPoint = function (point) {
  7477. if (!this.boundingSphere.centerWorld) {
  7478. return false;
  7479. }
  7480. if (!this.boundingSphere.intersectsPoint(point)) {
  7481. return false;
  7482. }
  7483. if (!this.boundingBox.intersectsPoint(point)) {
  7484. return false;
  7485. }
  7486. return true;
  7487. };
  7488. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  7489. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  7490. return false;
  7491. }
  7492. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  7493. return false;
  7494. }
  7495. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  7496. return false;
  7497. }
  7498. if (!precise) {
  7499. return true;
  7500. }
  7501. var box0 = this.boundingBox;
  7502. var box1 = boundingInfo.boundingBox;
  7503. if (!axisOverlap(box0.directions[0], box0, box1))
  7504. return false;
  7505. if (!axisOverlap(box0.directions[1], box0, box1))
  7506. return false;
  7507. if (!axisOverlap(box0.directions[2], box0, box1))
  7508. return false;
  7509. if (!axisOverlap(box1.directions[0], box0, box1))
  7510. return false;
  7511. if (!axisOverlap(box1.directions[1], box0, box1))
  7512. return false;
  7513. if (!axisOverlap(box1.directions[2], box0, box1))
  7514. return false;
  7515. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  7516. return false;
  7517. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  7518. return false;
  7519. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  7520. return false;
  7521. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  7522. return false;
  7523. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  7524. return false;
  7525. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  7526. return false;
  7527. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  7528. return false;
  7529. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  7530. return false;
  7531. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  7532. return false;
  7533. return true;
  7534. };
  7535. return BoundingInfo;
  7536. })();
  7537. BABYLON.BoundingInfo = BoundingInfo;
  7538. })(BABYLON || (BABYLON = {}));
  7539. //# sourceMappingURL=babylon.boundingInfo.js.map
  7540. var BABYLON;
  7541. (function (BABYLON) {
  7542. var AbstractMesh = (function (_super) {
  7543. __extends(AbstractMesh, _super);
  7544. function AbstractMesh(name, scene) {
  7545. var _this = this;
  7546. _super.call(this, name, scene);
  7547. // Properties
  7548. this.definedFacingForward = true; // orientation for POV movement & rotation
  7549. this.position = new BABYLON.Vector3(0, 0, 0);
  7550. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7551. this.scaling = new BABYLON.Vector3(1, 1, 1);
  7552. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  7553. this.visibility = 1.0;
  7554. this.alphaIndex = Number.MAX_VALUE;
  7555. this.infiniteDistance = false;
  7556. this.isVisible = true;
  7557. this.isPickable = true;
  7558. this.showBoundingBox = false;
  7559. this.showSubMeshesBoundingBox = false;
  7560. this.onDispose = null;
  7561. this.isBlocker = false;
  7562. this.renderingGroupId = 0;
  7563. this.receiveShadows = false;
  7564. this.renderOutline = false;
  7565. this.outlineColor = BABYLON.Color3.Red();
  7566. this.outlineWidth = 0.02;
  7567. this.renderOverlay = false;
  7568. this.overlayColor = BABYLON.Color3.Red();
  7569. this.overlayAlpha = 0.5;
  7570. this.hasVertexAlpha = false;
  7571. this.useVertexColors = true;
  7572. this.applyFog = true;
  7573. this.useOctreeForRenderingSelection = true;
  7574. this.useOctreeForPicking = true;
  7575. this.useOctreeForCollisions = true;
  7576. this.layerMask = 0x0FFFFFFF;
  7577. this.alwaysSelectAsActiveMesh = false;
  7578. // Physics
  7579. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  7580. // Collisions
  7581. this._checkCollisions = false;
  7582. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7583. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  7584. this._collider = new BABYLON.Collider();
  7585. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7586. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7587. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  7588. // Cache
  7589. this._localScaling = BABYLON.Matrix.Zero();
  7590. this._localRotation = BABYLON.Matrix.Zero();
  7591. this._localTranslation = BABYLON.Matrix.Zero();
  7592. this._localBillboard = BABYLON.Matrix.Zero();
  7593. this._localPivotScaling = BABYLON.Matrix.Zero();
  7594. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  7595. this._localWorld = BABYLON.Matrix.Zero();
  7596. this._worldMatrix = BABYLON.Matrix.Zero();
  7597. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  7598. this._absolutePosition = BABYLON.Vector3.Zero();
  7599. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  7600. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  7601. this._isDirty = false;
  7602. this._pivotMatrix = BABYLON.Matrix.Identity();
  7603. this._isDisposed = false;
  7604. this._renderId = 0;
  7605. this._intersectionsInProgress = new Array();
  7606. this._onAfterWorldMatrixUpdate = new Array();
  7607. this._isWorldMatrixFrozen = false;
  7608. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  7609. if (collidedMesh === void 0) { collidedMesh = null; }
  7610. //TODO move this to the collision coordinator!
  7611. if (_this.getScene().workerCollisions)
  7612. newPosition.multiplyInPlace(_this._collider.radius);
  7613. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  7614. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  7615. _this.position.addInPlace(_this._diffPositionForCollisions);
  7616. }
  7617. };
  7618. scene.addMesh(this);
  7619. }
  7620. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  7621. get: function () {
  7622. return AbstractMesh._BILLBOARDMODE_NONE;
  7623. },
  7624. enumerable: true,
  7625. configurable: true
  7626. });
  7627. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  7628. get: function () {
  7629. return AbstractMesh._BILLBOARDMODE_X;
  7630. },
  7631. enumerable: true,
  7632. configurable: true
  7633. });
  7634. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  7635. get: function () {
  7636. return AbstractMesh._BILLBOARDMODE_Y;
  7637. },
  7638. enumerable: true,
  7639. configurable: true
  7640. });
  7641. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  7642. get: function () {
  7643. return AbstractMesh._BILLBOARDMODE_Z;
  7644. },
  7645. enumerable: true,
  7646. configurable: true
  7647. });
  7648. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  7649. get: function () {
  7650. return AbstractMesh._BILLBOARDMODE_ALL;
  7651. },
  7652. enumerable: true,
  7653. configurable: true
  7654. });
  7655. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  7656. // Methods
  7657. get: function () {
  7658. return false;
  7659. },
  7660. enumerable: true,
  7661. configurable: true
  7662. });
  7663. AbstractMesh.prototype.getLOD = function (camera) {
  7664. return this;
  7665. };
  7666. AbstractMesh.prototype.getTotalVertices = function () {
  7667. return 0;
  7668. };
  7669. AbstractMesh.prototype.getIndices = function () {
  7670. return null;
  7671. };
  7672. AbstractMesh.prototype.getVerticesData = function (kind) {
  7673. return null;
  7674. };
  7675. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  7676. return false;
  7677. };
  7678. AbstractMesh.prototype.getBoundingInfo = function () {
  7679. if (this._masterMesh) {
  7680. return this._masterMesh.getBoundingInfo();
  7681. }
  7682. if (!this._boundingInfo) {
  7683. this._updateBoundingInfo();
  7684. }
  7685. return this._boundingInfo;
  7686. };
  7687. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  7688. get: function () {
  7689. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  7690. },
  7691. enumerable: true,
  7692. configurable: true
  7693. });
  7694. AbstractMesh.prototype._preActivate = function () {
  7695. };
  7696. AbstractMesh.prototype._activate = function (renderId) {
  7697. this._renderId = renderId;
  7698. };
  7699. AbstractMesh.prototype.getWorldMatrix = function () {
  7700. if (this._masterMesh) {
  7701. return this._masterMesh.getWorldMatrix();
  7702. }
  7703. if (this._currentRenderId !== this.getScene().getRenderId()) {
  7704. this.computeWorldMatrix();
  7705. }
  7706. return this._worldMatrix;
  7707. };
  7708. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  7709. get: function () {
  7710. return this._worldMatrix;
  7711. },
  7712. enumerable: true,
  7713. configurable: true
  7714. });
  7715. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  7716. get: function () {
  7717. return this._absolutePosition;
  7718. },
  7719. enumerable: true,
  7720. configurable: true
  7721. });
  7722. AbstractMesh.prototype.freezeWorldMatrix = function () {
  7723. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  7724. this.computeWorldMatrix(true);
  7725. this._isWorldMatrixFrozen = true;
  7726. };
  7727. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  7728. this._isWorldMatrixFrozen = false;
  7729. this.computeWorldMatrix(true);
  7730. };
  7731. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  7732. get: function () {
  7733. return this._isWorldMatrixFrozen;
  7734. },
  7735. enumerable: true,
  7736. configurable: true
  7737. });
  7738. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  7739. axis.normalize();
  7740. if (!this.rotationQuaternion) {
  7741. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7742. this.rotation = BABYLON.Vector3.Zero();
  7743. }
  7744. if (!space || space === BABYLON.Space.LOCAL) {
  7745. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7746. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  7747. }
  7748. else {
  7749. if (this.parent) {
  7750. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7751. invertParentWorldMatrix.invert();
  7752. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  7753. }
  7754. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  7755. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  7756. }
  7757. };
  7758. AbstractMesh.prototype.translate = function (axis, distance, space) {
  7759. var displacementVector = axis.scale(distance);
  7760. if (!space || space === BABYLON.Space.LOCAL) {
  7761. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  7762. this.setPositionWithLocalVector(tempV3);
  7763. }
  7764. else {
  7765. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  7766. }
  7767. };
  7768. AbstractMesh.prototype.getAbsolutePosition = function () {
  7769. this.computeWorldMatrix();
  7770. return this._absolutePosition;
  7771. };
  7772. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  7773. if (!absolutePosition) {
  7774. return;
  7775. }
  7776. var absolutePositionX;
  7777. var absolutePositionY;
  7778. var absolutePositionZ;
  7779. if (absolutePosition.x === undefined) {
  7780. if (arguments.length < 3) {
  7781. return;
  7782. }
  7783. absolutePositionX = arguments[0];
  7784. absolutePositionY = arguments[1];
  7785. absolutePositionZ = arguments[2];
  7786. }
  7787. else {
  7788. absolutePositionX = absolutePosition.x;
  7789. absolutePositionY = absolutePosition.y;
  7790. absolutePositionZ = absolutePosition.z;
  7791. }
  7792. if (this.parent) {
  7793. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  7794. invertParentWorldMatrix.invert();
  7795. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  7796. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  7797. }
  7798. else {
  7799. this.position.x = absolutePositionX;
  7800. this.position.y = absolutePositionY;
  7801. this.position.z = absolutePositionZ;
  7802. }
  7803. };
  7804. // ================================== Point of View Movement =================================
  7805. /**
  7806. * Perform relative position change from the point of view of behind the front of the mesh.
  7807. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7808. * Supports definition of mesh facing forward or backward.
  7809. * @param {number} amountRight
  7810. * @param {number} amountUp
  7811. * @param {number} amountForward
  7812. */
  7813. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  7814. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  7815. };
  7816. /**
  7817. * Calculate relative position change from the point of view of behind the front of the mesh.
  7818. * This is performed taking into account the meshes current rotation, so you do not have to care.
  7819. * Supports definition of mesh facing forward or backward.
  7820. * @param {number} amountRight
  7821. * @param {number} amountUp
  7822. * @param {number} amountForward
  7823. */
  7824. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  7825. var rotMatrix = new BABYLON.Matrix();
  7826. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  7827. rotQuaternion.toRotationMatrix(rotMatrix);
  7828. var translationDelta = BABYLON.Vector3.Zero();
  7829. var defForwardMult = this.definedFacingForward ? -1 : 1;
  7830. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  7831. return translationDelta;
  7832. };
  7833. // ================================== Point of View Rotation =================================
  7834. /**
  7835. * Perform relative rotation change from the point of view of behind the front of the mesh.
  7836. * Supports definition of mesh facing forward or backward.
  7837. * @param {number} flipBack
  7838. * @param {number} twirlClockwise
  7839. * @param {number} tiltRight
  7840. */
  7841. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7842. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  7843. };
  7844. /**
  7845. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  7846. * Supports definition of mesh facing forward or backward.
  7847. * @param {number} flipBack
  7848. * @param {number} twirlClockwise
  7849. * @param {number} tiltRight
  7850. */
  7851. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  7852. var defForwardMult = this.definedFacingForward ? 1 : -1;
  7853. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  7854. };
  7855. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  7856. this._pivotMatrix = matrix;
  7857. this._cache.pivotMatrixUpdated = true;
  7858. };
  7859. AbstractMesh.prototype.getPivotMatrix = function () {
  7860. return this._pivotMatrix;
  7861. };
  7862. AbstractMesh.prototype._isSynchronized = function () {
  7863. if (this._isDirty) {
  7864. return false;
  7865. }
  7866. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  7867. return false;
  7868. if (this._cache.pivotMatrixUpdated) {
  7869. return false;
  7870. }
  7871. if (this.infiniteDistance) {
  7872. return false;
  7873. }
  7874. if (!this._cache.position.equals(this.position))
  7875. return false;
  7876. if (this.rotationQuaternion) {
  7877. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  7878. return false;
  7879. }
  7880. else {
  7881. if (!this._cache.rotation.equals(this.rotation))
  7882. return false;
  7883. }
  7884. if (!this._cache.scaling.equals(this.scaling))
  7885. return false;
  7886. return true;
  7887. };
  7888. AbstractMesh.prototype._initCache = function () {
  7889. _super.prototype._initCache.call(this);
  7890. this._cache.localMatrixUpdated = false;
  7891. this._cache.position = BABYLON.Vector3.Zero();
  7892. this._cache.scaling = BABYLON.Vector3.Zero();
  7893. this._cache.rotation = BABYLON.Vector3.Zero();
  7894. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  7895. };
  7896. AbstractMesh.prototype.markAsDirty = function (property) {
  7897. if (property === "rotation") {
  7898. this.rotationQuaternion = null;
  7899. }
  7900. this._currentRenderId = Number.MAX_VALUE;
  7901. this._isDirty = true;
  7902. };
  7903. AbstractMesh.prototype._updateBoundingInfo = function () {
  7904. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  7905. this._boundingInfo._update(this.worldMatrixFromCache);
  7906. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  7907. };
  7908. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  7909. if (!this.subMeshes) {
  7910. return;
  7911. }
  7912. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  7913. var subMesh = this.subMeshes[subIndex];
  7914. subMesh.updateBoundingInfo(matrix);
  7915. }
  7916. };
  7917. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  7918. if (this._isWorldMatrixFrozen) {
  7919. return this._worldMatrix;
  7920. }
  7921. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  7922. return this._worldMatrix;
  7923. }
  7924. this._cache.position.copyFrom(this.position);
  7925. this._cache.scaling.copyFrom(this.scaling);
  7926. this._cache.pivotMatrixUpdated = false;
  7927. this._currentRenderId = this.getScene().getRenderId();
  7928. this._isDirty = false;
  7929. // Scaling
  7930. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  7931. // Rotation
  7932. if (this.rotationQuaternion) {
  7933. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  7934. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  7935. }
  7936. else {
  7937. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  7938. this._cache.rotation.copyFrom(this.rotation);
  7939. }
  7940. // Translation
  7941. if (this.infiniteDistance && !this.parent) {
  7942. var camera = this.getScene().activeCamera;
  7943. var cameraWorldMatrix = camera.getWorldMatrix();
  7944. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  7945. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  7946. }
  7947. else {
  7948. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  7949. }
  7950. // Composing transformations
  7951. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  7952. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  7953. // Billboarding
  7954. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  7955. var localPosition = this.position.clone();
  7956. var zero = this.getScene().activeCamera.globalPosition.clone();
  7957. if (this.parent && this.parent.position) {
  7958. localPosition.addInPlace(this.parent.position);
  7959. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  7960. }
  7961. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) != AbstractMesh.BILLBOARDMODE_ALL) {
  7962. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  7963. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  7964. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  7965. zero.y = localPosition.y + 0.001;
  7966. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  7967. zero.z = localPosition.z + 0.001;
  7968. }
  7969. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  7970. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  7971. this._localBillboard.invert();
  7972. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  7973. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  7974. }
  7975. // Local world
  7976. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  7977. // Parent
  7978. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  7979. this._markSyncedWithParent();
  7980. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  7981. }
  7982. else {
  7983. this._worldMatrix.copyFrom(this._localWorld);
  7984. }
  7985. // Bounding info
  7986. this._updateBoundingInfo();
  7987. // Absolute position
  7988. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  7989. // Callbacks
  7990. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  7991. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  7992. }
  7993. return this._worldMatrix;
  7994. };
  7995. /**
  7996. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  7997. * @param func: callback function to add
  7998. */
  7999. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8000. this._onAfterWorldMatrixUpdate.push(func);
  8001. };
  8002. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8003. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8004. if (index > -1) {
  8005. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8006. }
  8007. };
  8008. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8009. this.computeWorldMatrix();
  8010. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8011. };
  8012. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8013. this.computeWorldMatrix();
  8014. var invLocalWorldMatrix = this._localWorld.clone();
  8015. invLocalWorldMatrix.invert();
  8016. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8017. };
  8018. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8019. this.computeWorldMatrix(true);
  8020. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8021. };
  8022. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8023. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8024. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  8025. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  8026. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  8027. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  8028. /// <returns>Mesh oriented towards targetMesh</returns>
  8029. yawCor = yawCor || 0; // default to zero if undefined
  8030. pitchCor = pitchCor || 0;
  8031. rollCor = rollCor || 0;
  8032. var dv = targetPoint.subtract(this.position);
  8033. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  8034. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  8035. var pitch = Math.atan2(dv.y, len);
  8036. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  8037. };
  8038. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  8039. return this._boundingInfo.isInFrustum(frustumPlanes);
  8040. };
  8041. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  8042. if (!camera) {
  8043. camera = this.getScene().activeCamera;
  8044. }
  8045. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  8046. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  8047. return false;
  8048. }
  8049. return true;
  8050. };
  8051. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  8052. if (!this._boundingInfo || !mesh._boundingInfo) {
  8053. return false;
  8054. }
  8055. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  8056. };
  8057. AbstractMesh.prototype.intersectsPoint = function (point) {
  8058. if (!this._boundingInfo) {
  8059. return false;
  8060. }
  8061. return this._boundingInfo.intersectsPoint(point);
  8062. };
  8063. // Physics
  8064. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  8065. var physicsEngine = this.getScene().getPhysicsEngine();
  8066. if (!physicsEngine) {
  8067. return;
  8068. }
  8069. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  8070. if (impostor.impostor) {
  8071. // Old API
  8072. options = impostor;
  8073. impostor = impostor.impostor;
  8074. }
  8075. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  8076. physicsEngine._unregisterMesh(this);
  8077. return;
  8078. }
  8079. if (!options) {
  8080. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  8081. }
  8082. else {
  8083. if (!options.mass && options.mass !== 0)
  8084. options.mass = 0;
  8085. if (!options.friction && options.friction !== 0)
  8086. options.friction = 0.2;
  8087. if (!options.restitution && options.restitution !== 0)
  8088. options.restitution = 0.2;
  8089. }
  8090. this._physicImpostor = impostor;
  8091. this._physicsMass = options.mass;
  8092. this._physicsFriction = options.friction;
  8093. this._physicRestitution = options.restitution;
  8094. return physicsEngine._registerMesh(this, impostor, options);
  8095. };
  8096. AbstractMesh.prototype.getPhysicsImpostor = function () {
  8097. if (!this._physicImpostor) {
  8098. return BABYLON.PhysicsEngine.NoImpostor;
  8099. }
  8100. return this._physicImpostor;
  8101. };
  8102. AbstractMesh.prototype.getPhysicsMass = function () {
  8103. if (!this._physicsMass) {
  8104. return 0;
  8105. }
  8106. return this._physicsMass;
  8107. };
  8108. AbstractMesh.prototype.getPhysicsFriction = function () {
  8109. if (!this._physicsFriction) {
  8110. return 0;
  8111. }
  8112. return this._physicsFriction;
  8113. };
  8114. AbstractMesh.prototype.getPhysicsRestitution = function () {
  8115. if (!this._physicRestitution) {
  8116. return 0;
  8117. }
  8118. return this._physicRestitution;
  8119. };
  8120. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  8121. if (!camera) {
  8122. camera = this.getScene().activeCamera;
  8123. }
  8124. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  8125. };
  8126. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  8127. if (!camera) {
  8128. camera = this.getScene().activeCamera;
  8129. }
  8130. return this.absolutePosition.subtract(camera.position).length();
  8131. };
  8132. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  8133. if (!this._physicImpostor) {
  8134. return;
  8135. }
  8136. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  8137. };
  8138. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  8139. if (!this._physicImpostor) {
  8140. return;
  8141. }
  8142. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  8143. };
  8144. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  8145. if (!this._physicImpostor) {
  8146. return;
  8147. }
  8148. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  8149. };
  8150. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  8151. // Collisions
  8152. get: function () {
  8153. return this._checkCollisions;
  8154. },
  8155. set: function (collisionEnabled) {
  8156. this._checkCollisions = collisionEnabled;
  8157. if (this.getScene().workerCollisions) {
  8158. this.getScene().collisionCoordinator.onMeshUpdated(this);
  8159. }
  8160. },
  8161. enumerable: true,
  8162. configurable: true
  8163. });
  8164. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  8165. var globalPosition = this.getAbsolutePosition();
  8166. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  8167. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  8168. this._collider.radius = this.ellipsoid;
  8169. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  8170. };
  8171. // Submeshes octree
  8172. /**
  8173. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  8174. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  8175. */
  8176. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  8177. if (maxCapacity === void 0) { maxCapacity = 64; }
  8178. if (maxDepth === void 0) { maxDepth = 2; }
  8179. if (!this._submeshesOctree) {
  8180. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  8181. }
  8182. this.computeWorldMatrix(true);
  8183. // Update octree
  8184. var bbox = this.getBoundingInfo().boundingBox;
  8185. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  8186. return this._submeshesOctree;
  8187. };
  8188. // Collisions
  8189. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  8190. this._generatePointsArray();
  8191. // Transformation
  8192. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  8193. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  8194. subMesh._lastColliderWorldVertices = [];
  8195. subMesh._trianglePlanes = [];
  8196. var start = subMesh.verticesStart;
  8197. var end = (subMesh.verticesStart + subMesh.verticesCount);
  8198. for (var i = start; i < end; i++) {
  8199. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  8200. }
  8201. }
  8202. // Collide
  8203. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  8204. if (collider.collisionFound) {
  8205. collider.collidedMesh = this;
  8206. }
  8207. };
  8208. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  8209. var subMeshes;
  8210. var len;
  8211. // Octrees
  8212. if (this._submeshesOctree && this.useOctreeForCollisions) {
  8213. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  8214. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  8215. len = intersections.length;
  8216. subMeshes = intersections.data;
  8217. }
  8218. else {
  8219. subMeshes = this.subMeshes;
  8220. len = subMeshes.length;
  8221. }
  8222. for (var index = 0; index < len; index++) {
  8223. var subMesh = subMeshes[index];
  8224. // Bounding test
  8225. if (len > 1 && !subMesh._checkCollision(collider))
  8226. continue;
  8227. this._collideForSubMesh(subMesh, transformMatrix, collider);
  8228. }
  8229. };
  8230. AbstractMesh.prototype._checkCollision = function (collider) {
  8231. // Bounding box test
  8232. if (!this._boundingInfo._checkCollision(collider))
  8233. return;
  8234. // Transformation matrix
  8235. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  8236. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  8237. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  8238. };
  8239. // Picking
  8240. AbstractMesh.prototype._generatePointsArray = function () {
  8241. return false;
  8242. };
  8243. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  8244. var pickingInfo = new BABYLON.PickingInfo();
  8245. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  8246. return pickingInfo;
  8247. }
  8248. if (!this._generatePointsArray()) {
  8249. return pickingInfo;
  8250. }
  8251. var intersectInfo = null;
  8252. // Octrees
  8253. var subMeshes;
  8254. var len;
  8255. if (this._submeshesOctree && this.useOctreeForPicking) {
  8256. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  8257. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  8258. len = intersections.length;
  8259. subMeshes = intersections.data;
  8260. }
  8261. else {
  8262. subMeshes = this.subMeshes;
  8263. len = subMeshes.length;
  8264. }
  8265. for (var index = 0; index < len; index++) {
  8266. var subMesh = subMeshes[index];
  8267. // Bounding test
  8268. if (len > 1 && !subMesh.canIntersects(ray))
  8269. continue;
  8270. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  8271. if (currentIntersectInfo) {
  8272. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  8273. intersectInfo = currentIntersectInfo;
  8274. intersectInfo.subMeshId = index;
  8275. if (fastCheck) {
  8276. break;
  8277. }
  8278. }
  8279. }
  8280. }
  8281. if (intersectInfo) {
  8282. // Get picked point
  8283. var world = this.getWorldMatrix();
  8284. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  8285. var direction = ray.direction.clone();
  8286. direction = direction.scale(intersectInfo.distance);
  8287. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  8288. var pickedPoint = worldOrigin.add(worldDirection);
  8289. // Return result
  8290. pickingInfo.hit = true;
  8291. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  8292. pickingInfo.pickedPoint = pickedPoint;
  8293. pickingInfo.pickedMesh = this;
  8294. pickingInfo.bu = intersectInfo.bu;
  8295. pickingInfo.bv = intersectInfo.bv;
  8296. pickingInfo.faceId = intersectInfo.faceId;
  8297. pickingInfo.subMeshId = intersectInfo.subMeshId;
  8298. return pickingInfo;
  8299. }
  8300. return pickingInfo;
  8301. };
  8302. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  8303. return null;
  8304. };
  8305. AbstractMesh.prototype.releaseSubMeshes = function () {
  8306. if (this.subMeshes) {
  8307. while (this.subMeshes.length) {
  8308. this.subMeshes[0].dispose();
  8309. }
  8310. }
  8311. else {
  8312. this.subMeshes = new Array();
  8313. }
  8314. };
  8315. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  8316. var index;
  8317. // Physics
  8318. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  8319. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  8320. }
  8321. // Intersections in progress
  8322. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  8323. var other = this._intersectionsInProgress[index];
  8324. var pos = other._intersectionsInProgress.indexOf(this);
  8325. other._intersectionsInProgress.splice(pos, 1);
  8326. }
  8327. this._intersectionsInProgress = [];
  8328. // SubMeshes
  8329. this.releaseSubMeshes();
  8330. // Remove from scene
  8331. this.getScene().removeMesh(this);
  8332. if (!doNotRecurse) {
  8333. // Particles
  8334. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  8335. if (this.getScene().particleSystems[index].emitter === this) {
  8336. this.getScene().particleSystems[index].dispose();
  8337. index--;
  8338. }
  8339. }
  8340. // Children
  8341. var objects = this.getScene().meshes.slice(0);
  8342. for (index = 0; index < objects.length; index++) {
  8343. if (objects[index].parent === this) {
  8344. objects[index].dispose();
  8345. }
  8346. }
  8347. }
  8348. else {
  8349. for (index = 0; index < this.getScene().meshes.length; index++) {
  8350. var obj = this.getScene().meshes[index];
  8351. if (obj.parent === this) {
  8352. obj.parent = null;
  8353. obj.computeWorldMatrix(true);
  8354. }
  8355. }
  8356. }
  8357. this._onAfterWorldMatrixUpdate = [];
  8358. this._isDisposed = true;
  8359. // Callback
  8360. if (this.onDispose) {
  8361. this.onDispose();
  8362. }
  8363. };
  8364. // Statics
  8365. AbstractMesh._BILLBOARDMODE_NONE = 0;
  8366. AbstractMesh._BILLBOARDMODE_X = 1;
  8367. AbstractMesh._BILLBOARDMODE_Y = 2;
  8368. AbstractMesh._BILLBOARDMODE_Z = 4;
  8369. AbstractMesh._BILLBOARDMODE_ALL = 7;
  8370. return AbstractMesh;
  8371. })(BABYLON.Node);
  8372. BABYLON.AbstractMesh = AbstractMesh;
  8373. })(BABYLON || (BABYLON = {}));
  8374. //# sourceMappingURL=babylon.abstractMesh.js.map
  8375. var BABYLON;
  8376. (function (BABYLON) {
  8377. var Light = (function (_super) {
  8378. __extends(Light, _super);
  8379. function Light(name, scene) {
  8380. _super.call(this, name, scene);
  8381. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  8382. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  8383. this.intensity = 1.0;
  8384. this.range = Number.MAX_VALUE;
  8385. this.includeOnlyWithLayerMask = 0;
  8386. this.includedOnlyMeshes = new Array();
  8387. this.excludedMeshes = new Array();
  8388. this.excludeWithLayerMask = 0;
  8389. this._excludedMeshesIds = new Array();
  8390. this._includedOnlyMeshesIds = new Array();
  8391. scene.addLight(this);
  8392. }
  8393. Light.prototype.getShadowGenerator = function () {
  8394. return this._shadowGenerator;
  8395. };
  8396. Light.prototype.getAbsolutePosition = function () {
  8397. return BABYLON.Vector3.Zero();
  8398. };
  8399. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  8400. };
  8401. Light.prototype._getWorldMatrix = function () {
  8402. return BABYLON.Matrix.Identity();
  8403. };
  8404. Light.prototype.canAffectMesh = function (mesh) {
  8405. if (!mesh) {
  8406. return true;
  8407. }
  8408. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  8409. return false;
  8410. }
  8411. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  8412. return false;
  8413. }
  8414. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  8415. return false;
  8416. }
  8417. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  8418. return false;
  8419. }
  8420. return true;
  8421. };
  8422. Light.prototype.getWorldMatrix = function () {
  8423. this._currentRenderId = this.getScene().getRenderId();
  8424. var worldMatrix = this._getWorldMatrix();
  8425. if (this.parent && this.parent.getWorldMatrix) {
  8426. if (!this._parentedWorldMatrix) {
  8427. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  8428. }
  8429. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  8430. this._markSyncedWithParent();
  8431. return this._parentedWorldMatrix;
  8432. }
  8433. return worldMatrix;
  8434. };
  8435. Light.prototype.dispose = function () {
  8436. if (this._shadowGenerator) {
  8437. this._shadowGenerator.dispose();
  8438. this._shadowGenerator = null;
  8439. }
  8440. // Remove from scene
  8441. this.getScene().removeLight(this);
  8442. };
  8443. return Light;
  8444. })(BABYLON.Node);
  8445. BABYLON.Light = Light;
  8446. })(BABYLON || (BABYLON = {}));
  8447. //# sourceMappingURL=babylon.light.js.map
  8448. var BABYLON;
  8449. (function (BABYLON) {
  8450. var PointLight = (function (_super) {
  8451. __extends(PointLight, _super);
  8452. function PointLight(name, position, scene) {
  8453. _super.call(this, name, scene);
  8454. this.position = position;
  8455. }
  8456. PointLight.prototype.getAbsolutePosition = function () {
  8457. return this._transformedPosition ? this._transformedPosition : this.position;
  8458. };
  8459. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  8460. if (this.parent && this.parent.getWorldMatrix) {
  8461. if (!this._transformedPosition) {
  8462. this._transformedPosition = BABYLON.Vector3.Zero();
  8463. }
  8464. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  8465. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  8466. return;
  8467. }
  8468. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  8469. };
  8470. PointLight.prototype.getShadowGenerator = function () {
  8471. return null;
  8472. };
  8473. PointLight.prototype._getWorldMatrix = function () {
  8474. if (!this._worldMatrix) {
  8475. this._worldMatrix = BABYLON.Matrix.Identity();
  8476. }
  8477. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8478. return this._worldMatrix;
  8479. };
  8480. return PointLight;
  8481. })(BABYLON.Light);
  8482. BABYLON.PointLight = PointLight;
  8483. })(BABYLON || (BABYLON = {}));
  8484. //# sourceMappingURL=babylon.pointLight.js.map
  8485. var BABYLON;
  8486. (function (BABYLON) {
  8487. var SpotLight = (function (_super) {
  8488. __extends(SpotLight, _super);
  8489. function SpotLight(name, position, direction, angle, exponent, scene) {
  8490. _super.call(this, name, scene);
  8491. this.position = position;
  8492. this.direction = direction;
  8493. this.angle = angle;
  8494. this.exponent = exponent;
  8495. }
  8496. SpotLight.prototype.getAbsolutePosition = function () {
  8497. return this.transformedPosition ? this.transformedPosition : this.position;
  8498. };
  8499. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8500. var activeCamera = this.getScene().activeCamera;
  8501. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  8502. };
  8503. SpotLight.prototype.supportsVSM = function () {
  8504. return true;
  8505. };
  8506. SpotLight.prototype.needRefreshPerFrame = function () {
  8507. return false;
  8508. };
  8509. SpotLight.prototype.setDirectionToTarget = function (target) {
  8510. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8511. return this.direction;
  8512. };
  8513. SpotLight.prototype.computeTransformedPosition = function () {
  8514. if (this.parent && this.parent.getWorldMatrix) {
  8515. if (!this.transformedPosition) {
  8516. this.transformedPosition = BABYLON.Vector3.Zero();
  8517. }
  8518. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8519. return true;
  8520. }
  8521. return false;
  8522. };
  8523. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  8524. var normalizeDirection;
  8525. if (this.parent && this.parent.getWorldMatrix) {
  8526. if (!this._transformedDirection) {
  8527. this._transformedDirection = BABYLON.Vector3.Zero();
  8528. }
  8529. this.computeTransformedPosition();
  8530. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8531. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  8532. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  8533. }
  8534. else {
  8535. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  8536. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8537. }
  8538. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  8539. };
  8540. SpotLight.prototype._getWorldMatrix = function () {
  8541. if (!this._worldMatrix) {
  8542. this._worldMatrix = BABYLON.Matrix.Identity();
  8543. }
  8544. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8545. return this._worldMatrix;
  8546. };
  8547. return SpotLight;
  8548. })(BABYLON.Light);
  8549. BABYLON.SpotLight = SpotLight;
  8550. })(BABYLON || (BABYLON = {}));
  8551. //# sourceMappingURL=babylon.spotLight.js.map
  8552. var BABYLON;
  8553. (function (BABYLON) {
  8554. var HemisphericLight = (function (_super) {
  8555. __extends(HemisphericLight, _super);
  8556. function HemisphericLight(name, direction, scene) {
  8557. _super.call(this, name, scene);
  8558. this.direction = direction;
  8559. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  8560. }
  8561. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  8562. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  8563. return this.direction;
  8564. };
  8565. HemisphericLight.prototype.getShadowGenerator = function () {
  8566. return null;
  8567. };
  8568. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  8569. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  8570. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  8571. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  8572. };
  8573. HemisphericLight.prototype._getWorldMatrix = function () {
  8574. if (!this._worldMatrix) {
  8575. this._worldMatrix = BABYLON.Matrix.Identity();
  8576. }
  8577. return this._worldMatrix;
  8578. };
  8579. return HemisphericLight;
  8580. })(BABYLON.Light);
  8581. BABYLON.HemisphericLight = HemisphericLight;
  8582. })(BABYLON || (BABYLON = {}));
  8583. //# sourceMappingURL=babylon.hemisphericLight.js.map
  8584. var BABYLON;
  8585. (function (BABYLON) {
  8586. var DirectionalLight = (function (_super) {
  8587. __extends(DirectionalLight, _super);
  8588. function DirectionalLight(name, direction, scene) {
  8589. _super.call(this, name, scene);
  8590. this.direction = direction;
  8591. this.shadowOrthoScale = 0.5;
  8592. this.position = direction.scale(-1);
  8593. }
  8594. DirectionalLight.prototype.getAbsolutePosition = function () {
  8595. return this.transformedPosition ? this.transformedPosition : this.position;
  8596. };
  8597. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  8598. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  8599. return this.direction;
  8600. };
  8601. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  8602. var orthoLeft = Number.MAX_VALUE;
  8603. var orthoRight = Number.MIN_VALUE;
  8604. var orthoTop = Number.MIN_VALUE;
  8605. var orthoBottom = Number.MAX_VALUE;
  8606. var tempVector3 = BABYLON.Vector3.Zero();
  8607. var activeCamera = this.getScene().activeCamera;
  8608. // Check extends
  8609. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  8610. var mesh = renderList[meshIndex];
  8611. if (!mesh) {
  8612. continue;
  8613. }
  8614. var boundingInfo = mesh.getBoundingInfo();
  8615. if (!boundingInfo) {
  8616. continue;
  8617. }
  8618. var boundingBox = boundingInfo.boundingBox;
  8619. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  8620. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  8621. if (tempVector3.x < orthoLeft)
  8622. orthoLeft = tempVector3.x;
  8623. if (tempVector3.y < orthoBottom)
  8624. orthoBottom = tempVector3.y;
  8625. if (tempVector3.x > orthoRight)
  8626. orthoRight = tempVector3.x;
  8627. if (tempVector3.y > orthoTop)
  8628. orthoTop = tempVector3.y;
  8629. }
  8630. }
  8631. var xOffset = orthoRight - orthoLeft;
  8632. var yOffset = orthoTop - orthoBottom;
  8633. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  8634. };
  8635. DirectionalLight.prototype.supportsVSM = function () {
  8636. return true;
  8637. };
  8638. DirectionalLight.prototype.needRefreshPerFrame = function () {
  8639. return true;
  8640. };
  8641. DirectionalLight.prototype.computeTransformedPosition = function () {
  8642. if (this.parent && this.parent.getWorldMatrix) {
  8643. if (!this.transformedPosition) {
  8644. this.transformedPosition = BABYLON.Vector3.Zero();
  8645. }
  8646. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  8647. return true;
  8648. }
  8649. return false;
  8650. };
  8651. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  8652. if (this.parent && this.parent.getWorldMatrix) {
  8653. if (!this._transformedDirection) {
  8654. this._transformedDirection = BABYLON.Vector3.Zero();
  8655. }
  8656. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  8657. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  8658. return;
  8659. }
  8660. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  8661. };
  8662. DirectionalLight.prototype._getWorldMatrix = function () {
  8663. if (!this._worldMatrix) {
  8664. this._worldMatrix = BABYLON.Matrix.Identity();
  8665. }
  8666. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  8667. return this._worldMatrix;
  8668. };
  8669. return DirectionalLight;
  8670. })(BABYLON.Light);
  8671. BABYLON.DirectionalLight = DirectionalLight;
  8672. })(BABYLON || (BABYLON = {}));
  8673. //# sourceMappingURL=babylon.directionalLight.js.map
  8674. var BABYLON;
  8675. (function (BABYLON) {
  8676. var ShadowGenerator = (function () {
  8677. function ShadowGenerator(mapSize, light) {
  8678. var _this = this;
  8679. // Members
  8680. this._filter = ShadowGenerator.FILTER_NONE;
  8681. this.blurScale = 2;
  8682. this._blurBoxOffset = 0;
  8683. this._bias = 0.00005;
  8684. this._darkness = 0;
  8685. this._transparencyShadow = false;
  8686. this._viewMatrix = BABYLON.Matrix.Zero();
  8687. this._projectionMatrix = BABYLON.Matrix.Zero();
  8688. this._transformMatrix = BABYLON.Matrix.Zero();
  8689. this._worldViewProjection = BABYLON.Matrix.Zero();
  8690. this._light = light;
  8691. this._scene = light.getScene();
  8692. this._mapSize = mapSize;
  8693. light._shadowGenerator = this;
  8694. // Render target
  8695. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  8696. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8697. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8698. this._shadowMap.anisotropicFilteringLevel = 1;
  8699. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8700. this._shadowMap.renderParticles = false;
  8701. this._shadowMap.onAfterUnbind = function () {
  8702. if (!_this.useBlurVarianceShadowMap) {
  8703. return;
  8704. }
  8705. if (!_this._shadowMap2) {
  8706. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  8707. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8708. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  8709. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  8710. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  8711. _this._downSamplePostprocess.onApply = function (effect) {
  8712. effect.setTexture("textureSampler", _this._shadowMap);
  8713. };
  8714. _this.blurBoxOffset = 1;
  8715. }
  8716. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  8717. };
  8718. // Custom render function
  8719. var renderSubMesh = function (subMesh) {
  8720. var mesh = subMesh.getRenderingMesh();
  8721. var scene = _this._scene;
  8722. var engine = scene.getEngine();
  8723. // Culling
  8724. engine.setState(subMesh.getMaterial().backFaceCulling);
  8725. // Managing instances
  8726. var batch = mesh._getInstancesRenderList(subMesh._id);
  8727. if (batch.mustReturn) {
  8728. return;
  8729. }
  8730. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  8731. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  8732. engine.enableEffect(_this._effect);
  8733. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  8734. var material = subMesh.getMaterial();
  8735. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  8736. // Alpha test
  8737. if (material && material.needAlphaTesting()) {
  8738. var alphaTexture = material.getAlphaTestTexture();
  8739. _this._effect.setTexture("diffuseSampler", alphaTexture);
  8740. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  8741. }
  8742. // Bones
  8743. if (mesh.useBones) {
  8744. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  8745. }
  8746. // Draw
  8747. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  8748. }
  8749. else {
  8750. // Need to reset refresh rate of the shadowMap
  8751. _this._shadowMap.resetRefreshCounter();
  8752. }
  8753. };
  8754. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  8755. var index;
  8756. for (index = 0; index < opaqueSubMeshes.length; index++) {
  8757. renderSubMesh(opaqueSubMeshes.data[index]);
  8758. }
  8759. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  8760. renderSubMesh(alphaTestSubMeshes.data[index]);
  8761. }
  8762. if (_this._transparencyShadow) {
  8763. for (index = 0; index < transparentSubMeshes.length; index++) {
  8764. renderSubMesh(transparentSubMeshes.data[index]);
  8765. }
  8766. }
  8767. };
  8768. this._shadowMap.onClear = function (engine) {
  8769. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  8770. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  8771. }
  8772. else {
  8773. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  8774. }
  8775. };
  8776. }
  8777. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  8778. // Static
  8779. get: function () {
  8780. return ShadowGenerator._FILTER_NONE;
  8781. },
  8782. enumerable: true,
  8783. configurable: true
  8784. });
  8785. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  8786. get: function () {
  8787. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  8788. },
  8789. enumerable: true,
  8790. configurable: true
  8791. });
  8792. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  8793. get: function () {
  8794. return ShadowGenerator._FILTER_POISSONSAMPLING;
  8795. },
  8796. enumerable: true,
  8797. configurable: true
  8798. });
  8799. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  8800. get: function () {
  8801. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  8802. },
  8803. enumerable: true,
  8804. configurable: true
  8805. });
  8806. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  8807. get: function () {
  8808. return this._bias;
  8809. },
  8810. set: function (bias) {
  8811. this._bias = bias;
  8812. },
  8813. enumerable: true,
  8814. configurable: true
  8815. });
  8816. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  8817. get: function () {
  8818. return this._blurBoxOffset;
  8819. },
  8820. set: function (value) {
  8821. var _this = this;
  8822. if (this._blurBoxOffset === value) {
  8823. return;
  8824. }
  8825. this._blurBoxOffset = value;
  8826. if (this._boxBlurPostprocess) {
  8827. this._boxBlurPostprocess.dispose();
  8828. }
  8829. 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);
  8830. this._boxBlurPostprocess.onApply = function (effect) {
  8831. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  8832. };
  8833. },
  8834. enumerable: true,
  8835. configurable: true
  8836. });
  8837. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  8838. get: function () {
  8839. return this._filter;
  8840. },
  8841. set: function (value) {
  8842. if (this._filter === value) {
  8843. return;
  8844. }
  8845. this._filter = value;
  8846. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8847. this._shadowMap.anisotropicFilteringLevel = 16;
  8848. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  8849. }
  8850. else {
  8851. this._shadowMap.anisotropicFilteringLevel = 1;
  8852. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8853. }
  8854. },
  8855. enumerable: true,
  8856. configurable: true
  8857. });
  8858. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  8859. get: function () {
  8860. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  8861. },
  8862. set: function (value) {
  8863. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8864. },
  8865. enumerable: true,
  8866. configurable: true
  8867. });
  8868. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  8869. get: function () {
  8870. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  8871. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  8872. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  8873. },
  8874. set: function (value) {
  8875. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  8876. },
  8877. enumerable: true,
  8878. configurable: true
  8879. });
  8880. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  8881. get: function () {
  8882. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  8883. },
  8884. set: function (value) {
  8885. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  8886. },
  8887. enumerable: true,
  8888. configurable: true
  8889. });
  8890. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  8891. var defines = [];
  8892. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  8893. defines.push("#define VSM");
  8894. }
  8895. var attribs = [BABYLON.VertexBuffer.PositionKind];
  8896. var mesh = subMesh.getMesh();
  8897. var material = subMesh.getMaterial();
  8898. // Alpha test
  8899. if (material && material.needAlphaTesting()) {
  8900. defines.push("#define ALPHATEST");
  8901. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  8902. attribs.push(BABYLON.VertexBuffer.UVKind);
  8903. defines.push("#define UV1");
  8904. }
  8905. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  8906. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  8907. defines.push("#define UV2");
  8908. }
  8909. }
  8910. // Bones
  8911. if (mesh.useBones) {
  8912. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  8913. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  8914. defines.push("#define BONES");
  8915. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  8916. }
  8917. // Instances
  8918. if (useInstances) {
  8919. defines.push("#define INSTANCES");
  8920. attribs.push("world0");
  8921. attribs.push("world1");
  8922. attribs.push("world2");
  8923. attribs.push("world3");
  8924. }
  8925. // Get correct effect
  8926. var join = defines.join("\n");
  8927. if (this._cachedDefines !== join) {
  8928. this._cachedDefines = join;
  8929. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  8930. }
  8931. return this._effect.isReady();
  8932. };
  8933. ShadowGenerator.prototype.getShadowMap = function () {
  8934. return this._shadowMap;
  8935. };
  8936. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  8937. if (this._shadowMap2) {
  8938. return this._shadowMap2;
  8939. }
  8940. return this._shadowMap;
  8941. };
  8942. ShadowGenerator.prototype.getLight = function () {
  8943. return this._light;
  8944. };
  8945. // Methods
  8946. ShadowGenerator.prototype.getTransformMatrix = function () {
  8947. var scene = this._scene;
  8948. if (this._currentRenderID === scene.getRenderId()) {
  8949. return this._transformMatrix;
  8950. }
  8951. this._currentRenderID = scene.getRenderId();
  8952. var lightPosition = this._light.position;
  8953. var lightDirection = this._light.direction;
  8954. if (this._light.computeTransformedPosition()) {
  8955. lightPosition = this._light.transformedPosition;
  8956. }
  8957. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  8958. this._cachedPosition = lightPosition.clone();
  8959. this._cachedDirection = lightDirection.clone();
  8960. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  8961. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  8962. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8963. }
  8964. return this._transformMatrix;
  8965. };
  8966. ShadowGenerator.prototype.getDarkness = function () {
  8967. return this._darkness;
  8968. };
  8969. ShadowGenerator.prototype.setDarkness = function (darkness) {
  8970. if (darkness >= 1.0)
  8971. this._darkness = 1.0;
  8972. else if (darkness <= 0.0)
  8973. this._darkness = 0.0;
  8974. else
  8975. this._darkness = darkness;
  8976. };
  8977. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  8978. this._transparencyShadow = hasShadow;
  8979. };
  8980. ShadowGenerator.prototype._packHalf = function (depth) {
  8981. var scale = depth * 255.0;
  8982. var fract = scale - Math.floor(scale);
  8983. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  8984. };
  8985. ShadowGenerator.prototype.dispose = function () {
  8986. this._shadowMap.dispose();
  8987. if (this._shadowMap2) {
  8988. this._shadowMap2.dispose();
  8989. }
  8990. if (this._downSamplePostprocess) {
  8991. this._downSamplePostprocess.dispose();
  8992. }
  8993. if (this._boxBlurPostprocess) {
  8994. this._boxBlurPostprocess.dispose();
  8995. }
  8996. };
  8997. ShadowGenerator._FILTER_NONE = 0;
  8998. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  8999. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  9000. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  9001. return ShadowGenerator;
  9002. })();
  9003. BABYLON.ShadowGenerator = ShadowGenerator;
  9004. })(BABYLON || (BABYLON = {}));
  9005. //# sourceMappingURL=babylon.shadowGenerator.js.map
  9006. var BABYLON;
  9007. (function (BABYLON) {
  9008. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  9009. if (boxMin.x > sphereCenter.x + sphereRadius)
  9010. return false;
  9011. if (sphereCenter.x - sphereRadius > boxMax.x)
  9012. return false;
  9013. if (boxMin.y > sphereCenter.y + sphereRadius)
  9014. return false;
  9015. if (sphereCenter.y - sphereRadius > boxMax.y)
  9016. return false;
  9017. if (boxMin.z > sphereCenter.z + sphereRadius)
  9018. return false;
  9019. if (sphereCenter.z - sphereRadius > boxMax.z)
  9020. return false;
  9021. return true;
  9022. };
  9023. var getLowestRoot = function (a, b, c, maxR) {
  9024. var determinant = b * b - 4.0 * a * c;
  9025. var result = { root: 0, found: false };
  9026. if (determinant < 0)
  9027. return result;
  9028. var sqrtD = Math.sqrt(determinant);
  9029. var r1 = (-b - sqrtD) / (2.0 * a);
  9030. var r2 = (-b + sqrtD) / (2.0 * a);
  9031. if (r1 > r2) {
  9032. var temp = r2;
  9033. r2 = r1;
  9034. r1 = temp;
  9035. }
  9036. if (r1 > 0 && r1 < maxR) {
  9037. result.root = r1;
  9038. result.found = true;
  9039. return result;
  9040. }
  9041. if (r2 > 0 && r2 < maxR) {
  9042. result.root = r2;
  9043. result.found = true;
  9044. return result;
  9045. }
  9046. return result;
  9047. };
  9048. var Collider = (function () {
  9049. function Collider() {
  9050. this.radius = new BABYLON.Vector3(1, 1, 1);
  9051. this.retry = 0;
  9052. this.basePointWorld = BABYLON.Vector3.Zero();
  9053. this.velocityWorld = BABYLON.Vector3.Zero();
  9054. this.normalizedVelocity = BABYLON.Vector3.Zero();
  9055. this._collisionPoint = BABYLON.Vector3.Zero();
  9056. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  9057. this._tempVector = BABYLON.Vector3.Zero();
  9058. this._tempVector2 = BABYLON.Vector3.Zero();
  9059. this._tempVector3 = BABYLON.Vector3.Zero();
  9060. this._tempVector4 = BABYLON.Vector3.Zero();
  9061. this._edge = BABYLON.Vector3.Zero();
  9062. this._baseToVertex = BABYLON.Vector3.Zero();
  9063. this._destinationPoint = BABYLON.Vector3.Zero();
  9064. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  9065. this._displacementVector = BABYLON.Vector3.Zero();
  9066. }
  9067. // Methods
  9068. Collider.prototype._initialize = function (source, dir, e) {
  9069. this.velocity = dir;
  9070. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  9071. this.basePoint = source;
  9072. source.multiplyToRef(this.radius, this.basePointWorld);
  9073. dir.multiplyToRef(this.radius, this.velocityWorld);
  9074. this.velocityWorldLength = this.velocityWorld.length();
  9075. this.epsilon = e;
  9076. this.collisionFound = false;
  9077. };
  9078. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  9079. pa.subtractToRef(point, this._tempVector);
  9080. pb.subtractToRef(point, this._tempVector2);
  9081. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  9082. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9083. if (d < 0)
  9084. return false;
  9085. pc.subtractToRef(point, this._tempVector3);
  9086. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  9087. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9088. if (d < 0)
  9089. return false;
  9090. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  9091. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  9092. return d >= 0;
  9093. };
  9094. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  9095. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  9096. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  9097. if (distance > this.velocityWorldLength + max + sphereRadius) {
  9098. return false;
  9099. }
  9100. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  9101. return false;
  9102. return true;
  9103. };
  9104. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  9105. var t0;
  9106. var embeddedInPlane = false;
  9107. //defensive programming, actually not needed.
  9108. if (!trianglePlaneArray) {
  9109. trianglePlaneArray = [];
  9110. }
  9111. if (!trianglePlaneArray[faceIndex]) {
  9112. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  9113. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  9114. }
  9115. var trianglePlane = trianglePlaneArray[faceIndex];
  9116. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  9117. return;
  9118. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  9119. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  9120. if (normalDotVelocity == 0) {
  9121. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  9122. return;
  9123. embeddedInPlane = true;
  9124. t0 = 0;
  9125. }
  9126. else {
  9127. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9128. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  9129. if (t0 > t1) {
  9130. var temp = t1;
  9131. t1 = t0;
  9132. t0 = temp;
  9133. }
  9134. if (t0 > 1.0 || t1 < 0.0)
  9135. return;
  9136. if (t0 < 0)
  9137. t0 = 0;
  9138. if (t0 > 1.0)
  9139. t0 = 1.0;
  9140. }
  9141. this._collisionPoint.copyFromFloats(0, 0, 0);
  9142. var found = false;
  9143. var t = 1.0;
  9144. if (!embeddedInPlane) {
  9145. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  9146. this.velocity.scaleToRef(t0, this._tempVector);
  9147. this._planeIntersectionPoint.addInPlace(this._tempVector);
  9148. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  9149. found = true;
  9150. t = t0;
  9151. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  9152. }
  9153. }
  9154. if (!found) {
  9155. var velocitySquaredLength = this.velocity.lengthSquared();
  9156. var a = velocitySquaredLength;
  9157. this.basePoint.subtractToRef(p1, this._tempVector);
  9158. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9159. var c = this._tempVector.lengthSquared() - 1.0;
  9160. var lowestRoot = getLowestRoot(a, b, c, t);
  9161. if (lowestRoot.found) {
  9162. t = lowestRoot.root;
  9163. found = true;
  9164. this._collisionPoint.copyFrom(p1);
  9165. }
  9166. this.basePoint.subtractToRef(p2, this._tempVector);
  9167. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9168. c = this._tempVector.lengthSquared() - 1.0;
  9169. lowestRoot = getLowestRoot(a, b, c, t);
  9170. if (lowestRoot.found) {
  9171. t = lowestRoot.root;
  9172. found = true;
  9173. this._collisionPoint.copyFrom(p2);
  9174. }
  9175. this.basePoint.subtractToRef(p3, this._tempVector);
  9176. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  9177. c = this._tempVector.lengthSquared() - 1.0;
  9178. lowestRoot = getLowestRoot(a, b, c, t);
  9179. if (lowestRoot.found) {
  9180. t = lowestRoot.root;
  9181. found = true;
  9182. this._collisionPoint.copyFrom(p3);
  9183. }
  9184. p2.subtractToRef(p1, this._edge);
  9185. p1.subtractToRef(this.basePoint, this._baseToVertex);
  9186. var edgeSquaredLength = this._edge.lengthSquared();
  9187. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9188. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9189. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9190. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9191. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9192. lowestRoot = getLowestRoot(a, b, c, t);
  9193. if (lowestRoot.found) {
  9194. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9195. if (f >= 0.0 && f <= 1.0) {
  9196. t = lowestRoot.root;
  9197. found = true;
  9198. this._edge.scaleInPlace(f);
  9199. p1.addToRef(this._edge, this._collisionPoint);
  9200. }
  9201. }
  9202. p3.subtractToRef(p2, this._edge);
  9203. p2.subtractToRef(this.basePoint, this._baseToVertex);
  9204. edgeSquaredLength = this._edge.lengthSquared();
  9205. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9206. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9207. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9208. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9209. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9210. lowestRoot = getLowestRoot(a, b, c, t);
  9211. if (lowestRoot.found) {
  9212. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9213. if (f >= 0.0 && f <= 1.0) {
  9214. t = lowestRoot.root;
  9215. found = true;
  9216. this._edge.scaleInPlace(f);
  9217. p2.addToRef(this._edge, this._collisionPoint);
  9218. }
  9219. }
  9220. p1.subtractToRef(p3, this._edge);
  9221. p3.subtractToRef(this.basePoint, this._baseToVertex);
  9222. edgeSquaredLength = this._edge.lengthSquared();
  9223. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  9224. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  9225. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  9226. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  9227. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  9228. lowestRoot = getLowestRoot(a, b, c, t);
  9229. if (lowestRoot.found) {
  9230. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  9231. if (f >= 0.0 && f <= 1.0) {
  9232. t = lowestRoot.root;
  9233. found = true;
  9234. this._edge.scaleInPlace(f);
  9235. p3.addToRef(this._edge, this._collisionPoint);
  9236. }
  9237. }
  9238. }
  9239. if (found) {
  9240. var distToCollision = t * this.velocity.length();
  9241. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  9242. if (!this.intersectionPoint) {
  9243. this.intersectionPoint = this._collisionPoint.clone();
  9244. }
  9245. else {
  9246. this.intersectionPoint.copyFrom(this._collisionPoint);
  9247. }
  9248. this.nearestDistance = distToCollision;
  9249. this.collisionFound = true;
  9250. }
  9251. }
  9252. };
  9253. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  9254. for (var i = indexStart; i < indexEnd; i += 3) {
  9255. var p1 = pts[indices[i] - decal];
  9256. var p2 = pts[indices[i + 1] - decal];
  9257. var p3 = pts[indices[i + 2] - decal];
  9258. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  9259. }
  9260. };
  9261. Collider.prototype._getResponse = function (pos, vel) {
  9262. pos.addToRef(vel, this._destinationPoint);
  9263. vel.scaleInPlace((this.nearestDistance / vel.length()));
  9264. this.basePoint.addToRef(vel, pos);
  9265. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  9266. this._slidePlaneNormal.normalize();
  9267. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  9268. pos.addInPlace(this._displacementVector);
  9269. this.intersectionPoint.addInPlace(this._displacementVector);
  9270. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  9271. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  9272. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  9273. };
  9274. return Collider;
  9275. })();
  9276. BABYLON.Collider = Collider;
  9277. })(BABYLON || (BABYLON = {}));
  9278. //# sourceMappingURL=babylon.collider.js.map
  9279. var BABYLON;
  9280. (function (BABYLON) {
  9281. //WebWorker code will be inserted to this variable.
  9282. BABYLON.CollisionWorker = "";
  9283. (function (WorkerTaskType) {
  9284. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  9285. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  9286. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  9287. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  9288. var WorkerTaskType = BABYLON.WorkerTaskType;
  9289. (function (WorkerReplyType) {
  9290. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  9291. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  9292. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  9293. var WorkerReplyType = BABYLON.WorkerReplyType;
  9294. var CollisionCoordinatorWorker = (function () {
  9295. function CollisionCoordinatorWorker() {
  9296. var _this = this;
  9297. this._scaledPosition = BABYLON.Vector3.Zero();
  9298. this._scaledVelocity = BABYLON.Vector3.Zero();
  9299. this.onMeshUpdated = function (mesh) {
  9300. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  9301. };
  9302. this.onGeometryUpdated = function (geometry) {
  9303. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  9304. };
  9305. this._afterRender = function () {
  9306. if (!_this._init)
  9307. return;
  9308. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  9309. return;
  9310. }
  9311. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  9312. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  9313. if (_this._runningUpdated > 4) {
  9314. return;
  9315. }
  9316. ++_this._runningUpdated;
  9317. var payload = {
  9318. updatedMeshes: _this._addUpdateMeshesList,
  9319. updatedGeometries: _this._addUpdateGeometriesList,
  9320. removedGeometries: _this._toRemoveGeometryArray,
  9321. removedMeshes: _this._toRemoveMeshesArray
  9322. };
  9323. var message = {
  9324. payload: payload,
  9325. taskType: WorkerTaskType.UPDATE
  9326. };
  9327. var serializable = [];
  9328. for (var id in payload.updatedGeometries) {
  9329. if (payload.updatedGeometries.hasOwnProperty(id)) {
  9330. //prepare transferables
  9331. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  9332. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  9333. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  9334. }
  9335. }
  9336. _this._worker.postMessage(message, serializable);
  9337. _this._addUpdateMeshesList = {};
  9338. _this._addUpdateGeometriesList = {};
  9339. _this._toRemoveGeometryArray = [];
  9340. _this._toRemoveMeshesArray = [];
  9341. };
  9342. this._onMessageFromWorker = function (e) {
  9343. var returnData = e.data;
  9344. if (returnData.error != WorkerReplyType.SUCCESS) {
  9345. //TODO what errors can be returned from the worker?
  9346. BABYLON.Tools.Warn("error returned from worker!");
  9347. return;
  9348. }
  9349. switch (returnData.taskType) {
  9350. case WorkerTaskType.INIT:
  9351. _this._init = true;
  9352. //Update the worked with ALL of the scene's current state
  9353. _this._scene.meshes.forEach(function (mesh) {
  9354. _this.onMeshAdded(mesh);
  9355. });
  9356. _this._scene.getGeometries().forEach(function (geometry) {
  9357. _this.onGeometryAdded(geometry);
  9358. });
  9359. break;
  9360. case WorkerTaskType.UPDATE:
  9361. _this._runningUpdated--;
  9362. break;
  9363. case WorkerTaskType.COLLIDE:
  9364. _this._runningCollisionTask = false;
  9365. var returnPayload = returnData.payload;
  9366. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  9367. return;
  9368. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  9369. //cleanup
  9370. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  9371. break;
  9372. }
  9373. };
  9374. this._collisionsCallbackArray = [];
  9375. this._init = false;
  9376. this._runningUpdated = 0;
  9377. this._runningCollisionTask = false;
  9378. this._addUpdateMeshesList = {};
  9379. this._addUpdateGeometriesList = {};
  9380. this._toRemoveGeometryArray = [];
  9381. this._toRemoveMeshesArray = [];
  9382. }
  9383. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9384. if (!this._init)
  9385. return;
  9386. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  9387. return;
  9388. position.divideToRef(collider.radius, this._scaledPosition);
  9389. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9390. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  9391. var payload = {
  9392. collider: {
  9393. position: this._scaledPosition.asArray(),
  9394. velocity: this._scaledVelocity.asArray(),
  9395. radius: collider.radius.asArray()
  9396. },
  9397. collisionId: collisionIndex,
  9398. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  9399. maximumRetry: maximumRetry
  9400. };
  9401. var message = {
  9402. payload: payload,
  9403. taskType: WorkerTaskType.COLLIDE
  9404. };
  9405. this._worker.postMessage(message);
  9406. };
  9407. CollisionCoordinatorWorker.prototype.init = function (scene) {
  9408. this._scene = scene;
  9409. this._scene.registerAfterRender(this._afterRender);
  9410. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  9411. this._worker = new Worker(workerUrl);
  9412. this._worker.onmessage = this._onMessageFromWorker;
  9413. var message = {
  9414. payload: {},
  9415. taskType: WorkerTaskType.INIT
  9416. };
  9417. this._worker.postMessage(message);
  9418. };
  9419. CollisionCoordinatorWorker.prototype.destroy = function () {
  9420. this._scene.unregisterAfterRender(this._afterRender);
  9421. this._worker.terminate();
  9422. };
  9423. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  9424. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  9425. this.onMeshUpdated(mesh);
  9426. };
  9427. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  9428. this._toRemoveMeshesArray.push(mesh.uniqueId);
  9429. };
  9430. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  9431. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  9432. geometry.onGeometryUpdated = this.onGeometryUpdated;
  9433. this.onGeometryUpdated(geometry);
  9434. };
  9435. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  9436. this._toRemoveGeometryArray.push(geometry.id);
  9437. };
  9438. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  9439. var submeshes = [];
  9440. if (mesh.subMeshes) {
  9441. submeshes = mesh.subMeshes.map(function (sm, idx) {
  9442. return {
  9443. position: idx,
  9444. verticesStart: sm.verticesStart,
  9445. verticesCount: sm.verticesCount,
  9446. indexStart: sm.indexStart,
  9447. indexCount: sm.indexCount,
  9448. hasMaterial: !!sm.getMaterial(),
  9449. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9450. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  9451. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9452. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  9453. };
  9454. });
  9455. }
  9456. var geometryId = mesh.geometry ? mesh.geometry.id : null;
  9457. return {
  9458. uniqueId: mesh.uniqueId,
  9459. id: mesh.id,
  9460. name: mesh.name,
  9461. geometryId: geometryId,
  9462. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  9463. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  9464. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  9465. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  9466. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  9467. subMeshes: submeshes,
  9468. checkCollisions: mesh.checkCollisions
  9469. };
  9470. };
  9471. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  9472. return {
  9473. id: geometry.id,
  9474. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  9475. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  9476. indices: new Int32Array(geometry.getIndices() || []),
  9477. };
  9478. };
  9479. return CollisionCoordinatorWorker;
  9480. })();
  9481. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  9482. var CollisionCoordinatorLegacy = (function () {
  9483. function CollisionCoordinatorLegacy() {
  9484. this._scaledPosition = BABYLON.Vector3.Zero();
  9485. this._scaledVelocity = BABYLON.Vector3.Zero();
  9486. this._finalPosition = BABYLON.Vector3.Zero();
  9487. }
  9488. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  9489. position.divideToRef(collider.radius, this._scaledPosition);
  9490. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9491. collider.collidedMesh = null;
  9492. collider.retry = 0;
  9493. collider.initialVelocity = this._scaledVelocity;
  9494. collider.initialPosition = this._scaledPosition;
  9495. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  9496. this._finalPosition.multiplyInPlace(collider.radius);
  9497. //run the callback
  9498. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  9499. };
  9500. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  9501. this._scene = scene;
  9502. };
  9503. CollisionCoordinatorLegacy.prototype.destroy = function () {
  9504. //Legacy need no destruction method.
  9505. };
  9506. //No update in legacy mode
  9507. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  9508. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  9509. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  9510. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  9511. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  9512. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  9513. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9514. if (excludedMesh === void 0) { excludedMesh = null; }
  9515. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9516. if (collider.retry >= maximumRetry) {
  9517. finalPosition.copyFrom(position);
  9518. return;
  9519. }
  9520. collider._initialize(position, velocity, closeDistance);
  9521. // Check all meshes
  9522. for (var index = 0; index < this._scene.meshes.length; index++) {
  9523. var mesh = this._scene.meshes[index];
  9524. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9525. mesh._checkCollision(collider);
  9526. }
  9527. }
  9528. if (!collider.collisionFound) {
  9529. position.addToRef(velocity, finalPosition);
  9530. return;
  9531. }
  9532. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9533. collider._getResponse(position, velocity);
  9534. }
  9535. if (velocity.length() <= closeDistance) {
  9536. finalPosition.copyFrom(position);
  9537. return;
  9538. }
  9539. collider.retry++;
  9540. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9541. };
  9542. return CollisionCoordinatorLegacy;
  9543. })();
  9544. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  9545. })(BABYLON || (BABYLON = {}));
  9546. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  9547. var BABYLON;
  9548. (function (BABYLON) {
  9549. var VRCameraMetrics = (function () {
  9550. function VRCameraMetrics() {
  9551. this.compensateDistorsion = true;
  9552. }
  9553. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  9554. get: function () {
  9555. return this.hResolution / (2 * this.vResolution);
  9556. },
  9557. enumerable: true,
  9558. configurable: true
  9559. });
  9560. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  9561. get: function () {
  9562. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  9563. },
  9564. enumerable: true,
  9565. configurable: true
  9566. });
  9567. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  9568. get: function () {
  9569. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9570. var h = (4 * meters) / this.hScreenSize;
  9571. return BABYLON.Matrix.Translation(h, 0, 0);
  9572. },
  9573. enumerable: true,
  9574. configurable: true
  9575. });
  9576. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  9577. get: function () {
  9578. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  9579. var h = (4 * meters) / this.hScreenSize;
  9580. return BABYLON.Matrix.Translation(-h, 0, 0);
  9581. },
  9582. enumerable: true,
  9583. configurable: true
  9584. });
  9585. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  9586. get: function () {
  9587. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  9588. },
  9589. enumerable: true,
  9590. configurable: true
  9591. });
  9592. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  9593. get: function () {
  9594. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  9595. },
  9596. enumerable: true,
  9597. configurable: true
  9598. });
  9599. VRCameraMetrics.GetDefault = function () {
  9600. var result = new VRCameraMetrics();
  9601. result.hResolution = 1280;
  9602. result.vResolution = 800;
  9603. result.hScreenSize = 0.149759993;
  9604. result.vScreenSize = 0.0935999975;
  9605. result.vScreenCenter = 0.0467999987,
  9606. result.eyeToScreenDistance = 0.0410000011;
  9607. result.lensSeparationDistance = 0.0635000020;
  9608. result.interpupillaryDistance = 0.0640000030;
  9609. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  9610. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  9611. result.postProcessScaleFactor = 1.714605507808412;
  9612. result.lensCenterOffset = 0.151976421;
  9613. return result;
  9614. };
  9615. return VRCameraMetrics;
  9616. })();
  9617. BABYLON.VRCameraMetrics = VRCameraMetrics;
  9618. var Camera = (function (_super) {
  9619. __extends(Camera, _super);
  9620. function Camera(name, position, scene) {
  9621. _super.call(this, name, scene);
  9622. this.position = position;
  9623. // Members
  9624. this.upVector = BABYLON.Vector3.Up();
  9625. this.orthoLeft = null;
  9626. this.orthoRight = null;
  9627. this.orthoBottom = null;
  9628. this.orthoTop = null;
  9629. this.fov = 0.8;
  9630. this.minZ = 1.0;
  9631. this.maxZ = 10000.0;
  9632. this.inertia = 0.9;
  9633. this.mode = Camera.PERSPECTIVE_CAMERA;
  9634. this.isIntermediate = false;
  9635. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  9636. this.layerMask = 0x0FFFFFFF;
  9637. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  9638. // Camera rig members
  9639. this.cameraRigMode = Camera.RIG_MODE_NONE;
  9640. this._rigCameras = new Array();
  9641. // Cache
  9642. this._computedViewMatrix = BABYLON.Matrix.Identity();
  9643. this._projectionMatrix = new BABYLON.Matrix();
  9644. this._postProcesses = new Array();
  9645. this._postProcessesTakenIndices = [];
  9646. this._activeMeshes = new BABYLON.SmartArray(256);
  9647. this._globalPosition = BABYLON.Vector3.Zero();
  9648. scene.addCamera(this);
  9649. if (!scene.activeCamera) {
  9650. scene.activeCamera = this;
  9651. }
  9652. }
  9653. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  9654. get: function () {
  9655. return Camera._PERSPECTIVE_CAMERA;
  9656. },
  9657. enumerable: true,
  9658. configurable: true
  9659. });
  9660. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  9661. get: function () {
  9662. return Camera._ORTHOGRAPHIC_CAMERA;
  9663. },
  9664. enumerable: true,
  9665. configurable: true
  9666. });
  9667. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  9668. get: function () {
  9669. return Camera._FOVMODE_VERTICAL_FIXED;
  9670. },
  9671. enumerable: true,
  9672. configurable: true
  9673. });
  9674. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  9675. get: function () {
  9676. return Camera._FOVMODE_HORIZONTAL_FIXED;
  9677. },
  9678. enumerable: true,
  9679. configurable: true
  9680. });
  9681. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  9682. get: function () {
  9683. return Camera._RIG_MODE_NONE;
  9684. },
  9685. enumerable: true,
  9686. configurable: true
  9687. });
  9688. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  9689. get: function () {
  9690. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  9691. },
  9692. enumerable: true,
  9693. configurable: true
  9694. });
  9695. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  9696. get: function () {
  9697. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  9698. },
  9699. enumerable: true,
  9700. configurable: true
  9701. });
  9702. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  9703. get: function () {
  9704. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  9705. },
  9706. enumerable: true,
  9707. configurable: true
  9708. });
  9709. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  9710. get: function () {
  9711. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  9712. },
  9713. enumerable: true,
  9714. configurable: true
  9715. });
  9716. Object.defineProperty(Camera, "RIG_MODE_VR", {
  9717. get: function () {
  9718. return Camera._RIG_MODE_VR;
  9719. },
  9720. enumerable: true,
  9721. configurable: true
  9722. });
  9723. Object.defineProperty(Camera.prototype, "globalPosition", {
  9724. get: function () {
  9725. return this._globalPosition;
  9726. },
  9727. enumerable: true,
  9728. configurable: true
  9729. });
  9730. Camera.prototype.getActiveMeshes = function () {
  9731. return this._activeMeshes;
  9732. };
  9733. Camera.prototype.isActiveMesh = function (mesh) {
  9734. return (this._activeMeshes.indexOf(mesh) !== -1);
  9735. };
  9736. //Cache
  9737. Camera.prototype._initCache = function () {
  9738. _super.prototype._initCache.call(this);
  9739. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9740. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9741. this._cache.mode = undefined;
  9742. this._cache.minZ = undefined;
  9743. this._cache.maxZ = undefined;
  9744. this._cache.fov = undefined;
  9745. this._cache.aspectRatio = undefined;
  9746. this._cache.orthoLeft = undefined;
  9747. this._cache.orthoRight = undefined;
  9748. this._cache.orthoBottom = undefined;
  9749. this._cache.orthoTop = undefined;
  9750. this._cache.renderWidth = undefined;
  9751. this._cache.renderHeight = undefined;
  9752. };
  9753. Camera.prototype._updateCache = function (ignoreParentClass) {
  9754. if (!ignoreParentClass) {
  9755. _super.prototype._updateCache.call(this);
  9756. }
  9757. var engine = this.getEngine();
  9758. this._cache.position.copyFrom(this.position);
  9759. this._cache.upVector.copyFrom(this.upVector);
  9760. this._cache.mode = this.mode;
  9761. this._cache.minZ = this.minZ;
  9762. this._cache.maxZ = this.maxZ;
  9763. this._cache.fov = this.fov;
  9764. this._cache.aspectRatio = engine.getAspectRatio(this);
  9765. this._cache.orthoLeft = this.orthoLeft;
  9766. this._cache.orthoRight = this.orthoRight;
  9767. this._cache.orthoBottom = this.orthoBottom;
  9768. this._cache.orthoTop = this.orthoTop;
  9769. this._cache.renderWidth = engine.getRenderWidth();
  9770. this._cache.renderHeight = engine.getRenderHeight();
  9771. };
  9772. Camera.prototype._updateFromScene = function () {
  9773. this.updateCache();
  9774. this._update();
  9775. };
  9776. // Synchronized
  9777. Camera.prototype._isSynchronized = function () {
  9778. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  9779. };
  9780. Camera.prototype._isSynchronizedViewMatrix = function () {
  9781. if (!_super.prototype._isSynchronized.call(this))
  9782. return false;
  9783. return this._cache.position.equals(this.position)
  9784. && this._cache.upVector.equals(this.upVector)
  9785. && this.isSynchronizedWithParent();
  9786. };
  9787. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  9788. var check = this._cache.mode === this.mode
  9789. && this._cache.minZ === this.minZ
  9790. && this._cache.maxZ === this.maxZ;
  9791. if (!check) {
  9792. return false;
  9793. }
  9794. var engine = this.getEngine();
  9795. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9796. check = this._cache.fov === this.fov
  9797. && this._cache.aspectRatio === engine.getAspectRatio(this);
  9798. }
  9799. else {
  9800. check = this._cache.orthoLeft === this.orthoLeft
  9801. && this._cache.orthoRight === this.orthoRight
  9802. && this._cache.orthoBottom === this.orthoBottom
  9803. && this._cache.orthoTop === this.orthoTop
  9804. && this._cache.renderWidth === engine.getRenderWidth()
  9805. && this._cache.renderHeight === engine.getRenderHeight();
  9806. }
  9807. return check;
  9808. };
  9809. // Controls
  9810. Camera.prototype.attachControl = function (element) {
  9811. };
  9812. Camera.prototype.detachControl = function (element) {
  9813. };
  9814. Camera.prototype._update = function () {
  9815. this._checkInputs();
  9816. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  9817. this._updateRigCameras();
  9818. }
  9819. };
  9820. Camera.prototype._checkInputs = function () {
  9821. };
  9822. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  9823. if (insertAt === void 0) { insertAt = null; }
  9824. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  9825. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  9826. return 0;
  9827. }
  9828. if (insertAt == null || insertAt < 0) {
  9829. this._postProcesses.push(postProcess);
  9830. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  9831. return this._postProcesses.length - 1;
  9832. }
  9833. var add = 0;
  9834. if (this._postProcesses[insertAt]) {
  9835. var start = this._postProcesses.length - 1;
  9836. for (var i = start; i >= insertAt + 1; --i) {
  9837. this._postProcesses[i + 1] = this._postProcesses[i];
  9838. }
  9839. add = 1;
  9840. }
  9841. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9842. if (this._postProcessesTakenIndices[i] < insertAt) {
  9843. continue;
  9844. }
  9845. start = this._postProcessesTakenIndices.length - 1;
  9846. for (var j = start; j >= i; --j) {
  9847. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  9848. }
  9849. this._postProcessesTakenIndices[i] = insertAt;
  9850. break;
  9851. }
  9852. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  9853. this._postProcessesTakenIndices.push(insertAt);
  9854. }
  9855. var result = insertAt + add;
  9856. this._postProcesses[result] = postProcess;
  9857. return result;
  9858. };
  9859. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  9860. if (atIndices === void 0) { atIndices = null; }
  9861. var result = [];
  9862. if (!atIndices) {
  9863. var length = this._postProcesses.length;
  9864. for (var i = 0; i < length; i++) {
  9865. if (this._postProcesses[i] !== postProcess) {
  9866. continue;
  9867. }
  9868. delete this._postProcesses[i];
  9869. var index = this._postProcessesTakenIndices.indexOf(i);
  9870. this._postProcessesTakenIndices.splice(index, 1);
  9871. }
  9872. }
  9873. else {
  9874. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  9875. for (i = 0; i < atIndices.length; i++) {
  9876. var foundPostProcess = this._postProcesses[atIndices[i]];
  9877. if (foundPostProcess !== postProcess) {
  9878. result.push(i);
  9879. continue;
  9880. }
  9881. delete this._postProcesses[atIndices[i]];
  9882. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  9883. this._postProcessesTakenIndices.splice(index, 1);
  9884. }
  9885. }
  9886. return result;
  9887. };
  9888. Camera.prototype.getWorldMatrix = function () {
  9889. if (!this._worldMatrix) {
  9890. this._worldMatrix = BABYLON.Matrix.Identity();
  9891. }
  9892. var viewMatrix = this.getViewMatrix();
  9893. viewMatrix.invertToRef(this._worldMatrix);
  9894. return this._worldMatrix;
  9895. };
  9896. Camera.prototype._getViewMatrix = function () {
  9897. return BABYLON.Matrix.Identity();
  9898. };
  9899. Camera.prototype.getViewMatrix = function (force) {
  9900. this._computedViewMatrix = this._computeViewMatrix(force);
  9901. if (!force && this._isSynchronizedViewMatrix()) {
  9902. return this._computedViewMatrix;
  9903. }
  9904. if (!this.parent || !this.parent.getWorldMatrix) {
  9905. this._globalPosition.copyFrom(this.position);
  9906. }
  9907. else {
  9908. if (!this._worldMatrix) {
  9909. this._worldMatrix = BABYLON.Matrix.Identity();
  9910. }
  9911. this._computedViewMatrix.invertToRef(this._worldMatrix);
  9912. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  9913. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  9914. this._computedViewMatrix.invert();
  9915. this._markSyncedWithParent();
  9916. }
  9917. this._currentRenderId = this.getScene().getRenderId();
  9918. return this._computedViewMatrix;
  9919. };
  9920. Camera.prototype._computeViewMatrix = function (force) {
  9921. if (!force && this._isSynchronizedViewMatrix()) {
  9922. return this._computedViewMatrix;
  9923. }
  9924. this._computedViewMatrix = this._getViewMatrix();
  9925. this._currentRenderId = this.getScene().getRenderId();
  9926. return this._computedViewMatrix;
  9927. };
  9928. Camera.prototype.getProjectionMatrix = function (force) {
  9929. if (!force && this._isSynchronizedProjectionMatrix()) {
  9930. return this._projectionMatrix;
  9931. }
  9932. var engine = this.getEngine();
  9933. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  9934. if (this.minZ <= 0) {
  9935. this.minZ = 0.1;
  9936. }
  9937. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  9938. return this._projectionMatrix;
  9939. }
  9940. var halfWidth = engine.getRenderWidth() / 2.0;
  9941. var halfHeight = engine.getRenderHeight() / 2.0;
  9942. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  9943. return this._projectionMatrix;
  9944. };
  9945. Camera.prototype.dispose = function () {
  9946. // Remove from scene
  9947. this.getScene().removeCamera(this);
  9948. while (this._rigCameras.length > 0) {
  9949. this._rigCameras.pop().dispose();
  9950. }
  9951. // Postprocesses
  9952. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  9953. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  9954. }
  9955. };
  9956. // ---- Camera rigs section ----
  9957. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  9958. while (this._rigCameras.length > 0) {
  9959. this._rigCameras.pop().dispose();
  9960. }
  9961. this.cameraRigMode = mode;
  9962. this._cameraRigParams = {};
  9963. switch (this.cameraRigMode) {
  9964. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  9965. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  9966. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  9967. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  9968. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  9969. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  9970. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  9971. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  9972. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  9973. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  9974. break;
  9975. }
  9976. var postProcesses = new Array();
  9977. switch (this.cameraRigMode) {
  9978. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  9979. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]));
  9980. this._rigCameras[0].isIntermediate = true;
  9981. postProcesses.push(new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras[1]));
  9982. postProcesses[1].onApply = function (effect) {
  9983. effect.setTextureFromPostProcess("leftSampler", postProcesses[0]);
  9984. };
  9985. break;
  9986. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  9987. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  9988. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  9989. var isStereoscopicHoriz = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED);
  9990. var firstCamIndex = (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : 0;
  9991. var secondCamIndex = 1 - firstCamIndex;
  9992. postProcesses.push(new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[firstCamIndex]));
  9993. this._rigCameras[firstCamIndex].isIntermediate = true;
  9994. postProcesses.push(new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras[secondCamIndex], postProcesses[0], isStereoscopicHoriz));
  9995. break;
  9996. case Camera.RIG_MODE_VR:
  9997. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  9998. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  9999. var metrics = rigParams.vrCameraMetrics || VRCameraMetrics.GetDefault();
  10000. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  10001. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  10002. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10003. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  10004. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  10005. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  10006. if (metrics.compensateDistorsion) {
  10007. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics));
  10008. }
  10009. this._rigCameras[1]._cameraRigParams.vrMetrics = this._rigCameras[0]._cameraRigParams.vrMetrics;
  10010. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  10011. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  10012. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  10013. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  10014. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  10015. if (metrics.compensateDistorsion) {
  10016. postProcesses.push(new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics));
  10017. }
  10018. break;
  10019. }
  10020. this._update();
  10021. };
  10022. Camera.prototype._getVRProjectionMatrix = function () {
  10023. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  10024. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  10025. return this._projectionMatrix;
  10026. };
  10027. Camera.prototype.setCameraRigParameter = function (name, value) {
  10028. this._cameraRigParams[name] = value;
  10029. //provisionnally:
  10030. if (name === "interaxialDistance") {
  10031. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  10032. }
  10033. };
  10034. /**
  10035. * May needs to be overridden by children so sub has required properties to be copied
  10036. */
  10037. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  10038. return null;
  10039. };
  10040. /**
  10041. * May needs to be overridden by children
  10042. */
  10043. Camera.prototype._updateRigCameras = function () {
  10044. for (var i = 0; i < this._rigCameras.length; i++) {
  10045. this._rigCameras[i].minZ = this.minZ;
  10046. this._rigCameras[i].maxZ = this.maxZ;
  10047. this._rigCameras[i].fov = this.fov;
  10048. }
  10049. // only update viewport when ANAGLYPH
  10050. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  10051. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  10052. }
  10053. };
  10054. // Statics
  10055. Camera._PERSPECTIVE_CAMERA = 0;
  10056. Camera._ORTHOGRAPHIC_CAMERA = 1;
  10057. Camera._FOVMODE_VERTICAL_FIXED = 0;
  10058. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  10059. Camera._RIG_MODE_NONE = 0;
  10060. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  10061. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  10062. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  10063. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  10064. Camera._RIG_MODE_VR = 20;
  10065. return Camera;
  10066. })(BABYLON.Node);
  10067. BABYLON.Camera = Camera;
  10068. })(BABYLON || (BABYLON = {}));
  10069. //# sourceMappingURL=babylon.camera.js.map
  10070. var BABYLON;
  10071. (function (BABYLON) {
  10072. var TargetCamera = (function (_super) {
  10073. __extends(TargetCamera, _super);
  10074. function TargetCamera(name, position, scene) {
  10075. _super.call(this, name, position, scene);
  10076. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10077. this.cameraRotation = new BABYLON.Vector2(0, 0);
  10078. this.rotation = new BABYLON.Vector3(0, 0, 0);
  10079. this.speed = 2.0;
  10080. this.noRotationConstraint = false;
  10081. this.lockedTarget = null;
  10082. this._currentTarget = BABYLON.Vector3.Zero();
  10083. this._viewMatrix = BABYLON.Matrix.Zero();
  10084. this._camMatrix = BABYLON.Matrix.Zero();
  10085. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  10086. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  10087. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  10088. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  10089. this._lookAtTemp = BABYLON.Matrix.Zero();
  10090. this._tempMatrix = BABYLON.Matrix.Zero();
  10091. }
  10092. TargetCamera.prototype._getLockedTargetPosition = function () {
  10093. if (!this.lockedTarget) {
  10094. return null;
  10095. }
  10096. return this.lockedTarget.position || this.lockedTarget;
  10097. };
  10098. // Cache
  10099. TargetCamera.prototype._initCache = function () {
  10100. _super.prototype._initCache.call(this);
  10101. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10102. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10103. };
  10104. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  10105. if (!ignoreParentClass) {
  10106. _super.prototype._updateCache.call(this);
  10107. }
  10108. var lockedTargetPosition = this._getLockedTargetPosition();
  10109. if (!lockedTargetPosition) {
  10110. this._cache.lockedTarget = null;
  10111. }
  10112. else {
  10113. if (!this._cache.lockedTarget) {
  10114. this._cache.lockedTarget = lockedTargetPosition.clone();
  10115. }
  10116. else {
  10117. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  10118. }
  10119. }
  10120. this._cache.rotation.copyFrom(this.rotation);
  10121. };
  10122. // Synchronized
  10123. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  10124. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  10125. return false;
  10126. }
  10127. var lockedTargetPosition = this._getLockedTargetPosition();
  10128. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  10129. && this._cache.rotation.equals(this.rotation);
  10130. };
  10131. // Methods
  10132. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  10133. var engine = this.getEngine();
  10134. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  10135. };
  10136. // Target
  10137. TargetCamera.prototype.setTarget = function (target) {
  10138. this.upVector.normalize();
  10139. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  10140. this._camMatrix.invert();
  10141. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  10142. var vDir = target.subtract(this.position);
  10143. if (vDir.x >= 0.0) {
  10144. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  10145. }
  10146. else {
  10147. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  10148. }
  10149. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  10150. if (isNaN(this.rotation.x)) {
  10151. this.rotation.x = 0;
  10152. }
  10153. if (isNaN(this.rotation.y)) {
  10154. this.rotation.y = 0;
  10155. }
  10156. if (isNaN(this.rotation.z)) {
  10157. this.rotation.z = 0;
  10158. }
  10159. };
  10160. TargetCamera.prototype.getTarget = function () {
  10161. return this._currentTarget;
  10162. };
  10163. TargetCamera.prototype._decideIfNeedsToMove = function () {
  10164. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10165. };
  10166. TargetCamera.prototype._updatePosition = function () {
  10167. this.position.addInPlace(this.cameraDirection);
  10168. };
  10169. TargetCamera.prototype._checkInputs = function () {
  10170. var needToMove = this._decideIfNeedsToMove();
  10171. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  10172. // Move
  10173. if (needToMove) {
  10174. this._updatePosition();
  10175. }
  10176. // Rotate
  10177. if (needToRotate) {
  10178. this.rotation.x += this.cameraRotation.x;
  10179. this.rotation.y += this.cameraRotation.y;
  10180. if (!this.noRotationConstraint) {
  10181. var limit = (Math.PI / 2) * 0.95;
  10182. if (this.rotation.x > limit)
  10183. this.rotation.x = limit;
  10184. if (this.rotation.x < -limit)
  10185. this.rotation.x = -limit;
  10186. }
  10187. }
  10188. // Inertia
  10189. if (needToMove) {
  10190. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  10191. this.cameraDirection.x = 0;
  10192. }
  10193. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  10194. this.cameraDirection.y = 0;
  10195. }
  10196. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  10197. this.cameraDirection.z = 0;
  10198. }
  10199. this.cameraDirection.scaleInPlace(this.inertia);
  10200. }
  10201. if (needToRotate) {
  10202. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  10203. this.cameraRotation.x = 0;
  10204. }
  10205. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  10206. this.cameraRotation.y = 0;
  10207. }
  10208. this.cameraRotation.scaleInPlace(this.inertia);
  10209. }
  10210. _super.prototype._checkInputs.call(this);
  10211. };
  10212. TargetCamera.prototype._getViewMatrix = function () {
  10213. if (!this.lockedTarget) {
  10214. // Compute
  10215. if (this.upVector.x !== 0 || this.upVector.y !== 1.0 || this.upVector.z !== 0) {
  10216. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  10217. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10218. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  10219. this._lookAtTemp.invert();
  10220. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  10221. }
  10222. else {
  10223. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10224. }
  10225. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10226. // Computing target and final matrix
  10227. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10228. }
  10229. else {
  10230. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  10231. }
  10232. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  10233. return this._viewMatrix;
  10234. };
  10235. TargetCamera.prototype._getVRViewMatrix = function () {
  10236. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  10237. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  10238. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._cameraRigParams.vrActualUp);
  10239. // Computing target and final matrix
  10240. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  10241. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._cameraRigParams.vrActualUp, this._cameraRigParams.vrWorkMatrix);
  10242. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._viewMatrix);
  10243. return this._viewMatrix;
  10244. };
  10245. /**
  10246. * @override
  10247. * Override Camera.createRigCamera
  10248. */
  10249. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  10250. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  10251. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  10252. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10253. rigCamera._cameraRigParams = {};
  10254. rigCamera._cameraRigParams.vrActualUp = new BABYLON.Vector3(0, 0, 0);
  10255. rigCamera._getViewMatrix = rigCamera._getVRViewMatrix;
  10256. }
  10257. return rigCamera;
  10258. }
  10259. return null;
  10260. };
  10261. /**
  10262. * @override
  10263. * Override Camera._updateRigCameras
  10264. */
  10265. TargetCamera.prototype._updateRigCameras = function () {
  10266. switch (this.cameraRigMode) {
  10267. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  10268. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  10269. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  10270. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  10271. case BABYLON.Camera.RIG_MODE_VR:
  10272. var camLeft = this._rigCameras[0];
  10273. var camRight = this._rigCameras[1];
  10274. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR) {
  10275. camLeft.rotation.x = camRight.rotation.x = this.rotation.x;
  10276. camLeft.rotation.y = camRight.rotation.y = this.rotation.y;
  10277. camLeft.rotation.z = camRight.rotation.z = this.rotation.z;
  10278. camLeft.position.copyFrom(this.position);
  10279. camRight.position.copyFrom(this.position);
  10280. }
  10281. else {
  10282. camLeft.setTarget(this.getTarget());
  10283. camRight.setTarget(this.getTarget());
  10284. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  10285. this._getRigCamPosition(-this._cameraRigParams.stereoHalfAngle, camLeft.position);
  10286. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle, camRight.position);
  10287. }
  10288. break;
  10289. }
  10290. _super.prototype._updateRigCameras.call(this);
  10291. };
  10292. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  10293. if (!this._rigCamTransformMatrix) {
  10294. this._rigCamTransformMatrix = new BABYLON.Matrix();
  10295. }
  10296. var target = this.getTarget();
  10297. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  10298. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  10299. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  10300. };
  10301. return TargetCamera;
  10302. })(BABYLON.Camera);
  10303. BABYLON.TargetCamera = TargetCamera;
  10304. })(BABYLON || (BABYLON = {}));
  10305. //# sourceMappingURL=babylon.targetCamera.js.map
  10306. var BABYLON;
  10307. (function (BABYLON) {
  10308. var FreeCamera = (function (_super) {
  10309. __extends(FreeCamera, _super);
  10310. function FreeCamera(name, position, scene) {
  10311. var _this = this;
  10312. _super.call(this, name, position, scene);
  10313. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10314. this.keysUp = [38];
  10315. this.keysDown = [40];
  10316. this.keysLeft = [37];
  10317. this.keysRight = [39];
  10318. this.checkCollisions = false;
  10319. this.applyGravity = false;
  10320. this.angularSensibility = 2000.0;
  10321. this._keys = [];
  10322. this._collider = new BABYLON.Collider();
  10323. this._needMoveForGravity = false;
  10324. this._oldPosition = BABYLON.Vector3.Zero();
  10325. this._diffPosition = BABYLON.Vector3.Zero();
  10326. this._newPosition = BABYLON.Vector3.Zero();
  10327. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10328. if (collidedMesh === void 0) { collidedMesh = null; }
  10329. //TODO move this to the collision coordinator!
  10330. if (_this.getScene().workerCollisions)
  10331. newPosition.multiplyInPlace(_this._collider.radius);
  10332. var updatePosition = function (newPos) {
  10333. _this._newPosition.copyFrom(newPos);
  10334. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  10335. var oldPosition = _this.position.clone();
  10336. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  10337. _this.position.addInPlace(_this._diffPosition);
  10338. if (_this.onCollide && collidedMesh) {
  10339. _this.onCollide(collidedMesh);
  10340. }
  10341. }
  10342. };
  10343. updatePosition(newPosition);
  10344. };
  10345. }
  10346. // Controls
  10347. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  10348. var _this = this;
  10349. var previousPosition;
  10350. var engine = this.getEngine();
  10351. if (this._attachedElement) {
  10352. return;
  10353. }
  10354. this._attachedElement = element;
  10355. if (this._onMouseDown === undefined) {
  10356. this._onMouseDown = function (evt) {
  10357. previousPosition = {
  10358. x: evt.clientX,
  10359. y: evt.clientY
  10360. };
  10361. if (!noPreventDefault) {
  10362. evt.preventDefault();
  10363. }
  10364. };
  10365. this._onMouseUp = function (evt) {
  10366. previousPosition = null;
  10367. if (!noPreventDefault) {
  10368. evt.preventDefault();
  10369. }
  10370. };
  10371. this._onMouseOut = function (evt) {
  10372. previousPosition = null;
  10373. _this._keys = [];
  10374. if (!noPreventDefault) {
  10375. evt.preventDefault();
  10376. }
  10377. };
  10378. this._onMouseMove = function (evt) {
  10379. if (!previousPosition && !engine.isPointerLock) {
  10380. return;
  10381. }
  10382. var offsetX;
  10383. var offsetY;
  10384. if (!engine.isPointerLock) {
  10385. offsetX = evt.clientX - previousPosition.x;
  10386. offsetY = evt.clientY - previousPosition.y;
  10387. }
  10388. else {
  10389. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10390. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10391. }
  10392. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  10393. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  10394. previousPosition = {
  10395. x: evt.clientX,
  10396. y: evt.clientY
  10397. };
  10398. if (!noPreventDefault) {
  10399. evt.preventDefault();
  10400. }
  10401. };
  10402. this._onKeyDown = function (evt) {
  10403. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10404. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10405. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10406. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10407. var index = _this._keys.indexOf(evt.keyCode);
  10408. if (index === -1) {
  10409. _this._keys.push(evt.keyCode);
  10410. }
  10411. if (!noPreventDefault) {
  10412. evt.preventDefault();
  10413. }
  10414. }
  10415. };
  10416. this._onKeyUp = function (evt) {
  10417. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10418. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10419. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10420. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10421. var index = _this._keys.indexOf(evt.keyCode);
  10422. if (index >= 0) {
  10423. _this._keys.splice(index, 1);
  10424. }
  10425. if (!noPreventDefault) {
  10426. evt.preventDefault();
  10427. }
  10428. }
  10429. };
  10430. this._onLostFocus = function () {
  10431. _this._keys = [];
  10432. };
  10433. this._reset = function () {
  10434. _this._keys = [];
  10435. previousPosition = null;
  10436. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  10437. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  10438. };
  10439. }
  10440. element.addEventListener("mousedown", this._onMouseDown, false);
  10441. element.addEventListener("mouseup", this._onMouseUp, false);
  10442. element.addEventListener("mouseout", this._onMouseOut, false);
  10443. element.addEventListener("mousemove", this._onMouseMove, false);
  10444. BABYLON.Tools.RegisterTopRootEvents([
  10445. { name: "keydown", handler: this._onKeyDown },
  10446. { name: "keyup", handler: this._onKeyUp },
  10447. { name: "blur", handler: this._onLostFocus }
  10448. ]);
  10449. };
  10450. FreeCamera.prototype.detachControl = function (element) {
  10451. if (this._attachedElement != element) {
  10452. return;
  10453. }
  10454. element.removeEventListener("mousedown", this._onMouseDown);
  10455. element.removeEventListener("mouseup", this._onMouseUp);
  10456. element.removeEventListener("mouseout", this._onMouseOut);
  10457. element.removeEventListener("mousemove", this._onMouseMove);
  10458. BABYLON.Tools.UnregisterTopRootEvents([
  10459. { name: "keydown", handler: this._onKeyDown },
  10460. { name: "keyup", handler: this._onKeyUp },
  10461. { name: "blur", handler: this._onLostFocus }
  10462. ]);
  10463. this._attachedElement = null;
  10464. if (this._reset) {
  10465. this._reset();
  10466. }
  10467. };
  10468. FreeCamera.prototype._collideWithWorld = function (velocity) {
  10469. var globalPosition;
  10470. if (this.parent) {
  10471. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  10472. }
  10473. else {
  10474. globalPosition = this.position;
  10475. }
  10476. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  10477. this._collider.radius = this.ellipsoid;
  10478. //add gravity to the velocity to prevent the dual-collision checking
  10479. if (this.applyGravity) {
  10480. velocity.addInPlace(this.getScene().gravity);
  10481. }
  10482. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, velocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  10483. };
  10484. FreeCamera.prototype._checkInputs = function () {
  10485. if (!this._localDirection) {
  10486. this._localDirection = BABYLON.Vector3.Zero();
  10487. this._transformedDirection = BABYLON.Vector3.Zero();
  10488. }
  10489. // Keyboard
  10490. for (var index = 0; index < this._keys.length; index++) {
  10491. var keyCode = this._keys[index];
  10492. var speed = this._computeLocalCameraSpeed();
  10493. if (this.keysLeft.indexOf(keyCode) !== -1) {
  10494. this._localDirection.copyFromFloats(-speed, 0, 0);
  10495. }
  10496. else if (this.keysUp.indexOf(keyCode) !== -1) {
  10497. this._localDirection.copyFromFloats(0, 0, speed);
  10498. }
  10499. else if (this.keysRight.indexOf(keyCode) !== -1) {
  10500. this._localDirection.copyFromFloats(speed, 0, 0);
  10501. }
  10502. else if (this.keysDown.indexOf(keyCode) !== -1) {
  10503. this._localDirection.copyFromFloats(0, 0, -speed);
  10504. }
  10505. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  10506. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  10507. this.cameraDirection.addInPlace(this._transformedDirection);
  10508. }
  10509. _super.prototype._checkInputs.call(this);
  10510. };
  10511. FreeCamera.prototype._decideIfNeedsToMove = function () {
  10512. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  10513. };
  10514. FreeCamera.prototype._updatePosition = function () {
  10515. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  10516. this._collideWithWorld(this.cameraDirection);
  10517. }
  10518. else {
  10519. this.position.addInPlace(this.cameraDirection);
  10520. }
  10521. };
  10522. return FreeCamera;
  10523. })(BABYLON.TargetCamera);
  10524. BABYLON.FreeCamera = FreeCamera;
  10525. })(BABYLON || (BABYLON = {}));
  10526. //# sourceMappingURL=babylon.freeCamera.js.map
  10527. var BABYLON;
  10528. (function (BABYLON) {
  10529. var FollowCamera = (function (_super) {
  10530. __extends(FollowCamera, _super);
  10531. function FollowCamera(name, position, scene) {
  10532. _super.call(this, name, position, scene);
  10533. this.radius = 12;
  10534. this.rotationOffset = 0;
  10535. this.heightOffset = 4;
  10536. this.cameraAcceleration = 0.05;
  10537. this.maxCameraSpeed = 20;
  10538. }
  10539. FollowCamera.prototype.getRadians = function (degrees) {
  10540. return degrees * Math.PI / 180;
  10541. };
  10542. FollowCamera.prototype.follow = function (cameraTarget) {
  10543. if (!cameraTarget)
  10544. return;
  10545. var yRotation;
  10546. if (cameraTarget.rotationQuaternion) {
  10547. var rotMatrix = new BABYLON.Matrix();
  10548. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  10549. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  10550. }
  10551. else {
  10552. yRotation = cameraTarget.rotation.y;
  10553. }
  10554. var radians = this.getRadians(this.rotationOffset) + yRotation;
  10555. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  10556. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  10557. var dx = targetX - this.position.x;
  10558. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  10559. var dz = (targetZ) - this.position.z;
  10560. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  10561. var vy = dy * this.cameraAcceleration;
  10562. var vz = dz * this.cameraAcceleration * 2;
  10563. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  10564. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10565. }
  10566. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  10567. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10568. }
  10569. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  10570. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  10571. }
  10572. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  10573. this.setTarget(cameraTarget.position);
  10574. };
  10575. FollowCamera.prototype._checkInputs = function () {
  10576. _super.prototype._checkInputs.call(this);
  10577. this.follow(this.target);
  10578. };
  10579. return FollowCamera;
  10580. })(BABYLON.TargetCamera);
  10581. BABYLON.FollowCamera = FollowCamera;
  10582. })(BABYLON || (BABYLON = {}));
  10583. //# sourceMappingURL=babylon.followCamera.js.map
  10584. var BABYLON;
  10585. (function (BABYLON) {
  10586. // We're mainly based on the logic defined into the FreeCamera code
  10587. var TouchCamera = (function (_super) {
  10588. __extends(TouchCamera, _super);
  10589. function TouchCamera(name, position, scene) {
  10590. _super.call(this, name, position, scene);
  10591. this._offsetX = null;
  10592. this._offsetY = null;
  10593. this._pointerCount = 0;
  10594. this._pointerPressed = [];
  10595. this.angularSensibility = 200000.0;
  10596. this.moveSensibility = 500.0;
  10597. }
  10598. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  10599. var _this = this;
  10600. var previousPosition;
  10601. if (this._attachedCanvas) {
  10602. return;
  10603. }
  10604. this._attachedCanvas = canvas;
  10605. if (this._onPointerDown === undefined) {
  10606. this._onPointerDown = function (evt) {
  10607. if (!noPreventDefault) {
  10608. evt.preventDefault();
  10609. }
  10610. _this._pointerPressed.push(evt.pointerId);
  10611. if (_this._pointerPressed.length !== 1) {
  10612. return;
  10613. }
  10614. previousPosition = {
  10615. x: evt.clientX,
  10616. y: evt.clientY
  10617. };
  10618. };
  10619. this._onPointerUp = function (evt) {
  10620. if (!noPreventDefault) {
  10621. evt.preventDefault();
  10622. }
  10623. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10624. if (index === -1) {
  10625. return;
  10626. }
  10627. _this._pointerPressed.splice(index, 1);
  10628. if (index != 0) {
  10629. return;
  10630. }
  10631. previousPosition = null;
  10632. _this._offsetX = null;
  10633. _this._offsetY = null;
  10634. };
  10635. this._onPointerMove = function (evt) {
  10636. if (!noPreventDefault) {
  10637. evt.preventDefault();
  10638. }
  10639. if (!previousPosition) {
  10640. return;
  10641. }
  10642. var index = _this._pointerPressed.indexOf(evt.pointerId);
  10643. if (index != 0) {
  10644. return;
  10645. }
  10646. _this._offsetX = evt.clientX - previousPosition.x;
  10647. _this._offsetY = -(evt.clientY - previousPosition.y);
  10648. };
  10649. this._onLostFocus = function () {
  10650. _this._offsetX = null;
  10651. _this._offsetY = null;
  10652. };
  10653. }
  10654. canvas.addEventListener("pointerdown", this._onPointerDown);
  10655. canvas.addEventListener("pointerup", this._onPointerUp);
  10656. canvas.addEventListener("pointerout", this._onPointerUp);
  10657. canvas.addEventListener("pointermove", this._onPointerMove);
  10658. BABYLON.Tools.RegisterTopRootEvents([
  10659. { name: "blur", handler: this._onLostFocus }
  10660. ]);
  10661. };
  10662. TouchCamera.prototype.detachControl = function (canvas) {
  10663. if (this._attachedCanvas != canvas) {
  10664. return;
  10665. }
  10666. canvas.removeEventListener("pointerdown", this._onPointerDown);
  10667. canvas.removeEventListener("pointerup", this._onPointerUp);
  10668. canvas.removeEventListener("pointerout", this._onPointerUp);
  10669. canvas.removeEventListener("pointermove", this._onPointerMove);
  10670. BABYLON.Tools.UnregisterTopRootEvents([
  10671. { name: "blur", handler: this._onLostFocus }
  10672. ]);
  10673. this._attachedCanvas = null;
  10674. };
  10675. TouchCamera.prototype._checkInputs = function () {
  10676. if (!this._offsetX) {
  10677. return;
  10678. }
  10679. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  10680. if (this._pointerPressed.length > 1) {
  10681. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  10682. }
  10683. else {
  10684. var speed = this._computeLocalCameraSpeed();
  10685. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  10686. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  10687. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  10688. }
  10689. _super.prototype._checkInputs.call(this);
  10690. };
  10691. return TouchCamera;
  10692. })(BABYLON.FreeCamera);
  10693. BABYLON.TouchCamera = TouchCamera;
  10694. })(BABYLON || (BABYLON = {}));
  10695. //# sourceMappingURL=babylon.touchCamera.js.map
  10696. var BABYLON;
  10697. (function (BABYLON) {
  10698. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  10699. var ArcRotateCamera = (function (_super) {
  10700. __extends(ArcRotateCamera, _super);
  10701. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  10702. var _this = this;
  10703. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  10704. this.alpha = alpha;
  10705. this.beta = beta;
  10706. this.radius = radius;
  10707. this.target = target;
  10708. this.inertialAlphaOffset = 0;
  10709. this.inertialBetaOffset = 0;
  10710. this.inertialRadiusOffset = 0;
  10711. this.lowerAlphaLimit = null;
  10712. this.upperAlphaLimit = null;
  10713. this.lowerBetaLimit = 0.01;
  10714. this.upperBetaLimit = Math.PI;
  10715. this.lowerRadiusLimit = null;
  10716. this.upperRadiusLimit = null;
  10717. this.angularSensibility = 1000.0;
  10718. this.wheelPrecision = 3.0;
  10719. this.pinchPrecision = 2.0;
  10720. this.keysUp = [38];
  10721. this.keysDown = [40];
  10722. this.keysLeft = [37];
  10723. this.keysRight = [39];
  10724. this.zoomOnFactor = 1;
  10725. this.targetScreenOffset = BABYLON.Vector2.Zero();
  10726. this.pinchInwards = true;
  10727. this.allowUpsideDown = true;
  10728. this._keys = [];
  10729. this._viewMatrix = new BABYLON.Matrix();
  10730. this.checkCollisions = false;
  10731. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  10732. this._collider = new BABYLON.Collider();
  10733. this._previousPosition = BABYLON.Vector3.Zero();
  10734. this._collisionVelocity = BABYLON.Vector3.Zero();
  10735. this._newPosition = BABYLON.Vector3.Zero();
  10736. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10737. if (collidedMesh === void 0) { collidedMesh = null; }
  10738. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  10739. newPosition.multiplyInPlace(_this._collider.radius);
  10740. }
  10741. if (!collidedMesh) {
  10742. _this._previousPosition.copyFrom(_this.position);
  10743. }
  10744. else {
  10745. _this.setPosition(_this.position);
  10746. if (_this.onCollide) {
  10747. _this.onCollide(collidedMesh);
  10748. }
  10749. }
  10750. // Recompute because of constraints
  10751. var cosa = Math.cos(_this.alpha);
  10752. var sina = Math.sin(_this.alpha);
  10753. var cosb = Math.cos(_this.beta);
  10754. var sinb = Math.sin(_this.beta);
  10755. var target = _this._getTargetPosition();
  10756. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  10757. _this.position.copyFrom(_this._newPosition);
  10758. var up = _this.upVector;
  10759. if (_this.allowUpsideDown && _this.beta < 0) {
  10760. var up = up.clone();
  10761. up = up.negate();
  10762. }
  10763. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  10764. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  10765. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  10766. _this._collisionTriggered = false;
  10767. };
  10768. if (!this.target) {
  10769. this.target = BABYLON.Vector3.Zero();
  10770. }
  10771. this.getViewMatrix();
  10772. }
  10773. ArcRotateCamera.prototype._getTargetPosition = function () {
  10774. return this.target.position || this.target;
  10775. };
  10776. // Cache
  10777. ArcRotateCamera.prototype._initCache = function () {
  10778. _super.prototype._initCache.call(this);
  10779. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  10780. this._cache.alpha = undefined;
  10781. this._cache.beta = undefined;
  10782. this._cache.radius = undefined;
  10783. this._cache.targetScreenOffset = undefined;
  10784. };
  10785. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  10786. if (!ignoreParentClass) {
  10787. _super.prototype._updateCache.call(this);
  10788. }
  10789. this._cache.target.copyFrom(this._getTargetPosition());
  10790. this._cache.alpha = this.alpha;
  10791. this._cache.beta = this.beta;
  10792. this._cache.radius = this.radius;
  10793. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  10794. };
  10795. // Synchronized
  10796. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  10797. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  10798. return false;
  10799. return this._cache.target.equals(this._getTargetPosition())
  10800. && this._cache.alpha === this.alpha
  10801. && this._cache.beta === this.beta
  10802. && this._cache.radius === this.radius
  10803. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  10804. };
  10805. // Methods
  10806. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  10807. var _this = this;
  10808. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  10809. var previousPinchDistance = 0;
  10810. var pointers = new BABYLON.SmartCollection();
  10811. if (this._attachedElement) {
  10812. return;
  10813. }
  10814. this._attachedElement = element;
  10815. var engine = this.getEngine();
  10816. if (this._onPointerDown === undefined) {
  10817. this._onPointerDown = function (evt) {
  10818. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  10819. cacheSoloPointer = pointers.item(evt.pointerId);
  10820. if (!noPreventDefault) {
  10821. evt.preventDefault();
  10822. }
  10823. };
  10824. this._onPointerUp = function (evt) {
  10825. cacheSoloPointer = null;
  10826. previousPinchDistance = 0;
  10827. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  10828. //but emptying completly pointers collection is required to fix a bug on iPhone :
  10829. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  10830. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  10831. pointers.empty();
  10832. if (!noPreventDefault) {
  10833. evt.preventDefault();
  10834. }
  10835. };
  10836. this._onPointerMove = function (evt) {
  10837. if (!noPreventDefault) {
  10838. evt.preventDefault();
  10839. }
  10840. switch (pointers.count) {
  10841. case 1:
  10842. var offsetX = evt.clientX - cacheSoloPointer.x;
  10843. var offsetY = evt.clientY - cacheSoloPointer.y;
  10844. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  10845. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  10846. cacheSoloPointer.x = evt.clientX;
  10847. cacheSoloPointer.y = evt.clientY;
  10848. break;
  10849. case 2:
  10850. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  10851. pointers.item(evt.pointerId).x = evt.clientX;
  10852. pointers.item(evt.pointerId).y = evt.clientY;
  10853. var direction = _this.pinchInwards ? 1 : -1;
  10854. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  10855. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  10856. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  10857. if (previousPinchDistance === 0) {
  10858. previousPinchDistance = pinchSquaredDistance;
  10859. return;
  10860. }
  10861. if (pinchSquaredDistance !== previousPinchDistance) {
  10862. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * _this.angularSensibility * direction);
  10863. previousPinchDistance = pinchSquaredDistance;
  10864. }
  10865. break;
  10866. default:
  10867. if (pointers.item(evt.pointerId)) {
  10868. pointers.item(evt.pointerId).x = evt.clientX;
  10869. pointers.item(evt.pointerId).y = evt.clientY;
  10870. }
  10871. }
  10872. };
  10873. this._onMouseMove = function (evt) {
  10874. if (!engine.isPointerLock) {
  10875. return;
  10876. }
  10877. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  10878. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  10879. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  10880. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  10881. if (!noPreventDefault) {
  10882. evt.preventDefault();
  10883. }
  10884. };
  10885. this._wheel = function (event) {
  10886. var delta = 0;
  10887. if (event.wheelDelta) {
  10888. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  10889. }
  10890. else if (event.detail) {
  10891. delta = -event.detail / _this.wheelPrecision;
  10892. }
  10893. if (delta)
  10894. _this.inertialRadiusOffset += delta;
  10895. if (event.preventDefault) {
  10896. if (!noPreventDefault) {
  10897. event.preventDefault();
  10898. }
  10899. }
  10900. };
  10901. this._onKeyDown = function (evt) {
  10902. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10903. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10904. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10905. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10906. var index = _this._keys.indexOf(evt.keyCode);
  10907. if (index === -1) {
  10908. _this._keys.push(evt.keyCode);
  10909. }
  10910. if (evt.preventDefault) {
  10911. if (!noPreventDefault) {
  10912. evt.preventDefault();
  10913. }
  10914. }
  10915. }
  10916. };
  10917. this._onKeyUp = function (evt) {
  10918. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  10919. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  10920. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  10921. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  10922. var index = _this._keys.indexOf(evt.keyCode);
  10923. if (index >= 0) {
  10924. _this._keys.splice(index, 1);
  10925. }
  10926. if (evt.preventDefault) {
  10927. if (!noPreventDefault) {
  10928. evt.preventDefault();
  10929. }
  10930. }
  10931. }
  10932. };
  10933. this._onLostFocus = function () {
  10934. _this._keys = [];
  10935. pointers.empty();
  10936. previousPinchDistance = 0;
  10937. cacheSoloPointer = null;
  10938. };
  10939. this._onGestureStart = function (e) {
  10940. if (window.MSGesture === undefined) {
  10941. return;
  10942. }
  10943. if (!_this._MSGestureHandler) {
  10944. _this._MSGestureHandler = new MSGesture();
  10945. _this._MSGestureHandler.target = element;
  10946. }
  10947. _this._MSGestureHandler.addPointer(e.pointerId);
  10948. };
  10949. this._onGesture = function (e) {
  10950. _this.radius *= e.scale;
  10951. if (e.preventDefault) {
  10952. if (!noPreventDefault) {
  10953. e.stopPropagation();
  10954. e.preventDefault();
  10955. }
  10956. }
  10957. };
  10958. this._reset = function () {
  10959. _this._keys = [];
  10960. _this.inertialAlphaOffset = 0;
  10961. _this.inertialBetaOffset = 0;
  10962. _this.inertialRadiusOffset = 0;
  10963. pointers.empty();
  10964. previousPinchDistance = 0;
  10965. cacheSoloPointer = null;
  10966. };
  10967. }
  10968. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  10969. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  10970. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  10971. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  10972. element.addEventListener("mousemove", this._onMouseMove, false);
  10973. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  10974. element.addEventListener("MSGestureChange", this._onGesture, false);
  10975. element.addEventListener('mousewheel', this._wheel, false);
  10976. element.addEventListener('DOMMouseScroll', this._wheel, false);
  10977. BABYLON.Tools.RegisterTopRootEvents([
  10978. { name: "keydown", handler: this._onKeyDown },
  10979. { name: "keyup", handler: this._onKeyUp },
  10980. { name: "blur", handler: this._onLostFocus }
  10981. ]);
  10982. };
  10983. ArcRotateCamera.prototype.detachControl = function (element) {
  10984. if (this._attachedElement !== element) {
  10985. return;
  10986. }
  10987. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  10988. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  10989. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  10990. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  10991. element.removeEventListener("mousemove", this._onMouseMove);
  10992. element.removeEventListener("MSPointerDown", this._onGestureStart);
  10993. element.removeEventListener("MSGestureChange", this._onGesture);
  10994. element.removeEventListener('mousewheel', this._wheel);
  10995. element.removeEventListener('DOMMouseScroll', this._wheel);
  10996. BABYLON.Tools.UnregisterTopRootEvents([
  10997. { name: "keydown", handler: this._onKeyDown },
  10998. { name: "keyup", handler: this._onKeyUp },
  10999. { name: "blur", handler: this._onLostFocus }
  11000. ]);
  11001. this._MSGestureHandler = null;
  11002. this._attachedElement = null;
  11003. if (this._reset) {
  11004. this._reset();
  11005. }
  11006. };
  11007. ArcRotateCamera.prototype._checkInputs = function () {
  11008. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  11009. if (this._collisionTriggered) {
  11010. return;
  11011. }
  11012. // Keyboard
  11013. for (var index = 0; index < this._keys.length; index++) {
  11014. var keyCode = this._keys[index];
  11015. if (this.keysLeft.indexOf(keyCode) !== -1) {
  11016. this.inertialAlphaOffset -= 0.01;
  11017. }
  11018. else if (this.keysUp.indexOf(keyCode) !== -1) {
  11019. this.inertialBetaOffset -= 0.01;
  11020. }
  11021. else if (this.keysRight.indexOf(keyCode) !== -1) {
  11022. this.inertialAlphaOffset += 0.01;
  11023. }
  11024. else if (this.keysDown.indexOf(keyCode) !== -1) {
  11025. this.inertialBetaOffset += 0.01;
  11026. }
  11027. }
  11028. // Inertia
  11029. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset != 0) {
  11030. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  11031. this.beta += this.inertialBetaOffset;
  11032. this.radius -= this.inertialRadiusOffset;
  11033. this.inertialAlphaOffset *= this.inertia;
  11034. this.inertialBetaOffset *= this.inertia;
  11035. this.inertialRadiusOffset *= this.inertia;
  11036. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  11037. this.inertialAlphaOffset = 0;
  11038. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  11039. this.inertialBetaOffset = 0;
  11040. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  11041. this.inertialRadiusOffset = 0;
  11042. }
  11043. // Limits
  11044. this._checkLimits();
  11045. _super.prototype._checkInputs.call(this);
  11046. };
  11047. ArcRotateCamera.prototype._checkLimits = function () {
  11048. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  11049. if (this.allowUpsideDown && this.beta > Math.PI) {
  11050. this.beta = this.beta - (2 * Math.PI);
  11051. }
  11052. }
  11053. else {
  11054. if (this.beta < this.lowerBetaLimit) {
  11055. this.beta = this.lowerBetaLimit;
  11056. }
  11057. }
  11058. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  11059. if (this.allowUpsideDown && this.beta < -Math.PI) {
  11060. this.beta = this.beta + (2 * Math.PI);
  11061. }
  11062. }
  11063. else {
  11064. if (this.beta > this.upperBetaLimit) {
  11065. this.beta = this.upperBetaLimit;
  11066. }
  11067. }
  11068. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  11069. this.alpha = this.lowerAlphaLimit;
  11070. }
  11071. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  11072. this.alpha = this.upperAlphaLimit;
  11073. }
  11074. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  11075. this.radius = this.lowerRadiusLimit;
  11076. }
  11077. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  11078. this.radius = this.upperRadiusLimit;
  11079. }
  11080. };
  11081. ArcRotateCamera.prototype.setPosition = function (position) {
  11082. var radiusv3 = position.subtract(this._getTargetPosition());
  11083. this.radius = radiusv3.length();
  11084. // Alpha
  11085. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  11086. if (radiusv3.z < 0) {
  11087. this.alpha = 2 * Math.PI - this.alpha;
  11088. }
  11089. // Beta
  11090. this.beta = Math.acos(radiusv3.y / this.radius);
  11091. this._checkLimits();
  11092. };
  11093. ArcRotateCamera.prototype._getViewMatrix = function () {
  11094. // Compute
  11095. var cosa = Math.cos(this.alpha);
  11096. var sina = Math.sin(this.alpha);
  11097. var cosb = Math.cos(this.beta);
  11098. var sinb = Math.sin(this.beta);
  11099. var target = this._getTargetPosition();
  11100. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  11101. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  11102. this._collider.radius = this.collisionRadius;
  11103. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  11104. this._collisionTriggered = true;
  11105. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  11106. }
  11107. else {
  11108. this.position.copyFrom(this._newPosition);
  11109. var up = this.upVector;
  11110. if (this.allowUpsideDown && this.beta < 0) {
  11111. var up = up.clone();
  11112. up = up.negate();
  11113. }
  11114. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  11115. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  11116. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  11117. }
  11118. return this._viewMatrix;
  11119. };
  11120. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  11121. meshes = meshes || this.getScene().meshes;
  11122. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  11123. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  11124. this.radius = distance * this.zoomOnFactor;
  11125. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  11126. };
  11127. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  11128. var meshesOrMinMaxVector;
  11129. var distance;
  11130. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  11131. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  11132. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  11133. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  11134. }
  11135. else {
  11136. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  11137. distance = meshesOrMinMaxVectorAndDistance.distance;
  11138. }
  11139. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  11140. this.maxZ = distance * 2;
  11141. };
  11142. /**
  11143. * @override
  11144. * Override Camera.createRigCamera
  11145. */
  11146. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  11147. switch (this.cameraRigMode) {
  11148. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11149. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11150. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11151. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11152. case BABYLON.Camera.RIG_MODE_VR:
  11153. var alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  11154. return new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  11155. }
  11156. };
  11157. /**
  11158. * @override
  11159. * Override Camera._updateRigCameras
  11160. */
  11161. ArcRotateCamera.prototype._updateRigCameras = function () {
  11162. switch (this.cameraRigMode) {
  11163. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  11164. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  11165. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  11166. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  11167. case BABYLON.Camera.RIG_MODE_VR:
  11168. var camLeft = this._rigCameras[0];
  11169. var camRight = this._rigCameras[1];
  11170. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  11171. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  11172. camLeft.beta = camRight.beta = this.beta;
  11173. camLeft.radius = camRight.radius = this.radius;
  11174. break;
  11175. }
  11176. _super.prototype._updateRigCameras.call(this);
  11177. };
  11178. return ArcRotateCamera;
  11179. })(BABYLON.Camera);
  11180. BABYLON.ArcRotateCamera = ArcRotateCamera;
  11181. })(BABYLON || (BABYLON = {}));
  11182. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  11183. var BABYLON;
  11184. (function (BABYLON) {
  11185. // We're mainly based on the logic defined into the FreeCamera code
  11186. var DeviceOrientationCamera = (function (_super) {
  11187. __extends(DeviceOrientationCamera, _super);
  11188. function DeviceOrientationCamera(name, position, scene) {
  11189. var _this = this;
  11190. _super.call(this, name, position, scene);
  11191. this._offsetX = null;
  11192. this._offsetY = null;
  11193. this._orientationGamma = 0;
  11194. this._orientationBeta = 0;
  11195. this._initialOrientationGamma = 0;
  11196. this._initialOrientationBeta = 0;
  11197. this.angularSensibility = 10000.0;
  11198. this.moveSensibility = 50.0;
  11199. window.addEventListener("resize", function () {
  11200. _this._initialOrientationGamma = null;
  11201. }, false);
  11202. }
  11203. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  11204. var _this = this;
  11205. if (this._attachedCanvas) {
  11206. return;
  11207. }
  11208. this._attachedCanvas = canvas;
  11209. if (!this._orientationChanged) {
  11210. this._orientationChanged = function (evt) {
  11211. if (!_this._initialOrientationGamma) {
  11212. _this._initialOrientationGamma = evt.gamma;
  11213. _this._initialOrientationBeta = evt.beta;
  11214. }
  11215. _this._orientationGamma = evt.gamma;
  11216. _this._orientationBeta = evt.beta;
  11217. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  11218. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  11219. };
  11220. }
  11221. window.addEventListener("deviceorientation", this._orientationChanged);
  11222. };
  11223. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  11224. if (this._attachedCanvas != canvas) {
  11225. return;
  11226. }
  11227. window.removeEventListener("deviceorientation", this._orientationChanged);
  11228. this._attachedCanvas = null;
  11229. this._orientationGamma = 0;
  11230. this._orientationBeta = 0;
  11231. this._initialOrientationGamma = 0;
  11232. this._initialOrientationBeta = 0;
  11233. };
  11234. DeviceOrientationCamera.prototype._checkInputs = function () {
  11235. if (!this._offsetX) {
  11236. return;
  11237. }
  11238. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  11239. var speed = this._computeLocalCameraSpeed();
  11240. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  11241. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  11242. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  11243. _super.prototype._checkInputs.call(this);
  11244. };
  11245. return DeviceOrientationCamera;
  11246. })(BABYLON.FreeCamera);
  11247. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  11248. })(BABYLON || (BABYLON = {}));
  11249. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  11250. var BABYLON;
  11251. (function (BABYLON) {
  11252. var Gamepads = (function () {
  11253. function Gamepads(ongamedpadconnected) {
  11254. var _this = this;
  11255. this.babylonGamepads = [];
  11256. this.oneGamepadConnected = false;
  11257. this.isMonitoring = false;
  11258. this.gamepadEventSupported = 'GamepadEvent' in window;
  11259. this.gamepadSupportAvailable = (navigator.getGamepads ||
  11260. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  11261. 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=";
  11262. this._callbackGamepadConnected = ongamedpadconnected;
  11263. if (this.gamepadSupportAvailable) {
  11264. // Checking if the gamepad connected event is supported (like in Firefox)
  11265. if (this.gamepadEventSupported) {
  11266. window.addEventListener('gamepadconnected', function (evt) {
  11267. _this._onGamepadConnected(evt);
  11268. }, false);
  11269. window.addEventListener('gamepaddisconnected', function (evt) {
  11270. _this._onGamepadDisconnected(evt);
  11271. }, false);
  11272. }
  11273. else {
  11274. this._startMonitoringGamepads();
  11275. }
  11276. if (!this.oneGamepadConnected) {
  11277. this._insertGamepadDOMInstructions();
  11278. }
  11279. }
  11280. else {
  11281. this._insertGamepadDOMNotSupported();
  11282. }
  11283. }
  11284. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  11285. Gamepads.gamepadDOMInfo = document.createElement("div");
  11286. var buttonAImage = document.createElement("img");
  11287. buttonAImage.src = this.buttonADataURL;
  11288. var spanMessage = document.createElement("span");
  11289. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  11290. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  11291. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11292. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11293. Gamepads.gamepadDOMInfo.style.width = "100%";
  11294. Gamepads.gamepadDOMInfo.style.height = "48px";
  11295. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11296. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11297. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11298. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11299. buttonAImage.style.position = "relative";
  11300. buttonAImage.style.bottom = "8px";
  11301. spanMessage.style.position = "relative";
  11302. spanMessage.style.fontSize = "32px";
  11303. spanMessage.style.bottom = "32px";
  11304. spanMessage.style.color = "green";
  11305. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11306. };
  11307. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  11308. Gamepads.gamepadDOMInfo = document.createElement("div");
  11309. var spanMessage = document.createElement("span");
  11310. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  11311. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  11312. Gamepads.gamepadDOMInfo.style.position = "absolute";
  11313. Gamepads.gamepadDOMInfo.style.width = "100%";
  11314. Gamepads.gamepadDOMInfo.style.height = "40px";
  11315. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  11316. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  11317. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  11318. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  11319. spanMessage.style.position = "relative";
  11320. spanMessage.style.fontSize = "32px";
  11321. spanMessage.style.color = "red";
  11322. document.body.appendChild(Gamepads.gamepadDOMInfo);
  11323. };
  11324. Gamepads.prototype.dispose = function () {
  11325. if (Gamepads.gamepadDOMInfo) {
  11326. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11327. }
  11328. };
  11329. Gamepads.prototype._onGamepadConnected = function (evt) {
  11330. var newGamepad = this._addNewGamepad(evt.gamepad);
  11331. if (this._callbackGamepadConnected)
  11332. this._callbackGamepadConnected(newGamepad);
  11333. this._startMonitoringGamepads();
  11334. };
  11335. Gamepads.prototype._addNewGamepad = function (gamepad) {
  11336. if (!this.oneGamepadConnected) {
  11337. this.oneGamepadConnected = true;
  11338. if (Gamepads.gamepadDOMInfo) {
  11339. document.body.removeChild(Gamepads.gamepadDOMInfo);
  11340. Gamepads.gamepadDOMInfo = null;
  11341. }
  11342. }
  11343. var newGamepad;
  11344. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  11345. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  11346. }
  11347. else {
  11348. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  11349. }
  11350. this.babylonGamepads.push(newGamepad);
  11351. return newGamepad;
  11352. };
  11353. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  11354. // Remove the gamepad from the list of gamepads to monitor.
  11355. for (var i in this.babylonGamepads) {
  11356. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  11357. this.babylonGamepads.splice(i, 1);
  11358. break;
  11359. }
  11360. }
  11361. // If no gamepads are left, stop the polling loop.
  11362. if (this.babylonGamepads.length == 0) {
  11363. this._stopMonitoringGamepads();
  11364. }
  11365. };
  11366. Gamepads.prototype._startMonitoringGamepads = function () {
  11367. if (!this.isMonitoring) {
  11368. this.isMonitoring = true;
  11369. this._checkGamepadsStatus();
  11370. }
  11371. };
  11372. Gamepads.prototype._stopMonitoringGamepads = function () {
  11373. this.isMonitoring = false;
  11374. };
  11375. Gamepads.prototype._checkGamepadsStatus = function () {
  11376. var _this = this;
  11377. // updating gamepad objects
  11378. this._updateGamepadObjects();
  11379. for (var i in this.babylonGamepads) {
  11380. this.babylonGamepads[i].update();
  11381. }
  11382. if (this.isMonitoring) {
  11383. if (window.requestAnimationFrame) {
  11384. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11385. }
  11386. else if (window.mozRequestAnimationFrame) {
  11387. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11388. }
  11389. else if (window.webkitRequestAnimationFrame) {
  11390. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  11391. }
  11392. }
  11393. };
  11394. // This function is called only on Chrome, which does not yet support
  11395. // connection/disconnection events, but requires you to monitor
  11396. // an array for changes.
  11397. Gamepads.prototype._updateGamepadObjects = function () {
  11398. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  11399. for (var i = 0; i < gamepads.length; i++) {
  11400. if (gamepads[i]) {
  11401. if (!(gamepads[i].index in this.babylonGamepads)) {
  11402. var newGamepad = this._addNewGamepad(gamepads[i]);
  11403. if (this._callbackGamepadConnected) {
  11404. this._callbackGamepadConnected(newGamepad);
  11405. }
  11406. }
  11407. else {
  11408. this.babylonGamepads[i].browserGamepad = gamepads[i];
  11409. }
  11410. }
  11411. }
  11412. };
  11413. return Gamepads;
  11414. })();
  11415. BABYLON.Gamepads = Gamepads;
  11416. var StickValues = (function () {
  11417. function StickValues(x, y) {
  11418. this.x = x;
  11419. this.y = y;
  11420. }
  11421. return StickValues;
  11422. })();
  11423. BABYLON.StickValues = StickValues;
  11424. var Gamepad = (function () {
  11425. function Gamepad(id, index, browserGamepad) {
  11426. this.id = id;
  11427. this.index = index;
  11428. this.browserGamepad = browserGamepad;
  11429. if (this.browserGamepad.axes.length >= 2) {
  11430. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11431. }
  11432. if (this.browserGamepad.axes.length >= 4) {
  11433. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11434. }
  11435. }
  11436. Gamepad.prototype.onleftstickchanged = function (callback) {
  11437. this._onleftstickchanged = callback;
  11438. };
  11439. Gamepad.prototype.onrightstickchanged = function (callback) {
  11440. this._onrightstickchanged = callback;
  11441. };
  11442. Object.defineProperty(Gamepad.prototype, "leftStick", {
  11443. get: function () {
  11444. return this._leftStick;
  11445. },
  11446. set: function (newValues) {
  11447. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  11448. this._onleftstickchanged(newValues);
  11449. }
  11450. this._leftStick = newValues;
  11451. },
  11452. enumerable: true,
  11453. configurable: true
  11454. });
  11455. Object.defineProperty(Gamepad.prototype, "rightStick", {
  11456. get: function () {
  11457. return this._rightStick;
  11458. },
  11459. set: function (newValues) {
  11460. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  11461. this._onrightstickchanged(newValues);
  11462. }
  11463. this._rightStick = newValues;
  11464. },
  11465. enumerable: true,
  11466. configurable: true
  11467. });
  11468. Gamepad.prototype.update = function () {
  11469. if (this._leftStick) {
  11470. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  11471. }
  11472. if (this._rightStick) {
  11473. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  11474. }
  11475. };
  11476. return Gamepad;
  11477. })();
  11478. BABYLON.Gamepad = Gamepad;
  11479. var GenericPad = (function (_super) {
  11480. __extends(GenericPad, _super);
  11481. function GenericPad(id, index, gamepad) {
  11482. _super.call(this, id, index, gamepad);
  11483. this.id = id;
  11484. this.index = index;
  11485. this.gamepad = gamepad;
  11486. this._buttons = new Array(gamepad.buttons.length);
  11487. }
  11488. GenericPad.prototype.onbuttondown = function (callback) {
  11489. this._onbuttondown = callback;
  11490. };
  11491. GenericPad.prototype.onbuttonup = function (callback) {
  11492. this._onbuttonup = callback;
  11493. };
  11494. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  11495. if (newValue !== currentValue) {
  11496. if (this._onbuttondown && newValue === 1) {
  11497. this._onbuttondown(buttonIndex);
  11498. }
  11499. if (this._onbuttonup && newValue === 0) {
  11500. this._onbuttonup(buttonIndex);
  11501. }
  11502. }
  11503. return newValue;
  11504. };
  11505. GenericPad.prototype.update = function () {
  11506. _super.prototype.update.call(this);
  11507. for (var index = 0; index < this._buttons.length; index++) {
  11508. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  11509. }
  11510. };
  11511. return GenericPad;
  11512. })(Gamepad);
  11513. BABYLON.GenericPad = GenericPad;
  11514. (function (Xbox360Button) {
  11515. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  11516. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  11517. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  11518. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  11519. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  11520. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  11521. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  11522. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  11523. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  11524. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  11525. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  11526. var Xbox360Button = BABYLON.Xbox360Button;
  11527. (function (Xbox360Dpad) {
  11528. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  11529. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  11530. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  11531. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  11532. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  11533. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  11534. var Xbox360Pad = (function (_super) {
  11535. __extends(Xbox360Pad, _super);
  11536. function Xbox360Pad() {
  11537. _super.apply(this, arguments);
  11538. this._leftTrigger = 0;
  11539. this._rightTrigger = 0;
  11540. this._buttonA = 0;
  11541. this._buttonB = 0;
  11542. this._buttonX = 0;
  11543. this._buttonY = 0;
  11544. this._buttonBack = 0;
  11545. this._buttonStart = 0;
  11546. this._buttonLB = 0;
  11547. this._buttonRB = 0;
  11548. this._buttonLeftStick = 0;
  11549. this._buttonRightStick = 0;
  11550. this._dPadUp = 0;
  11551. this._dPadDown = 0;
  11552. this._dPadLeft = 0;
  11553. this._dPadRight = 0;
  11554. }
  11555. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  11556. this._onlefttriggerchanged = callback;
  11557. };
  11558. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  11559. this._onrighttriggerchanged = callback;
  11560. };
  11561. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  11562. get: function () {
  11563. return this._leftTrigger;
  11564. },
  11565. set: function (newValue) {
  11566. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  11567. this._onlefttriggerchanged(newValue);
  11568. }
  11569. this._leftTrigger = newValue;
  11570. },
  11571. enumerable: true,
  11572. configurable: true
  11573. });
  11574. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  11575. get: function () {
  11576. return this._rightTrigger;
  11577. },
  11578. set: function (newValue) {
  11579. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  11580. this._onrighttriggerchanged(newValue);
  11581. }
  11582. this._rightTrigger = newValue;
  11583. },
  11584. enumerable: true,
  11585. configurable: true
  11586. });
  11587. Xbox360Pad.prototype.onbuttondown = function (callback) {
  11588. this._onbuttondown = callback;
  11589. };
  11590. Xbox360Pad.prototype.onbuttonup = function (callback) {
  11591. this._onbuttonup = callback;
  11592. };
  11593. Xbox360Pad.prototype.ondpaddown = function (callback) {
  11594. this._ondpaddown = callback;
  11595. };
  11596. Xbox360Pad.prototype.ondpadup = function (callback) {
  11597. this._ondpadup = callback;
  11598. };
  11599. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  11600. if (newValue !== currentValue) {
  11601. if (this._onbuttondown && newValue === 1) {
  11602. this._onbuttondown(buttonType);
  11603. }
  11604. if (this._onbuttonup && newValue === 0) {
  11605. this._onbuttonup(buttonType);
  11606. }
  11607. }
  11608. return newValue;
  11609. };
  11610. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  11611. if (newValue !== currentValue) {
  11612. if (this._ondpaddown && newValue === 1) {
  11613. this._ondpaddown(buttonType);
  11614. }
  11615. if (this._ondpadup && newValue === 0) {
  11616. this._ondpadup(buttonType);
  11617. }
  11618. }
  11619. return newValue;
  11620. };
  11621. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  11622. get: function () {
  11623. return this._buttonA;
  11624. },
  11625. set: function (value) {
  11626. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  11627. },
  11628. enumerable: true,
  11629. configurable: true
  11630. });
  11631. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  11632. get: function () {
  11633. return this._buttonB;
  11634. },
  11635. set: function (value) {
  11636. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  11637. },
  11638. enumerable: true,
  11639. configurable: true
  11640. });
  11641. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  11642. get: function () {
  11643. return this._buttonX;
  11644. },
  11645. set: function (value) {
  11646. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  11647. },
  11648. enumerable: true,
  11649. configurable: true
  11650. });
  11651. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  11652. get: function () {
  11653. return this._buttonY;
  11654. },
  11655. set: function (value) {
  11656. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  11657. },
  11658. enumerable: true,
  11659. configurable: true
  11660. });
  11661. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  11662. get: function () {
  11663. return this._buttonStart;
  11664. },
  11665. set: function (value) {
  11666. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  11667. },
  11668. enumerable: true,
  11669. configurable: true
  11670. });
  11671. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  11672. get: function () {
  11673. return this._buttonBack;
  11674. },
  11675. set: function (value) {
  11676. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  11677. },
  11678. enumerable: true,
  11679. configurable: true
  11680. });
  11681. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  11682. get: function () {
  11683. return this._buttonLB;
  11684. },
  11685. set: function (value) {
  11686. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  11687. },
  11688. enumerable: true,
  11689. configurable: true
  11690. });
  11691. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  11692. get: function () {
  11693. return this._buttonRB;
  11694. },
  11695. set: function (value) {
  11696. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  11697. },
  11698. enumerable: true,
  11699. configurable: true
  11700. });
  11701. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  11702. get: function () {
  11703. return this._buttonLeftStick;
  11704. },
  11705. set: function (value) {
  11706. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  11707. },
  11708. enumerable: true,
  11709. configurable: true
  11710. });
  11711. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  11712. get: function () {
  11713. return this._buttonRightStick;
  11714. },
  11715. set: function (value) {
  11716. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  11717. },
  11718. enumerable: true,
  11719. configurable: true
  11720. });
  11721. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  11722. get: function () {
  11723. return this._dPadUp;
  11724. },
  11725. set: function (value) {
  11726. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  11727. },
  11728. enumerable: true,
  11729. configurable: true
  11730. });
  11731. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  11732. get: function () {
  11733. return this._dPadDown;
  11734. },
  11735. set: function (value) {
  11736. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  11737. },
  11738. enumerable: true,
  11739. configurable: true
  11740. });
  11741. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  11742. get: function () {
  11743. return this._dPadLeft;
  11744. },
  11745. set: function (value) {
  11746. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  11747. },
  11748. enumerable: true,
  11749. configurable: true
  11750. });
  11751. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  11752. get: function () {
  11753. return this._dPadRight;
  11754. },
  11755. set: function (value) {
  11756. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  11757. },
  11758. enumerable: true,
  11759. configurable: true
  11760. });
  11761. Xbox360Pad.prototype.update = function () {
  11762. _super.prototype.update.call(this);
  11763. this.buttonA = this.browserGamepad.buttons[0].value;
  11764. this.buttonB = this.browserGamepad.buttons[1].value;
  11765. this.buttonX = this.browserGamepad.buttons[2].value;
  11766. this.buttonY = this.browserGamepad.buttons[3].value;
  11767. this.buttonLB = this.browserGamepad.buttons[4].value;
  11768. this.buttonRB = this.browserGamepad.buttons[5].value;
  11769. this.leftTrigger = this.browserGamepad.buttons[6].value;
  11770. this.rightTrigger = this.browserGamepad.buttons[7].value;
  11771. this.buttonBack = this.browserGamepad.buttons[8].value;
  11772. this.buttonStart = this.browserGamepad.buttons[9].value;
  11773. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  11774. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  11775. this.dPadUp = this.browserGamepad.buttons[12].value;
  11776. this.dPadDown = this.browserGamepad.buttons[13].value;
  11777. this.dPadLeft = this.browserGamepad.buttons[14].value;
  11778. this.dPadRight = this.browserGamepad.buttons[15].value;
  11779. };
  11780. return Xbox360Pad;
  11781. })(Gamepad);
  11782. BABYLON.Xbox360Pad = Xbox360Pad;
  11783. })(BABYLON || (BABYLON = {}));
  11784. //# sourceMappingURL=babylon.gamepads.js.map
  11785. var BABYLON;
  11786. (function (BABYLON) {
  11787. // We're mainly based on the logic defined into the FreeCamera code
  11788. var GamepadCamera = (function (_super) {
  11789. __extends(GamepadCamera, _super);
  11790. function GamepadCamera(name, position, scene) {
  11791. var _this = this;
  11792. _super.call(this, name, position, scene);
  11793. this.angularSensibility = 200;
  11794. this.moveSensibility = 75;
  11795. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  11796. }
  11797. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  11798. // Only the first gamepad can control the camera
  11799. if (gamepad.index === 0) {
  11800. this._gamepad = gamepad;
  11801. }
  11802. };
  11803. GamepadCamera.prototype._checkInputs = function () {
  11804. if (this._gamepad) {
  11805. var LSValues = this._gamepad.leftStick;
  11806. var normalizedLX = LSValues.x / this.moveSensibility;
  11807. var normalizedLY = LSValues.y / this.moveSensibility;
  11808. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  11809. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  11810. var RSValues = this._gamepad.rightStick;
  11811. var normalizedRX = RSValues.x / this.angularSensibility;
  11812. var normalizedRY = RSValues.y / this.angularSensibility;
  11813. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  11814. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  11815. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  11816. var speed = this._computeLocalCameraSpeed() * 50.0;
  11817. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  11818. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  11819. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  11820. }
  11821. _super.prototype._checkInputs.call(this);
  11822. };
  11823. GamepadCamera.prototype.dispose = function () {
  11824. this._gamepads.dispose();
  11825. _super.prototype.dispose.call(this);
  11826. };
  11827. return GamepadCamera;
  11828. })(BABYLON.FreeCamera);
  11829. BABYLON.GamepadCamera = GamepadCamera;
  11830. })(BABYLON || (BABYLON = {}));
  11831. //# sourceMappingURL=babylon.gamepadCamera.js.map
  11832. var BABYLON;
  11833. (function (BABYLON) {
  11834. var RenderingManager = (function () {
  11835. function RenderingManager(scene) {
  11836. this._renderingGroups = new Array();
  11837. this._scene = scene;
  11838. }
  11839. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11840. if (this._scene._activeParticleSystems.length === 0) {
  11841. return;
  11842. }
  11843. // Particles
  11844. var beforeParticlesDate = BABYLON.Tools.Now;
  11845. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11846. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11847. if (particleSystem.renderingGroupId !== index) {
  11848. continue;
  11849. }
  11850. this._clearDepthBuffer();
  11851. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11852. this._scene._activeParticles += particleSystem.render();
  11853. }
  11854. }
  11855. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11856. };
  11857. RenderingManager.prototype._renderSprites = function (index) {
  11858. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11859. return;
  11860. }
  11861. // Sprites
  11862. var beforeSpritessDate = BABYLON.Tools.Now;
  11863. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11864. var spriteManager = this._scene.spriteManagers[id];
  11865. if (spriteManager.renderingGroupId === index) {
  11866. this._clearDepthBuffer();
  11867. spriteManager.render();
  11868. }
  11869. }
  11870. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11871. };
  11872. RenderingManager.prototype._clearDepthBuffer = function () {
  11873. if (this._depthBufferAlreadyCleaned) {
  11874. return;
  11875. }
  11876. this._scene.getEngine().clear(0, false, true);
  11877. this._depthBufferAlreadyCleaned = true;
  11878. };
  11879. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11880. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11881. this._depthBufferAlreadyCleaned = false;
  11882. var renderingGroup = this._renderingGroups[index];
  11883. var needToStepBack = false;
  11884. if (renderingGroup) {
  11885. this._clearDepthBuffer();
  11886. if (!renderingGroup.render(customRenderFunction)) {
  11887. this._renderingGroups.splice(index, 1);
  11888. needToStepBack = true;
  11889. }
  11890. }
  11891. if (renderSprites) {
  11892. this._renderSprites(index);
  11893. }
  11894. if (renderParticles) {
  11895. this._renderParticles(index, activeMeshes);
  11896. }
  11897. if (needToStepBack) {
  11898. index--;
  11899. }
  11900. }
  11901. };
  11902. RenderingManager.prototype.reset = function () {
  11903. for (var index in this._renderingGroups) {
  11904. var renderingGroup = this._renderingGroups[index];
  11905. renderingGroup.prepare();
  11906. }
  11907. };
  11908. RenderingManager.prototype.dispatch = function (subMesh) {
  11909. var mesh = subMesh.getMesh();
  11910. var renderingGroupId = mesh.renderingGroupId || 0;
  11911. if (!this._renderingGroups[renderingGroupId]) {
  11912. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11913. }
  11914. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11915. };
  11916. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11917. return RenderingManager;
  11918. })();
  11919. BABYLON.RenderingManager = RenderingManager;
  11920. })(BABYLON || (BABYLON = {}));
  11921. //# sourceMappingURL=babylon.renderingManager.js.map
  11922. var BABYLON;
  11923. (function (BABYLON) {
  11924. var RenderingGroup = (function () {
  11925. function RenderingGroup(index, scene) {
  11926. this.index = index;
  11927. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11928. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11929. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11930. this._scene = scene;
  11931. }
  11932. RenderingGroup.prototype.render = function (customRenderFunction) {
  11933. if (customRenderFunction) {
  11934. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11935. return true;
  11936. }
  11937. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11938. return false;
  11939. }
  11940. var engine = this._scene.getEngine();
  11941. // Opaque
  11942. var subIndex;
  11943. var submesh;
  11944. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11945. submesh = this._opaqueSubMeshes.data[subIndex];
  11946. submesh.render();
  11947. }
  11948. // Alpha test
  11949. engine.setAlphaTesting(true);
  11950. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11951. submesh = this._alphaTestSubMeshes.data[subIndex];
  11952. submesh.render();
  11953. }
  11954. engine.setAlphaTesting(false);
  11955. // Transparent
  11956. if (this._transparentSubMeshes.length) {
  11957. // Sorting
  11958. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11959. submesh = this._transparentSubMeshes.data[subIndex];
  11960. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11961. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  11962. }
  11963. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11964. sortedArray.sort(function (a, b) {
  11965. // Alpha index first
  11966. if (a._alphaIndex > b._alphaIndex) {
  11967. return 1;
  11968. }
  11969. if (a._alphaIndex < b._alphaIndex) {
  11970. return -1;
  11971. }
  11972. // Then distance to camera
  11973. if (a._distanceToCamera < b._distanceToCamera) {
  11974. return 1;
  11975. }
  11976. if (a._distanceToCamera > b._distanceToCamera) {
  11977. return -1;
  11978. }
  11979. return 0;
  11980. });
  11981. // Rendering
  11982. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11983. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11984. submesh = sortedArray[subIndex];
  11985. submesh.render();
  11986. }
  11987. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11988. }
  11989. return true;
  11990. };
  11991. RenderingGroup.prototype.prepare = function () {
  11992. this._opaqueSubMeshes.reset();
  11993. this._transparentSubMeshes.reset();
  11994. this._alphaTestSubMeshes.reset();
  11995. };
  11996. RenderingGroup.prototype.dispatch = function (subMesh) {
  11997. var material = subMesh.getMaterial();
  11998. var mesh = subMesh.getMesh();
  11999. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12000. this._transparentSubMeshes.push(subMesh);
  12001. }
  12002. else if (material.needAlphaTesting()) {
  12003. this._alphaTestSubMeshes.push(subMesh);
  12004. }
  12005. else {
  12006. this._opaqueSubMeshes.push(subMesh); // Opaque
  12007. }
  12008. };
  12009. return RenderingGroup;
  12010. })();
  12011. BABYLON.RenderingGroup = RenderingGroup;
  12012. })(BABYLON || (BABYLON = {}));
  12013. //# sourceMappingURL=babylon.renderingGroup.js.map
  12014. var BABYLON;
  12015. (function (BABYLON) {
  12016. /**
  12017. * Represents a scene to be rendered by the engine.
  12018. * @see http://doc.babylonjs.com/page.php?p=21911
  12019. */
  12020. var Scene = (function () {
  12021. /**
  12022. * @constructor
  12023. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  12024. */
  12025. function Scene(engine) {
  12026. // Members
  12027. this.autoClear = true;
  12028. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12029. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12030. this.forceWireframe = false;
  12031. this.forcePointsCloud = false;
  12032. this.forceShowBoundingBoxes = false;
  12033. this.animationsEnabled = true;
  12034. 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
  12035. // Fog
  12036. /**
  12037. * is fog enabled on this scene.
  12038. * @type {boolean}
  12039. */
  12040. this.fogEnabled = true;
  12041. this.fogMode = Scene.FOGMODE_NONE;
  12042. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  12043. this.fogDensity = 0.1;
  12044. this.fogStart = 0;
  12045. this.fogEnd = 1000.0;
  12046. // Lights
  12047. /**
  12048. * is shadow enabled on this scene.
  12049. * @type {boolean}
  12050. */
  12051. this.shadowsEnabled = true;
  12052. /**
  12053. * is light enabled on this scene.
  12054. * @type {boolean}
  12055. */
  12056. this.lightsEnabled = true;
  12057. /**
  12058. * All of the lights added to this scene.
  12059. * @see BABYLON.Light
  12060. * @type {BABYLON.Light[]}
  12061. */
  12062. this.lights = new Array();
  12063. // Cameras
  12064. /**
  12065. * All of the cameras added to this scene.
  12066. * @see BABYLON.Camera
  12067. * @type {BABYLON.Camera[]}
  12068. */
  12069. this.cameras = new Array();
  12070. this.activeCameras = new Array();
  12071. // Meshes
  12072. /**
  12073. * All of the (abstract) meshes added to this scene.
  12074. * @see BABYLON.AbstractMesh
  12075. * @type {BABYLON.AbstractMesh[]}
  12076. */
  12077. this.meshes = new Array();
  12078. // Geometries
  12079. this._geometries = new Array();
  12080. this.materials = new Array();
  12081. this.multiMaterials = new Array();
  12082. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  12083. // Textures
  12084. this.texturesEnabled = true;
  12085. this.textures = new Array();
  12086. // Particles
  12087. this.particlesEnabled = true;
  12088. this.particleSystems = new Array();
  12089. // Sprites
  12090. this.spritesEnabled = true;
  12091. this.spriteManagers = new Array();
  12092. // Layers
  12093. this.layers = new Array();
  12094. // Skeletons
  12095. this.skeletonsEnabled = true;
  12096. this.skeletons = new Array();
  12097. // Lens flares
  12098. this.lensFlaresEnabled = true;
  12099. this.lensFlareSystems = new Array();
  12100. // Collisions
  12101. this.collisionsEnabled = true;
  12102. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  12103. // Postprocesses
  12104. this.postProcessesEnabled = true;
  12105. // Customs render targets
  12106. this.renderTargetsEnabled = true;
  12107. this.dumpNextRenderTargets = false;
  12108. this.customRenderTargets = new Array();
  12109. // Imported meshes
  12110. this.importedMeshesFiles = new Array();
  12111. this._actionManagers = new Array();
  12112. this._meshesForIntersections = new BABYLON.SmartArray(256);
  12113. // Procedural textures
  12114. this.proceduralTexturesEnabled = true;
  12115. this._proceduralTextures = new Array();
  12116. this.soundTracks = new Array();
  12117. this._audioEnabled = true;
  12118. this._headphone = false;
  12119. this._totalVertices = 0;
  12120. this._activeIndices = 0;
  12121. this._activeParticles = 0;
  12122. this._lastFrameDuration = 0;
  12123. this._evaluateActiveMeshesDuration = 0;
  12124. this._renderTargetsDuration = 0;
  12125. this._particlesDuration = 0;
  12126. this._renderDuration = 0;
  12127. this._spritesDuration = 0;
  12128. this._animationRatio = 0;
  12129. this._renderId = 0;
  12130. this._executeWhenReadyTimeoutId = -1;
  12131. this._toBeDisposed = new BABYLON.SmartArray(256);
  12132. this._onReadyCallbacks = new Array();
  12133. this._pendingData = []; //ANY
  12134. this._onBeforeRenderCallbacks = new Array();
  12135. this._onAfterRenderCallbacks = new Array();
  12136. this._activeMeshes = new BABYLON.SmartArray(256);
  12137. this._processedMaterials = new BABYLON.SmartArray(256);
  12138. this._renderTargets = new BABYLON.SmartArray(256);
  12139. this._activeParticleSystems = new BABYLON.SmartArray(256);
  12140. this._activeSkeletons = new BABYLON.SmartArray(32);
  12141. this._activeBones = 0;
  12142. this._activeAnimatables = new Array();
  12143. this._transformMatrix = BABYLON.Matrix.Zero();
  12144. this._uniqueIdCounter = 0;
  12145. this._engine = engine;
  12146. engine.scenes.push(this);
  12147. this._renderingManager = new BABYLON.RenderingManager(this);
  12148. this.postProcessManager = new BABYLON.PostProcessManager(this);
  12149. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  12150. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  12151. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  12152. this.attachControl();
  12153. this._debugLayer = new BABYLON.DebugLayer(this);
  12154. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  12155. //simplification queue
  12156. this.simplificationQueue = new BABYLON.SimplificationQueue();
  12157. //collision coordinator initialization. For now legacy per default.
  12158. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  12159. }
  12160. Object.defineProperty(Scene, "FOGMODE_NONE", {
  12161. get: function () {
  12162. return Scene._FOGMODE_NONE;
  12163. },
  12164. enumerable: true,
  12165. configurable: true
  12166. });
  12167. Object.defineProperty(Scene, "FOGMODE_EXP", {
  12168. get: function () {
  12169. return Scene._FOGMODE_EXP;
  12170. },
  12171. enumerable: true,
  12172. configurable: true
  12173. });
  12174. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  12175. get: function () {
  12176. return Scene._FOGMODE_EXP2;
  12177. },
  12178. enumerable: true,
  12179. configurable: true
  12180. });
  12181. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  12182. get: function () {
  12183. return Scene._FOGMODE_LINEAR;
  12184. },
  12185. enumerable: true,
  12186. configurable: true
  12187. });
  12188. Object.defineProperty(Scene.prototype, "debugLayer", {
  12189. // Properties
  12190. get: function () {
  12191. return this._debugLayer;
  12192. },
  12193. enumerable: true,
  12194. configurable: true
  12195. });
  12196. Object.defineProperty(Scene.prototype, "workerCollisions", {
  12197. get: function () {
  12198. return this._workerCollisions;
  12199. },
  12200. set: function (enabled) {
  12201. enabled = (enabled && !!Worker);
  12202. this._workerCollisions = enabled;
  12203. if (this.collisionCoordinator) {
  12204. this.collisionCoordinator.destroy();
  12205. }
  12206. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  12207. this.collisionCoordinator.init(this);
  12208. },
  12209. enumerable: true,
  12210. configurable: true
  12211. });
  12212. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  12213. /**
  12214. * The mesh that is currently under the pointer.
  12215. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  12216. */
  12217. get: function () {
  12218. return this._meshUnderPointer;
  12219. },
  12220. enumerable: true,
  12221. configurable: true
  12222. });
  12223. Object.defineProperty(Scene.prototype, "pointerX", {
  12224. /**
  12225. * Current on-screen X position of the pointer
  12226. * @return {number} X position of the pointer
  12227. */
  12228. get: function () {
  12229. return this._pointerX;
  12230. },
  12231. enumerable: true,
  12232. configurable: true
  12233. });
  12234. Object.defineProperty(Scene.prototype, "pointerY", {
  12235. /**
  12236. * Current on-screen Y position of the pointer
  12237. * @return {number} Y position of the pointer
  12238. */
  12239. get: function () {
  12240. return this._pointerY;
  12241. },
  12242. enumerable: true,
  12243. configurable: true
  12244. });
  12245. Scene.prototype.getCachedMaterial = function () {
  12246. return this._cachedMaterial;
  12247. };
  12248. Scene.prototype.getBoundingBoxRenderer = function () {
  12249. return this._boundingBoxRenderer;
  12250. };
  12251. Scene.prototype.getOutlineRenderer = function () {
  12252. return this._outlineRenderer;
  12253. };
  12254. Scene.prototype.getEngine = function () {
  12255. return this._engine;
  12256. };
  12257. Scene.prototype.getTotalVertices = function () {
  12258. return this._totalVertices;
  12259. };
  12260. Scene.prototype.getActiveIndices = function () {
  12261. return this._activeIndices;
  12262. };
  12263. Scene.prototype.getActiveParticles = function () {
  12264. return this._activeParticles;
  12265. };
  12266. Scene.prototype.getActiveBones = function () {
  12267. return this._activeBones;
  12268. };
  12269. // Stats
  12270. Scene.prototype.getLastFrameDuration = function () {
  12271. return this._lastFrameDuration;
  12272. };
  12273. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  12274. return this._evaluateActiveMeshesDuration;
  12275. };
  12276. Scene.prototype.getActiveMeshes = function () {
  12277. return this._activeMeshes;
  12278. };
  12279. Scene.prototype.getRenderTargetsDuration = function () {
  12280. return this._renderTargetsDuration;
  12281. };
  12282. Scene.prototype.getRenderDuration = function () {
  12283. return this._renderDuration;
  12284. };
  12285. Scene.prototype.getParticlesDuration = function () {
  12286. return this._particlesDuration;
  12287. };
  12288. Scene.prototype.getSpritesDuration = function () {
  12289. return this._spritesDuration;
  12290. };
  12291. Scene.prototype.getAnimationRatio = function () {
  12292. return this._animationRatio;
  12293. };
  12294. Scene.prototype.getRenderId = function () {
  12295. return this._renderId;
  12296. };
  12297. Scene.prototype.incrementRenderId = function () {
  12298. this._renderId++;
  12299. };
  12300. Scene.prototype._updatePointerPosition = function (evt) {
  12301. var canvasRect = this._engine.getRenderingCanvasClientRect();
  12302. this._pointerX = evt.clientX - canvasRect.left;
  12303. this._pointerY = evt.clientY - canvasRect.top;
  12304. if (this.cameraToUseForPointers) {
  12305. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  12306. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  12307. }
  12308. };
  12309. // Pointers handling
  12310. Scene.prototype.attachControl = function () {
  12311. var _this = this;
  12312. this._onPointerMove = function (evt) {
  12313. var canvas = _this._engine.getRenderingCanvas();
  12314. _this._updatePointerPosition(evt);
  12315. 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);
  12316. if (pickResult.hit) {
  12317. _this._meshUnderPointer = pickResult.pickedMesh;
  12318. _this.setPointerOverMesh(pickResult.pickedMesh);
  12319. canvas.style.cursor = "pointer";
  12320. }
  12321. else {
  12322. _this.setPointerOverMesh(null);
  12323. canvas.style.cursor = "";
  12324. _this._meshUnderPointer = null;
  12325. }
  12326. };
  12327. this._onPointerDown = function (evt) {
  12328. var predicate = null;
  12329. if (!_this.onPointerDown) {
  12330. predicate = function (mesh) {
  12331. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  12332. };
  12333. }
  12334. _this._updatePointerPosition(evt);
  12335. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12336. if (pickResult.hit) {
  12337. if (pickResult.pickedMesh.actionManager) {
  12338. switch (evt.button) {
  12339. case 0:
  12340. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12341. break;
  12342. case 1:
  12343. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12344. break;
  12345. case 2:
  12346. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12347. break;
  12348. }
  12349. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12350. }
  12351. }
  12352. if (_this.onPointerDown) {
  12353. _this.onPointerDown(evt, pickResult);
  12354. }
  12355. };
  12356. this._onPointerUp = function (evt) {
  12357. var predicate = null;
  12358. if (!_this.onPointerUp) {
  12359. predicate = function (mesh) {
  12360. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickUpTrigger);
  12361. };
  12362. }
  12363. _this._updatePointerPosition(evt);
  12364. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  12365. if (pickResult.hit) {
  12366. if (pickResult.pickedMesh.actionManager) {
  12367. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  12368. }
  12369. }
  12370. if (_this.onPointerUp) {
  12371. _this.onPointerUp(evt, pickResult);
  12372. }
  12373. };
  12374. this._onKeyDown = function (evt) {
  12375. if (_this.actionManager) {
  12376. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12377. }
  12378. };
  12379. this._onKeyUp = function (evt) {
  12380. if (_this.actionManager) {
  12381. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  12382. }
  12383. };
  12384. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12385. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  12386. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  12387. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "up", this._onPointerUp, false);
  12388. BABYLON.Tools.RegisterTopRootEvents([
  12389. { name: "keydown", handler: this._onKeyDown },
  12390. { name: "keyup", handler: this._onKeyUp }
  12391. ]);
  12392. };
  12393. Scene.prototype.detachControl = function () {
  12394. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  12395. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  12396. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  12397. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "up", this._onPointerUp);
  12398. BABYLON.Tools.UnregisterTopRootEvents([
  12399. { name: "keydown", handler: this._onKeyDown },
  12400. { name: "keyup", handler: this._onKeyUp }
  12401. ]);
  12402. };
  12403. // Ready
  12404. Scene.prototype.isReady = function () {
  12405. if (this._pendingData.length > 0) {
  12406. return false;
  12407. }
  12408. for (var index = 0; index < this._geometries.length; index++) {
  12409. var geometry = this._geometries[index];
  12410. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  12411. return false;
  12412. }
  12413. }
  12414. for (index = 0; index < this.meshes.length; index++) {
  12415. var mesh = this.meshes[index];
  12416. if (!mesh.isReady()) {
  12417. return false;
  12418. }
  12419. var mat = mesh.material;
  12420. if (mat) {
  12421. if (!mat.isReady(mesh)) {
  12422. return false;
  12423. }
  12424. }
  12425. }
  12426. return true;
  12427. };
  12428. Scene.prototype.resetCachedMaterial = function () {
  12429. this._cachedMaterial = null;
  12430. };
  12431. Scene.prototype.registerBeforeRender = function (func) {
  12432. this._onBeforeRenderCallbacks.push(func);
  12433. };
  12434. Scene.prototype.unregisterBeforeRender = function (func) {
  12435. var index = this._onBeforeRenderCallbacks.indexOf(func);
  12436. if (index > -1) {
  12437. this._onBeforeRenderCallbacks.splice(index, 1);
  12438. }
  12439. };
  12440. Scene.prototype.registerAfterRender = function (func) {
  12441. this._onAfterRenderCallbacks.push(func);
  12442. };
  12443. Scene.prototype.unregisterAfterRender = function (func) {
  12444. var index = this._onAfterRenderCallbacks.indexOf(func);
  12445. if (index > -1) {
  12446. this._onAfterRenderCallbacks.splice(index, 1);
  12447. }
  12448. };
  12449. Scene.prototype._addPendingData = function (data) {
  12450. this._pendingData.push(data);
  12451. };
  12452. Scene.prototype._removePendingData = function (data) {
  12453. var index = this._pendingData.indexOf(data);
  12454. if (index !== -1) {
  12455. this._pendingData.splice(index, 1);
  12456. }
  12457. };
  12458. Scene.prototype.getWaitingItemsCount = function () {
  12459. return this._pendingData.length;
  12460. };
  12461. /**
  12462. * Registers a function to be executed when the scene is ready.
  12463. * @param {Function} func - the function to be executed.
  12464. */
  12465. Scene.prototype.executeWhenReady = function (func) {
  12466. var _this = this;
  12467. this._onReadyCallbacks.push(func);
  12468. if (this._executeWhenReadyTimeoutId !== -1) {
  12469. return;
  12470. }
  12471. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12472. _this._checkIsReady();
  12473. }, 150);
  12474. };
  12475. Scene.prototype._checkIsReady = function () {
  12476. var _this = this;
  12477. if (this.isReady()) {
  12478. this._onReadyCallbacks.forEach(function (func) {
  12479. func();
  12480. });
  12481. this._onReadyCallbacks = [];
  12482. this._executeWhenReadyTimeoutId = -1;
  12483. return;
  12484. }
  12485. this._executeWhenReadyTimeoutId = setTimeout(function () {
  12486. _this._checkIsReady();
  12487. }, 150);
  12488. };
  12489. // Animations
  12490. /**
  12491. * Will start the animation sequence of a given target
  12492. * @param target - the target
  12493. * @param {number} from - from which frame should animation start
  12494. * @param {number} to - till which frame should animation run.
  12495. * @param {boolean} [loop] - should the animation loop
  12496. * @param {number} [speedRatio] - the speed in which to run the animation
  12497. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  12498. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  12499. * @return {BABYLON.Animatable} the animatable object created for this animation
  12500. * @see BABYLON.Animatable
  12501. * @see http://doc.babylonjs.com/page.php?p=22081
  12502. */
  12503. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  12504. if (speedRatio === undefined) {
  12505. speedRatio = 1.0;
  12506. }
  12507. this.stopAnimation(target);
  12508. if (!animatable) {
  12509. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  12510. }
  12511. // Local animations
  12512. if (target.animations) {
  12513. animatable.appendAnimations(target, target.animations);
  12514. }
  12515. // Children animations
  12516. if (target.getAnimatables) {
  12517. var animatables = target.getAnimatables();
  12518. for (var index = 0; index < animatables.length; index++) {
  12519. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  12520. }
  12521. }
  12522. return animatable;
  12523. };
  12524. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  12525. if (speedRatio === undefined) {
  12526. speedRatio = 1.0;
  12527. }
  12528. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  12529. return animatable;
  12530. };
  12531. Scene.prototype.getAnimatableByTarget = function (target) {
  12532. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12533. if (this._activeAnimatables[index].target === target) {
  12534. return this._activeAnimatables[index];
  12535. }
  12536. }
  12537. return null;
  12538. };
  12539. /**
  12540. * Will stop the animation of the given target
  12541. * @param target - the target
  12542. * @see beginAnimation
  12543. */
  12544. Scene.prototype.stopAnimation = function (target) {
  12545. var animatable = this.getAnimatableByTarget(target);
  12546. if (animatable) {
  12547. animatable.stop();
  12548. }
  12549. };
  12550. Scene.prototype._animate = function () {
  12551. if (!this.animationsEnabled) {
  12552. return;
  12553. }
  12554. if (!this._animationStartDate) {
  12555. this._animationStartDate = BABYLON.Tools.Now;
  12556. }
  12557. // Getting time
  12558. var now = BABYLON.Tools.Now;
  12559. var delay = now - this._animationStartDate;
  12560. for (var index = 0; index < this._activeAnimatables.length; index++) {
  12561. this._activeAnimatables[index]._animate(delay);
  12562. }
  12563. };
  12564. // Matrix
  12565. Scene.prototype.getViewMatrix = function () {
  12566. return this._viewMatrix;
  12567. };
  12568. Scene.prototype.getProjectionMatrix = function () {
  12569. return this._projectionMatrix;
  12570. };
  12571. Scene.prototype.getTransformMatrix = function () {
  12572. return this._transformMatrix;
  12573. };
  12574. Scene.prototype.setTransformMatrix = function (view, projection) {
  12575. this._viewMatrix = view;
  12576. this._projectionMatrix = projection;
  12577. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12578. };
  12579. // Methods
  12580. Scene.prototype.addMesh = function (newMesh) {
  12581. newMesh.uniqueId = this._uniqueIdCounter++;
  12582. var position = this.meshes.push(newMesh);
  12583. //notify the collision coordinator
  12584. this.collisionCoordinator.onMeshAdded(newMesh);
  12585. if (this.onNewMeshAdded) {
  12586. this.onNewMeshAdded(newMesh, position, this);
  12587. }
  12588. };
  12589. Scene.prototype.removeMesh = function (toRemove) {
  12590. var index = this.meshes.indexOf(toRemove);
  12591. if (index !== -1) {
  12592. // Remove from the scene if mesh found
  12593. this.meshes.splice(index, 1);
  12594. }
  12595. //notify the collision coordinator
  12596. this.collisionCoordinator.onMeshRemoved(toRemove);
  12597. if (this.onMeshRemoved) {
  12598. this.onMeshRemoved(toRemove);
  12599. }
  12600. return index;
  12601. };
  12602. Scene.prototype.removeLight = function (toRemove) {
  12603. var index = this.lights.indexOf(toRemove);
  12604. if (index !== -1) {
  12605. // Remove from the scene if mesh found
  12606. this.lights.splice(index, 1);
  12607. }
  12608. if (this.onLightRemoved) {
  12609. this.onLightRemoved(toRemove);
  12610. }
  12611. return index;
  12612. };
  12613. Scene.prototype.removeCamera = function (toRemove) {
  12614. var index = this.cameras.indexOf(toRemove);
  12615. if (index !== -1) {
  12616. // Remove from the scene if mesh found
  12617. this.cameras.splice(index, 1);
  12618. }
  12619. // Remove from activeCameras
  12620. var index2 = this.activeCameras.indexOf(toRemove);
  12621. if (index2 !== -1) {
  12622. // Remove from the scene if mesh found
  12623. this.activeCameras.splice(index2, 1);
  12624. }
  12625. // Reset the activeCamera
  12626. if (this.activeCamera === toRemove) {
  12627. if (this.cameras.length > 0) {
  12628. this.activeCamera = this.cameras[0];
  12629. }
  12630. else {
  12631. this.activeCamera = null;
  12632. }
  12633. }
  12634. if (this.onCameraRemoved) {
  12635. this.onCameraRemoved(toRemove);
  12636. }
  12637. return index;
  12638. };
  12639. Scene.prototype.addLight = function (newLight) {
  12640. newLight.uniqueId = this._uniqueIdCounter++;
  12641. var position = this.lights.push(newLight);
  12642. if (this.onNewLightAdded) {
  12643. this.onNewLightAdded(newLight, position, this);
  12644. }
  12645. };
  12646. Scene.prototype.addCamera = function (newCamera) {
  12647. newCamera.uniqueId = this._uniqueIdCounter++;
  12648. var position = this.cameras.push(newCamera);
  12649. if (this.onNewCameraAdded) {
  12650. this.onNewCameraAdded(newCamera, position, this);
  12651. }
  12652. };
  12653. /**
  12654. * sets the active camera of the scene using its ID
  12655. * @param {string} id - the camera's ID
  12656. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12657. * @see activeCamera
  12658. */
  12659. Scene.prototype.setActiveCameraByID = function (id) {
  12660. var camera = this.getCameraByID(id);
  12661. if (camera) {
  12662. this.activeCamera = camera;
  12663. return camera;
  12664. }
  12665. return null;
  12666. };
  12667. /**
  12668. * sets the active camera of the scene using its name
  12669. * @param {string} name - the camera's name
  12670. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  12671. * @see activeCamera
  12672. */
  12673. Scene.prototype.setActiveCameraByName = function (name) {
  12674. var camera = this.getCameraByName(name);
  12675. if (camera) {
  12676. this.activeCamera = camera;
  12677. return camera;
  12678. }
  12679. return null;
  12680. };
  12681. /**
  12682. * get a material using its id
  12683. * @param {string} the material's ID
  12684. * @return {BABYLON.Material|null} the material or null if none found.
  12685. */
  12686. Scene.prototype.getMaterialByID = function (id) {
  12687. for (var index = 0; index < this.materials.length; index++) {
  12688. if (this.materials[index].id === id) {
  12689. return this.materials[index];
  12690. }
  12691. }
  12692. return null;
  12693. };
  12694. /**
  12695. * get a material using its name
  12696. * @param {string} the material's name
  12697. * @return {BABYLON.Material|null} the material or null if none found.
  12698. */
  12699. Scene.prototype.getMaterialByName = function (name) {
  12700. for (var index = 0; index < this.materials.length; index++) {
  12701. if (this.materials[index].name === name) {
  12702. return this.materials[index];
  12703. }
  12704. }
  12705. return null;
  12706. };
  12707. Scene.prototype.getCameraByID = function (id) {
  12708. for (var index = 0; index < this.cameras.length; index++) {
  12709. if (this.cameras[index].id === id) {
  12710. return this.cameras[index];
  12711. }
  12712. }
  12713. return null;
  12714. };
  12715. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  12716. for (var index = 0; index < this.cameras.length; index++) {
  12717. if (this.cameras[index].uniqueId === uniqueId) {
  12718. return this.cameras[index];
  12719. }
  12720. }
  12721. return null;
  12722. };
  12723. /**
  12724. * get a camera using its name
  12725. * @param {string} the camera's name
  12726. * @return {BABYLON.Camera|null} the camera or null if none found.
  12727. */
  12728. Scene.prototype.getCameraByName = function (name) {
  12729. for (var index = 0; index < this.cameras.length; index++) {
  12730. if (this.cameras[index].name === name) {
  12731. return this.cameras[index];
  12732. }
  12733. }
  12734. return null;
  12735. };
  12736. /**
  12737. * get a light node using its name
  12738. * @param {string} the light's name
  12739. * @return {BABYLON.Light|null} the light or null if none found.
  12740. */
  12741. Scene.prototype.getLightByName = function (name) {
  12742. for (var index = 0; index < this.lights.length; index++) {
  12743. if (this.lights[index].name === name) {
  12744. return this.lights[index];
  12745. }
  12746. }
  12747. return null;
  12748. };
  12749. /**
  12750. * get a light node using its ID
  12751. * @param {string} the light's id
  12752. * @return {BABYLON.Light|null} the light or null if none found.
  12753. */
  12754. Scene.prototype.getLightByID = function (id) {
  12755. for (var index = 0; index < this.lights.length; index++) {
  12756. if (this.lights[index].id === id) {
  12757. return this.lights[index];
  12758. }
  12759. }
  12760. return null;
  12761. };
  12762. /**
  12763. * get a light node using its scene-generated unique ID
  12764. * @param {number} the light's unique id
  12765. * @return {BABYLON.Light|null} the light or null if none found.
  12766. */
  12767. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  12768. for (var index = 0; index < this.lights.length; index++) {
  12769. if (this.lights[index].uniqueId === uniqueId) {
  12770. return this.lights[index];
  12771. }
  12772. }
  12773. return null;
  12774. };
  12775. /**
  12776. * get a geometry using its ID
  12777. * @param {string} the geometry's id
  12778. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  12779. */
  12780. Scene.prototype.getGeometryByID = function (id) {
  12781. for (var index = 0; index < this._geometries.length; index++) {
  12782. if (this._geometries[index].id === id) {
  12783. return this._geometries[index];
  12784. }
  12785. }
  12786. return null;
  12787. };
  12788. /**
  12789. * add a new geometry to this scene.
  12790. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  12791. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  12792. * @return {boolean} was the geometry added or not
  12793. */
  12794. Scene.prototype.pushGeometry = function (geometry, force) {
  12795. if (!force && this.getGeometryByID(geometry.id)) {
  12796. return false;
  12797. }
  12798. this._geometries.push(geometry);
  12799. //notify the collision coordinator
  12800. this.collisionCoordinator.onGeometryAdded(geometry);
  12801. if (this.onGeometryAdded) {
  12802. this.onGeometryAdded(geometry);
  12803. }
  12804. return true;
  12805. };
  12806. /**
  12807. * Removes an existing geometry
  12808. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  12809. * @return {boolean} was the geometry removed or not
  12810. */
  12811. Scene.prototype.removeGeometry = function (geometry) {
  12812. var index = this._geometries.indexOf(geometry);
  12813. if (index > -1) {
  12814. this._geometries.splice(index, 1);
  12815. //notify the collision coordinator
  12816. this.collisionCoordinator.onGeometryDeleted(geometry);
  12817. if (this.onGeometryRemoved) {
  12818. this.onGeometryRemoved(geometry);
  12819. }
  12820. return true;
  12821. }
  12822. return false;
  12823. };
  12824. Scene.prototype.getGeometries = function () {
  12825. return this._geometries;
  12826. };
  12827. /**
  12828. * Get the first added mesh found of a given ID
  12829. * @param {string} id - the id to search for
  12830. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12831. */
  12832. Scene.prototype.getMeshByID = function (id) {
  12833. for (var index = 0; index < this.meshes.length; index++) {
  12834. if (this.meshes[index].id === id) {
  12835. return this.meshes[index];
  12836. }
  12837. }
  12838. return null;
  12839. };
  12840. /**
  12841. * Get a mesh with its auto-generated unique id
  12842. * @param {number} uniqueId - the unique id to search for
  12843. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12844. */
  12845. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  12846. for (var index = 0; index < this.meshes.length; index++) {
  12847. if (this.meshes[index].uniqueId === uniqueId) {
  12848. return this.meshes[index];
  12849. }
  12850. }
  12851. return null;
  12852. };
  12853. /**
  12854. * Get a the last added mesh found of a given ID
  12855. * @param {string} id - the id to search for
  12856. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  12857. */
  12858. Scene.prototype.getLastMeshByID = function (id) {
  12859. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12860. if (this.meshes[index].id === id) {
  12861. return this.meshes[index];
  12862. }
  12863. }
  12864. return null;
  12865. };
  12866. /**
  12867. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  12868. * @param {string} id - the id to search for
  12869. * @return {BABYLON.Node|null} the node found or null if not found at all.
  12870. */
  12871. Scene.prototype.getLastEntryByID = function (id) {
  12872. for (var index = this.meshes.length - 1; index >= 0; index--) {
  12873. if (this.meshes[index].id === id) {
  12874. return this.meshes[index];
  12875. }
  12876. }
  12877. for (index = this.cameras.length - 1; index >= 0; index--) {
  12878. if (this.cameras[index].id === id) {
  12879. return this.cameras[index];
  12880. }
  12881. }
  12882. for (index = this.lights.length - 1; index >= 0; index--) {
  12883. if (this.lights[index].id === id) {
  12884. return this.lights[index];
  12885. }
  12886. }
  12887. return null;
  12888. };
  12889. Scene.prototype.getNodeByName = function (name) {
  12890. var mesh = this.getMeshByName(name);
  12891. if (mesh) {
  12892. return mesh;
  12893. }
  12894. var light = this.getLightByName(name);
  12895. if (light) {
  12896. return light;
  12897. }
  12898. return this.getCameraByName(name);
  12899. };
  12900. Scene.prototype.getMeshByName = function (name) {
  12901. for (var index = 0; index < this.meshes.length; index++) {
  12902. if (this.meshes[index].name === name) {
  12903. return this.meshes[index];
  12904. }
  12905. }
  12906. return null;
  12907. };
  12908. Scene.prototype.getSoundByName = function (name) {
  12909. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  12910. if (this.mainSoundTrack.soundCollection[index].name === name) {
  12911. return this.mainSoundTrack.soundCollection[index];
  12912. }
  12913. }
  12914. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  12915. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  12916. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  12917. return this.soundTracks[sdIndex].soundCollection[index];
  12918. }
  12919. }
  12920. }
  12921. return null;
  12922. };
  12923. Scene.prototype.getLastSkeletonByID = function (id) {
  12924. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  12925. if (this.skeletons[index].id === id) {
  12926. return this.skeletons[index];
  12927. }
  12928. }
  12929. return null;
  12930. };
  12931. Scene.prototype.getSkeletonById = function (id) {
  12932. for (var index = 0; index < this.skeletons.length; index++) {
  12933. if (this.skeletons[index].id === id) {
  12934. return this.skeletons[index];
  12935. }
  12936. }
  12937. return null;
  12938. };
  12939. Scene.prototype.getSkeletonByName = function (name) {
  12940. for (var index = 0; index < this.skeletons.length; index++) {
  12941. if (this.skeletons[index].name === name) {
  12942. return this.skeletons[index];
  12943. }
  12944. }
  12945. return null;
  12946. };
  12947. Scene.prototype.isActiveMesh = function (mesh) {
  12948. return (this._activeMeshes.indexOf(mesh) !== -1);
  12949. };
  12950. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  12951. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  12952. var material = subMesh.getMaterial();
  12953. if (mesh.showSubMeshesBoundingBox) {
  12954. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  12955. }
  12956. if (material) {
  12957. // Render targets
  12958. if (material.getRenderTargetTextures) {
  12959. if (this._processedMaterials.indexOf(material) === -1) {
  12960. this._processedMaterials.push(material);
  12961. this._renderTargets.concat(material.getRenderTargetTextures());
  12962. }
  12963. }
  12964. // Dispatch
  12965. this._activeIndices += subMesh.indexCount;
  12966. this._renderingManager.dispatch(subMesh);
  12967. }
  12968. }
  12969. };
  12970. Scene.prototype._evaluateActiveMeshes = function () {
  12971. this.activeCamera._activeMeshes.reset();
  12972. this._activeMeshes.reset();
  12973. this._renderingManager.reset();
  12974. this._processedMaterials.reset();
  12975. this._activeParticleSystems.reset();
  12976. this._activeSkeletons.reset();
  12977. this._boundingBoxRenderer.reset();
  12978. if (!this._frustumPlanes) {
  12979. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  12980. }
  12981. else {
  12982. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  12983. }
  12984. // Meshes
  12985. var meshes;
  12986. var len;
  12987. if (this._selectionOctree) {
  12988. var selection = this._selectionOctree.select(this._frustumPlanes);
  12989. meshes = selection.data;
  12990. len = selection.length;
  12991. }
  12992. else {
  12993. len = this.meshes.length;
  12994. meshes = this.meshes;
  12995. }
  12996. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  12997. var mesh = meshes[meshIndex];
  12998. if (mesh.isBlocked) {
  12999. continue;
  13000. }
  13001. this._totalVertices += mesh.getTotalVertices();
  13002. if (!mesh.isReady() || !mesh.isEnabled()) {
  13003. continue;
  13004. }
  13005. mesh.computeWorldMatrix();
  13006. // Intersections
  13007. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  13008. this._meshesForIntersections.pushNoDuplicate(mesh);
  13009. }
  13010. // Switch to current LOD
  13011. var meshLOD = mesh.getLOD(this.activeCamera);
  13012. if (!meshLOD) {
  13013. continue;
  13014. }
  13015. mesh._preActivate();
  13016. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  13017. this._activeMeshes.push(mesh);
  13018. this.activeCamera._activeMeshes.push(mesh);
  13019. mesh._activate(this._renderId);
  13020. this._activeMesh(meshLOD);
  13021. }
  13022. }
  13023. // Particle systems
  13024. var beforeParticlesDate = BABYLON.Tools.Now;
  13025. if (this.particlesEnabled) {
  13026. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  13027. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  13028. var particleSystem = this.particleSystems[particleIndex];
  13029. if (!particleSystem.isStarted()) {
  13030. continue;
  13031. }
  13032. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  13033. this._activeParticleSystems.push(particleSystem);
  13034. particleSystem.animate();
  13035. }
  13036. }
  13037. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  13038. }
  13039. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  13040. };
  13041. Scene.prototype._activeMesh = function (mesh) {
  13042. if (mesh.skeleton && this.skeletonsEnabled) {
  13043. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  13044. }
  13045. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  13046. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  13047. }
  13048. if (mesh && mesh.subMeshes) {
  13049. // Submeshes Octrees
  13050. var len;
  13051. var subMeshes;
  13052. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  13053. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  13054. len = intersections.length;
  13055. subMeshes = intersections.data;
  13056. }
  13057. else {
  13058. subMeshes = mesh.subMeshes;
  13059. len = subMeshes.length;
  13060. }
  13061. for (var subIndex = 0; subIndex < len; subIndex++) {
  13062. var subMesh = subMeshes[subIndex];
  13063. this._evaluateSubMesh(subMesh, mesh);
  13064. }
  13065. }
  13066. };
  13067. Scene.prototype.updateTransformMatrix = function (force) {
  13068. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  13069. };
  13070. Scene.prototype._renderForCamera = function (camera) {
  13071. var engine = this._engine;
  13072. this.activeCamera = camera;
  13073. if (!this.activeCamera)
  13074. throw new Error("Active camera not set");
  13075. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13076. // Viewport
  13077. engine.setViewport(this.activeCamera.viewport);
  13078. // Camera
  13079. this.resetCachedMaterial();
  13080. this._renderId++;
  13081. this.updateTransformMatrix();
  13082. if (this.beforeCameraRender) {
  13083. this.beforeCameraRender(this.activeCamera);
  13084. }
  13085. // Meshes
  13086. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  13087. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  13088. this._evaluateActiveMeshes();
  13089. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  13090. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  13091. // Skeletons
  13092. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  13093. var skeleton = this._activeSkeletons.data[skeletonIndex];
  13094. skeleton.prepare();
  13095. }
  13096. // Render targets
  13097. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13098. if (this.renderTargetsEnabled) {
  13099. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13100. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  13101. var renderTarget = this._renderTargets.data[renderIndex];
  13102. if (renderTarget._shouldRender()) {
  13103. this._renderId++;
  13104. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  13105. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  13106. }
  13107. }
  13108. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  13109. this._renderId++;
  13110. }
  13111. if (this._renderTargets.length > 0) {
  13112. engine.restoreDefaultFramebuffer();
  13113. }
  13114. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13115. // Prepare Frame
  13116. this.postProcessManager._prepareFrame();
  13117. var beforeRenderDate = BABYLON.Tools.Now;
  13118. // Backgrounds
  13119. if (this.layers.length) {
  13120. engine.setDepthBuffer(false);
  13121. var layerIndex;
  13122. var layer;
  13123. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13124. layer = this.layers[layerIndex];
  13125. if (layer.isBackground) {
  13126. layer.render();
  13127. }
  13128. }
  13129. engine.setDepthBuffer(true);
  13130. }
  13131. // Render
  13132. BABYLON.Tools.StartPerformanceCounter("Main render");
  13133. this._renderingManager.render(null, null, true, true);
  13134. BABYLON.Tools.EndPerformanceCounter("Main render");
  13135. // Bounding boxes
  13136. this._boundingBoxRenderer.render();
  13137. // Lens flares
  13138. if (this.lensFlaresEnabled) {
  13139. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13140. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  13141. this.lensFlareSystems[lensFlareSystemIndex].render();
  13142. }
  13143. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  13144. }
  13145. // Foregrounds
  13146. if (this.layers.length) {
  13147. engine.setDepthBuffer(false);
  13148. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  13149. layer = this.layers[layerIndex];
  13150. if (!layer.isBackground) {
  13151. layer.render();
  13152. }
  13153. }
  13154. engine.setDepthBuffer(true);
  13155. }
  13156. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  13157. // Finalize frame
  13158. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  13159. // Update camera
  13160. this.activeCamera._updateFromScene();
  13161. // Reset some special arrays
  13162. this._renderTargets.reset();
  13163. if (this.afterCameraRender) {
  13164. this.afterCameraRender(this.activeCamera);
  13165. }
  13166. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  13167. };
  13168. Scene.prototype._processSubCameras = function (camera) {
  13169. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  13170. this._renderForCamera(camera);
  13171. return;
  13172. }
  13173. // rig cameras
  13174. for (var index = 0; index < camera._rigCameras.length; index++) {
  13175. this._renderForCamera(camera._rigCameras[index]);
  13176. }
  13177. this.activeCamera = camera;
  13178. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  13179. // Update camera
  13180. this.activeCamera._updateFromScene();
  13181. };
  13182. Scene.prototype._checkIntersections = function () {
  13183. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  13184. var sourceMesh = this._meshesForIntersections.data[index];
  13185. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  13186. var action = sourceMesh.actionManager.actions[actionIndex];
  13187. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13188. var parameters = action.getTriggerParameter();
  13189. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  13190. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  13191. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  13192. if (areIntersecting && currentIntersectionInProgress === -1) {
  13193. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  13194. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  13195. sourceMesh._intersectionsInProgress.push(otherMesh);
  13196. }
  13197. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13198. sourceMesh._intersectionsInProgress.push(otherMesh);
  13199. }
  13200. }
  13201. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  13202. //They intersected, and now they don't.
  13203. //is this trigger an exit trigger? execute an event.
  13204. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13205. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  13206. }
  13207. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  13208. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  13209. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  13210. }
  13211. }
  13212. }
  13213. }
  13214. }
  13215. };
  13216. Scene.prototype.render = function () {
  13217. var startDate = BABYLON.Tools.Now;
  13218. this._particlesDuration = 0;
  13219. this._spritesDuration = 0;
  13220. this._activeParticles = 0;
  13221. this._renderDuration = 0;
  13222. this._renderTargetsDuration = 0;
  13223. this._evaluateActiveMeshesDuration = 0;
  13224. this._totalVertices = 0;
  13225. this._activeIndices = 0;
  13226. this._activeBones = 0;
  13227. this.getEngine().resetDrawCalls();
  13228. this._meshesForIntersections.reset();
  13229. this.resetCachedMaterial();
  13230. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  13231. // Actions
  13232. if (this.actionManager) {
  13233. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  13234. }
  13235. //Simplification Queue
  13236. if (!this.simplificationQueue.running) {
  13237. this.simplificationQueue.executeNext();
  13238. }
  13239. // Before render
  13240. if (this.beforeRender) {
  13241. this.beforeRender();
  13242. }
  13243. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  13244. this._onBeforeRenderCallbacks[callbackIndex]();
  13245. }
  13246. // Animations
  13247. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  13248. this._animationRatio = deltaTime * (60.0 / 1000.0);
  13249. this._animate();
  13250. // Physics
  13251. if (this._physicsEngine) {
  13252. BABYLON.Tools.StartPerformanceCounter("Physics");
  13253. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  13254. BABYLON.Tools.EndPerformanceCounter("Physics");
  13255. }
  13256. // Customs render targets
  13257. var beforeRenderTargetDate = BABYLON.Tools.Now;
  13258. var engine = this.getEngine();
  13259. var currentActiveCamera = this.activeCamera;
  13260. if (this.renderTargetsEnabled) {
  13261. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13262. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  13263. var renderTarget = this.customRenderTargets[customIndex];
  13264. if (renderTarget._shouldRender()) {
  13265. this._renderId++;
  13266. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  13267. if (!this.activeCamera)
  13268. throw new Error("Active camera not set");
  13269. // Viewport
  13270. engine.setViewport(this.activeCamera.viewport);
  13271. // Camera
  13272. this.updateTransformMatrix();
  13273. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  13274. }
  13275. }
  13276. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  13277. this._renderId++;
  13278. }
  13279. if (this.customRenderTargets.length > 0) {
  13280. engine.restoreDefaultFramebuffer();
  13281. }
  13282. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  13283. this.activeCamera = currentActiveCamera;
  13284. // Procedural textures
  13285. if (this.proceduralTexturesEnabled) {
  13286. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13287. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  13288. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  13289. if (proceduralTexture._shouldRender()) {
  13290. proceduralTexture.render();
  13291. }
  13292. }
  13293. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  13294. }
  13295. // Clear
  13296. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  13297. // Shadows
  13298. if (this.shadowsEnabled) {
  13299. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  13300. var light = this.lights[lightIndex];
  13301. var shadowGenerator = light.getShadowGenerator();
  13302. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  13303. this._renderTargets.push(shadowGenerator.getShadowMap());
  13304. }
  13305. }
  13306. }
  13307. // Depth renderer
  13308. if (this._depthRenderer) {
  13309. this._renderTargets.push(this._depthRenderer.getDepthMap());
  13310. }
  13311. // RenderPipeline
  13312. this.postProcessRenderPipelineManager.update();
  13313. // Multi-cameras?
  13314. if (this.activeCameras.length > 0) {
  13315. var currentRenderId = this._renderId;
  13316. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  13317. this._renderId = currentRenderId;
  13318. this._processSubCameras(this.activeCameras[cameraIndex]);
  13319. }
  13320. }
  13321. else {
  13322. if (!this.activeCamera) {
  13323. throw new Error("No camera defined");
  13324. }
  13325. this._processSubCameras(this.activeCamera);
  13326. }
  13327. // Intersection checks
  13328. this._checkIntersections();
  13329. // Update the audio listener attached to the camera
  13330. this._updateAudioParameters();
  13331. // After render
  13332. if (this.afterRender) {
  13333. this.afterRender();
  13334. }
  13335. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  13336. this._onAfterRenderCallbacks[callbackIndex]();
  13337. }
  13338. // Cleaning
  13339. for (var index = 0; index < this._toBeDisposed.length; index++) {
  13340. this._toBeDisposed.data[index].dispose();
  13341. this._toBeDisposed[index] = null;
  13342. }
  13343. this._toBeDisposed.reset();
  13344. if (this.dumpNextRenderTargets) {
  13345. this.dumpNextRenderTargets = false;
  13346. }
  13347. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  13348. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  13349. };
  13350. Scene.prototype._updateAudioParameters = function () {
  13351. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  13352. return;
  13353. }
  13354. var listeningCamera;
  13355. var audioEngine = BABYLON.Engine.audioEngine;
  13356. if (this.activeCameras.length > 0) {
  13357. listeningCamera = this.activeCameras[0];
  13358. }
  13359. else {
  13360. listeningCamera = this.activeCamera;
  13361. }
  13362. if (listeningCamera && audioEngine.canUseWebAudio) {
  13363. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  13364. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  13365. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  13366. cameraDirection.normalize();
  13367. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  13368. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13369. var sound = this.mainSoundTrack.soundCollection[i];
  13370. if (sound.useCustomAttenuation) {
  13371. sound.updateDistanceFromListener();
  13372. }
  13373. }
  13374. for (i = 0; i < this.soundTracks.length; i++) {
  13375. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13376. sound = this.soundTracks[i].soundCollection[j];
  13377. if (sound.useCustomAttenuation) {
  13378. sound.updateDistanceFromListener();
  13379. }
  13380. }
  13381. }
  13382. }
  13383. };
  13384. Object.defineProperty(Scene.prototype, "audioEnabled", {
  13385. // Audio
  13386. get: function () {
  13387. return this._audioEnabled;
  13388. },
  13389. set: function (value) {
  13390. this._audioEnabled = value;
  13391. if (this._audioEnabled) {
  13392. this._enableAudio();
  13393. }
  13394. else {
  13395. this._disableAudio();
  13396. }
  13397. },
  13398. enumerable: true,
  13399. configurable: true
  13400. });
  13401. Scene.prototype._disableAudio = function () {
  13402. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13403. this.mainSoundTrack.soundCollection[i].pause();
  13404. }
  13405. for (i = 0; i < this.soundTracks.length; i++) {
  13406. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13407. this.soundTracks[i].soundCollection[j].pause();
  13408. }
  13409. }
  13410. };
  13411. Scene.prototype._enableAudio = function () {
  13412. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  13413. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  13414. this.mainSoundTrack.soundCollection[i].play();
  13415. }
  13416. }
  13417. for (i = 0; i < this.soundTracks.length; i++) {
  13418. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  13419. if (this.soundTracks[i].soundCollection[j].isPaused) {
  13420. this.soundTracks[i].soundCollection[j].play();
  13421. }
  13422. }
  13423. }
  13424. };
  13425. Object.defineProperty(Scene.prototype, "headphone", {
  13426. get: function () {
  13427. return this._headphone;
  13428. },
  13429. set: function (value) {
  13430. this._headphone = value;
  13431. if (this._headphone) {
  13432. this._switchAudioModeForHeadphones();
  13433. }
  13434. else {
  13435. this._switchAudioModeForNormalSpeakers();
  13436. }
  13437. },
  13438. enumerable: true,
  13439. configurable: true
  13440. });
  13441. Scene.prototype._switchAudioModeForHeadphones = function () {
  13442. this.mainSoundTrack.switchPanningModelToHRTF();
  13443. for (var i = 0; i < this.soundTracks.length; i++) {
  13444. this.soundTracks[i].switchPanningModelToHRTF();
  13445. }
  13446. };
  13447. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  13448. this.mainSoundTrack.switchPanningModelToEqualPower();
  13449. for (var i = 0; i < this.soundTracks.length; i++) {
  13450. this.soundTracks[i].switchPanningModelToEqualPower();
  13451. }
  13452. };
  13453. Scene.prototype.enableDepthRenderer = function () {
  13454. if (this._depthRenderer) {
  13455. return this._depthRenderer;
  13456. }
  13457. this._depthRenderer = new BABYLON.DepthRenderer(this);
  13458. return this._depthRenderer;
  13459. };
  13460. Scene.prototype.disableDepthRenderer = function () {
  13461. if (!this._depthRenderer) {
  13462. return;
  13463. }
  13464. this._depthRenderer.dispose();
  13465. this._depthRenderer = null;
  13466. };
  13467. Scene.prototype.dispose = function () {
  13468. this.beforeRender = null;
  13469. this.afterRender = null;
  13470. this.skeletons = [];
  13471. this._boundingBoxRenderer.dispose();
  13472. if (this._depthRenderer) {
  13473. this._depthRenderer.dispose();
  13474. }
  13475. // Debug layer
  13476. this.debugLayer.hide();
  13477. // Events
  13478. if (this.onDispose) {
  13479. this.onDispose();
  13480. }
  13481. this._onBeforeRenderCallbacks = [];
  13482. this._onAfterRenderCallbacks = [];
  13483. this.detachControl();
  13484. // Release sounds & sounds tracks
  13485. this.disposeSounds();
  13486. // Detach cameras
  13487. var canvas = this._engine.getRenderingCanvas();
  13488. var index;
  13489. for (index = 0; index < this.cameras.length; index++) {
  13490. this.cameras[index].detachControl(canvas);
  13491. }
  13492. // Release lights
  13493. while (this.lights.length) {
  13494. this.lights[0].dispose();
  13495. }
  13496. // Release meshes
  13497. while (this.meshes.length) {
  13498. this.meshes[0].dispose(true);
  13499. }
  13500. // Release cameras
  13501. while (this.cameras.length) {
  13502. this.cameras[0].dispose();
  13503. }
  13504. // Release materials
  13505. while (this.materials.length) {
  13506. this.materials[0].dispose();
  13507. }
  13508. // Release particles
  13509. while (this.particleSystems.length) {
  13510. this.particleSystems[0].dispose();
  13511. }
  13512. // Release sprites
  13513. while (this.spriteManagers.length) {
  13514. this.spriteManagers[0].dispose();
  13515. }
  13516. // Release layers
  13517. while (this.layers.length) {
  13518. this.layers[0].dispose();
  13519. }
  13520. // Release textures
  13521. while (this.textures.length) {
  13522. this.textures[0].dispose();
  13523. }
  13524. // Post-processes
  13525. this.postProcessManager.dispose();
  13526. // Physics
  13527. if (this._physicsEngine) {
  13528. this.disablePhysicsEngine();
  13529. }
  13530. // Remove from engine
  13531. index = this._engine.scenes.indexOf(this);
  13532. if (index > -1) {
  13533. this._engine.scenes.splice(index, 1);
  13534. }
  13535. this._engine.wipeCaches();
  13536. };
  13537. // Release sounds & sounds tracks
  13538. Scene.prototype.disposeSounds = function () {
  13539. this.mainSoundTrack.dispose();
  13540. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  13541. this.soundTracks[scIndex].dispose();
  13542. }
  13543. };
  13544. // Octrees
  13545. Scene.prototype.getWorldExtends = function () {
  13546. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13547. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  13548. for (var index = 0; index < this.meshes.length; index++) {
  13549. var mesh = this.meshes[index];
  13550. mesh.computeWorldMatrix(true);
  13551. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  13552. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  13553. BABYLON.Tools.CheckExtends(minBox, min, max);
  13554. BABYLON.Tools.CheckExtends(maxBox, min, max);
  13555. }
  13556. return {
  13557. min: min,
  13558. max: max
  13559. };
  13560. };
  13561. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  13562. if (maxCapacity === void 0) { maxCapacity = 64; }
  13563. if (maxDepth === void 0) { maxDepth = 2; }
  13564. if (!this._selectionOctree) {
  13565. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  13566. }
  13567. var worldExtends = this.getWorldExtends();
  13568. // Update octree
  13569. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  13570. return this._selectionOctree;
  13571. };
  13572. // Picking
  13573. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  13574. var engine = this._engine;
  13575. if (!camera) {
  13576. if (!this.activeCamera)
  13577. throw new Error("Active camera not set");
  13578. camera = this.activeCamera;
  13579. }
  13580. var cameraViewport = camera.viewport;
  13581. var viewport = cameraViewport.toGlobal(engine);
  13582. // Moving coordinates to local viewport world
  13583. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  13584. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  13585. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13586. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  13587. };
  13588. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  13589. var pickingInfo = null;
  13590. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  13591. var mesh = this.meshes[meshIndex];
  13592. if (predicate) {
  13593. if (!predicate(mesh)) {
  13594. continue;
  13595. }
  13596. }
  13597. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  13598. continue;
  13599. }
  13600. var world = mesh.getWorldMatrix();
  13601. var ray = rayFunction(world);
  13602. var result = mesh.intersects(ray, fastCheck);
  13603. if (!result || !result.hit)
  13604. continue;
  13605. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  13606. continue;
  13607. pickingInfo = result;
  13608. if (fastCheck) {
  13609. break;
  13610. }
  13611. }
  13612. return pickingInfo || new BABYLON.PickingInfo();
  13613. };
  13614. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  13615. var _this = this;
  13616. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  13617. /// <param name="x">X position on screen</param>
  13618. /// <param name="y">Y position on screen</param>
  13619. /// <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>
  13620. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  13621. /// <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>
  13622. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  13623. };
  13624. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  13625. var _this = this;
  13626. return this._internalPick(function (world) {
  13627. if (!_this._pickWithRayInverseMatrix) {
  13628. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  13629. }
  13630. world.invertToRef(_this._pickWithRayInverseMatrix);
  13631. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  13632. }, predicate, fastCheck);
  13633. };
  13634. Scene.prototype.setPointerOverMesh = function (mesh) {
  13635. if (this._pointerOverMesh === mesh) {
  13636. return;
  13637. }
  13638. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13639. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13640. }
  13641. this._pointerOverMesh = mesh;
  13642. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  13643. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  13644. }
  13645. };
  13646. Scene.prototype.getPointerOverMesh = function () {
  13647. return this._pointerOverMesh;
  13648. };
  13649. // Physics
  13650. Scene.prototype.getPhysicsEngine = function () {
  13651. return this._physicsEngine;
  13652. };
  13653. Scene.prototype.enablePhysics = function (gravity, plugin) {
  13654. if (this._physicsEngine) {
  13655. return true;
  13656. }
  13657. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  13658. if (!this._physicsEngine.isSupported()) {
  13659. this._physicsEngine = null;
  13660. return false;
  13661. }
  13662. this._physicsEngine._initialize(gravity);
  13663. return true;
  13664. };
  13665. Scene.prototype.disablePhysicsEngine = function () {
  13666. if (!this._physicsEngine) {
  13667. return;
  13668. }
  13669. this._physicsEngine.dispose();
  13670. this._physicsEngine = undefined;
  13671. };
  13672. Scene.prototype.isPhysicsEnabled = function () {
  13673. return this._physicsEngine !== undefined;
  13674. };
  13675. Scene.prototype.setGravity = function (gravity) {
  13676. if (!this._physicsEngine) {
  13677. return;
  13678. }
  13679. this._physicsEngine._setGravity(gravity);
  13680. };
  13681. Scene.prototype.createCompoundImpostor = function (parts, options) {
  13682. if (parts.parts) {
  13683. options = parts;
  13684. parts = parts.parts;
  13685. }
  13686. if (!this._physicsEngine) {
  13687. return null;
  13688. }
  13689. for (var index = 0; index < parts.length; index++) {
  13690. var mesh = parts[index].mesh;
  13691. mesh._physicImpostor = parts[index].impostor;
  13692. mesh._physicsMass = options.mass / parts.length;
  13693. mesh._physicsFriction = options.friction;
  13694. mesh._physicRestitution = options.restitution;
  13695. }
  13696. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  13697. };
  13698. Scene.prototype.deleteCompoundImpostor = function (compound) {
  13699. for (var index = 0; index < compound.parts.length; index++) {
  13700. var mesh = compound.parts[index].mesh;
  13701. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  13702. this._physicsEngine._unregisterMesh(mesh);
  13703. }
  13704. };
  13705. // Misc.
  13706. Scene.prototype.createDefaultCameraOrLight = function () {
  13707. // Light
  13708. if (this.lights.length === 0) {
  13709. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  13710. }
  13711. // Camera
  13712. if (!this.activeCamera) {
  13713. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  13714. // Compute position
  13715. var worldExtends = this.getWorldExtends();
  13716. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  13717. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  13718. camera.setTarget(worldCenter);
  13719. this.activeCamera = camera;
  13720. }
  13721. };
  13722. // Tags
  13723. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  13724. if (tagsQuery === undefined) {
  13725. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  13726. return list;
  13727. }
  13728. var listByTags = [];
  13729. forEach = forEach || (function (item) { return; });
  13730. for (var i in list) {
  13731. var item = list[i];
  13732. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  13733. listByTags.push(item);
  13734. forEach(item);
  13735. }
  13736. }
  13737. return listByTags;
  13738. };
  13739. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  13740. return this._getByTags(this.meshes, tagsQuery, forEach);
  13741. };
  13742. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  13743. return this._getByTags(this.cameras, tagsQuery, forEach);
  13744. };
  13745. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  13746. return this._getByTags(this.lights, tagsQuery, forEach);
  13747. };
  13748. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  13749. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  13750. };
  13751. // Statics
  13752. Scene._FOGMODE_NONE = 0;
  13753. Scene._FOGMODE_EXP = 1;
  13754. Scene._FOGMODE_EXP2 = 2;
  13755. Scene._FOGMODE_LINEAR = 3;
  13756. Scene.MinDeltaTime = 1.0;
  13757. Scene.MaxDeltaTime = 1000.0;
  13758. return Scene;
  13759. })();
  13760. BABYLON.Scene = Scene;
  13761. })(BABYLON || (BABYLON = {}));
  13762. //# sourceMappingURL=babylon.scene.js.map
  13763. var BABYLON;
  13764. (function (BABYLON) {
  13765. var VertexBuffer = (function () {
  13766. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  13767. if (engine instanceof BABYLON.Mesh) {
  13768. this._engine = engine.getScene().getEngine();
  13769. }
  13770. else {
  13771. this._engine = engine;
  13772. }
  13773. this._updatable = updatable;
  13774. this._data = data;
  13775. if (!postponeInternalCreation) {
  13776. this.create();
  13777. }
  13778. this._kind = kind;
  13779. if (stride) {
  13780. this._strideSize = stride;
  13781. return;
  13782. }
  13783. // Deduce stride from kind
  13784. switch (kind) {
  13785. case VertexBuffer.PositionKind:
  13786. this._strideSize = 3;
  13787. break;
  13788. case VertexBuffer.NormalKind:
  13789. this._strideSize = 3;
  13790. break;
  13791. case VertexBuffer.UVKind:
  13792. this._strideSize = 2;
  13793. break;
  13794. case VertexBuffer.UV2Kind:
  13795. this._strideSize = 2;
  13796. break;
  13797. case VertexBuffer.ColorKind:
  13798. this._strideSize = 4;
  13799. break;
  13800. case VertexBuffer.MatricesIndicesKind:
  13801. this._strideSize = 4;
  13802. break;
  13803. case VertexBuffer.MatricesWeightsKind:
  13804. this._strideSize = 4;
  13805. break;
  13806. }
  13807. }
  13808. // Properties
  13809. VertexBuffer.prototype.isUpdatable = function () {
  13810. return this._updatable;
  13811. };
  13812. VertexBuffer.prototype.getData = function () {
  13813. return this._data;
  13814. };
  13815. VertexBuffer.prototype.getBuffer = function () {
  13816. return this._buffer;
  13817. };
  13818. VertexBuffer.prototype.getStrideSize = function () {
  13819. return this._strideSize;
  13820. };
  13821. // Methods
  13822. VertexBuffer.prototype.create = function (data) {
  13823. if (!data && this._buffer) {
  13824. return; // nothing to do
  13825. }
  13826. data = data || this._data;
  13827. if (!this._buffer) {
  13828. if (this._updatable) {
  13829. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  13830. }
  13831. else {
  13832. this._buffer = this._engine.createVertexBuffer(data);
  13833. }
  13834. }
  13835. if (this._updatable) {
  13836. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  13837. this._data = data;
  13838. }
  13839. };
  13840. VertexBuffer.prototype.update = function (data) {
  13841. this.create(data);
  13842. };
  13843. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  13844. if (!this._buffer) {
  13845. return;
  13846. }
  13847. if (this._updatable) {
  13848. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  13849. this._data = null;
  13850. }
  13851. };
  13852. VertexBuffer.prototype.dispose = function () {
  13853. if (!this._buffer) {
  13854. return;
  13855. }
  13856. if (this._engine._releaseBuffer(this._buffer)) {
  13857. this._buffer = null;
  13858. }
  13859. };
  13860. Object.defineProperty(VertexBuffer, "PositionKind", {
  13861. get: function () {
  13862. return VertexBuffer._PositionKind;
  13863. },
  13864. enumerable: true,
  13865. configurable: true
  13866. });
  13867. Object.defineProperty(VertexBuffer, "NormalKind", {
  13868. get: function () {
  13869. return VertexBuffer._NormalKind;
  13870. },
  13871. enumerable: true,
  13872. configurable: true
  13873. });
  13874. Object.defineProperty(VertexBuffer, "UVKind", {
  13875. get: function () {
  13876. return VertexBuffer._UVKind;
  13877. },
  13878. enumerable: true,
  13879. configurable: true
  13880. });
  13881. Object.defineProperty(VertexBuffer, "UV2Kind", {
  13882. get: function () {
  13883. return VertexBuffer._UV2Kind;
  13884. },
  13885. enumerable: true,
  13886. configurable: true
  13887. });
  13888. Object.defineProperty(VertexBuffer, "ColorKind", {
  13889. get: function () {
  13890. return VertexBuffer._ColorKind;
  13891. },
  13892. enumerable: true,
  13893. configurable: true
  13894. });
  13895. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  13896. get: function () {
  13897. return VertexBuffer._MatricesIndicesKind;
  13898. },
  13899. enumerable: true,
  13900. configurable: true
  13901. });
  13902. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  13903. get: function () {
  13904. return VertexBuffer._MatricesWeightsKind;
  13905. },
  13906. enumerable: true,
  13907. configurable: true
  13908. });
  13909. // Enums
  13910. VertexBuffer._PositionKind = "position";
  13911. VertexBuffer._NormalKind = "normal";
  13912. VertexBuffer._UVKind = "uv";
  13913. VertexBuffer._UV2Kind = "uv2";
  13914. VertexBuffer._ColorKind = "color";
  13915. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  13916. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  13917. return VertexBuffer;
  13918. })();
  13919. BABYLON.VertexBuffer = VertexBuffer;
  13920. })(BABYLON || (BABYLON = {}));
  13921. //# sourceMappingURL=babylon.vertexBuffer.js.map
  13922. var BABYLON;
  13923. (function (BABYLON) {
  13924. /**
  13925. * Creates an instance based on a source mesh.
  13926. */
  13927. var InstancedMesh = (function (_super) {
  13928. __extends(InstancedMesh, _super);
  13929. function InstancedMesh(name, source) {
  13930. _super.call(this, name, source.getScene());
  13931. source.instances.push(this);
  13932. this._sourceMesh = source;
  13933. this.position.copyFrom(source.position);
  13934. this.rotation.copyFrom(source.rotation);
  13935. this.scaling.copyFrom(source.scaling);
  13936. if (source.rotationQuaternion) {
  13937. this.rotationQuaternion = source.rotationQuaternion.clone();
  13938. }
  13939. this.infiniteDistance = source.infiniteDistance;
  13940. this.setPivotMatrix(source.getPivotMatrix());
  13941. this.refreshBoundingInfo();
  13942. this._syncSubMeshes();
  13943. }
  13944. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  13945. // Methods
  13946. get: function () {
  13947. return this._sourceMesh.receiveShadows;
  13948. },
  13949. enumerable: true,
  13950. configurable: true
  13951. });
  13952. Object.defineProperty(InstancedMesh.prototype, "material", {
  13953. get: function () {
  13954. return this._sourceMesh.material;
  13955. },
  13956. enumerable: true,
  13957. configurable: true
  13958. });
  13959. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  13960. get: function () {
  13961. return this._sourceMesh.visibility;
  13962. },
  13963. enumerable: true,
  13964. configurable: true
  13965. });
  13966. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  13967. get: function () {
  13968. return this._sourceMesh.skeleton;
  13969. },
  13970. enumerable: true,
  13971. configurable: true
  13972. });
  13973. InstancedMesh.prototype.getTotalVertices = function () {
  13974. return this._sourceMesh.getTotalVertices();
  13975. };
  13976. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  13977. get: function () {
  13978. return this._sourceMesh;
  13979. },
  13980. enumerable: true,
  13981. configurable: true
  13982. });
  13983. InstancedMesh.prototype.getVerticesData = function (kind) {
  13984. return this._sourceMesh.getVerticesData(kind);
  13985. };
  13986. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  13987. return this._sourceMesh.isVerticesDataPresent(kind);
  13988. };
  13989. InstancedMesh.prototype.getIndices = function () {
  13990. return this._sourceMesh.getIndices();
  13991. };
  13992. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  13993. get: function () {
  13994. return this._sourceMesh._positions;
  13995. },
  13996. enumerable: true,
  13997. configurable: true
  13998. });
  13999. InstancedMesh.prototype.refreshBoundingInfo = function () {
  14000. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14001. if (data) {
  14002. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  14003. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14004. }
  14005. this._updateBoundingInfo();
  14006. };
  14007. InstancedMesh.prototype._preActivate = function () {
  14008. if (this._currentLOD) {
  14009. this._currentLOD._preActivate();
  14010. }
  14011. };
  14012. InstancedMesh.prototype._activate = function (renderId) {
  14013. if (this._currentLOD) {
  14014. this._currentLOD._registerInstanceForRenderId(this, renderId);
  14015. }
  14016. };
  14017. InstancedMesh.prototype.getLOD = function (camera) {
  14018. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  14019. if (this._currentLOD === this.sourceMesh) {
  14020. return this;
  14021. }
  14022. return this._currentLOD;
  14023. };
  14024. InstancedMesh.prototype._syncSubMeshes = function () {
  14025. this.releaseSubMeshes();
  14026. if (this._sourceMesh.subMeshes) {
  14027. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  14028. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  14029. }
  14030. }
  14031. };
  14032. InstancedMesh.prototype._generatePointsArray = function () {
  14033. return this._sourceMesh._generatePointsArray();
  14034. };
  14035. // Clone
  14036. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14037. var result = this._sourceMesh.createInstance(name);
  14038. // Deep copy
  14039. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  14040. // Bounding info
  14041. this.refreshBoundingInfo();
  14042. // Parent
  14043. if (newParent) {
  14044. result.parent = newParent;
  14045. }
  14046. if (!doNotCloneChildren) {
  14047. // Children
  14048. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14049. var mesh = this.getScene().meshes[index];
  14050. if (mesh.parent === this) {
  14051. mesh.clone(mesh.name, result);
  14052. }
  14053. }
  14054. }
  14055. result.computeWorldMatrix(true);
  14056. return result;
  14057. };
  14058. // Dispoe
  14059. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  14060. // Remove from mesh
  14061. var index = this._sourceMesh.instances.indexOf(this);
  14062. this._sourceMesh.instances.splice(index, 1);
  14063. _super.prototype.dispose.call(this, doNotRecurse);
  14064. };
  14065. return InstancedMesh;
  14066. })(BABYLON.AbstractMesh);
  14067. BABYLON.InstancedMesh = InstancedMesh;
  14068. })(BABYLON || (BABYLON = {}));
  14069. //# sourceMappingURL=babylon.instancedMesh.js.map
  14070. var BABYLON;
  14071. (function (BABYLON) {
  14072. var _InstancesBatch = (function () {
  14073. function _InstancesBatch() {
  14074. this.mustReturn = false;
  14075. this.visibleInstances = new Array();
  14076. this.renderSelf = new Array();
  14077. }
  14078. return _InstancesBatch;
  14079. })();
  14080. BABYLON._InstancesBatch = _InstancesBatch;
  14081. var Mesh = (function (_super) {
  14082. __extends(Mesh, _super);
  14083. /**
  14084. * @constructor
  14085. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  14086. * @param {Scene} scene - The scene to add this mesh to.
  14087. * @param {Node} parent - The parent of this mesh, if it has one
  14088. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  14089. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  14090. * When false, achieved by calling a clone(), also passing False.
  14091. * This will make creation of children, recursive.
  14092. */
  14093. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  14094. if (parent === void 0) { parent = null; }
  14095. _super.call(this, name, scene);
  14096. // Members
  14097. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  14098. this.instances = new Array();
  14099. this._LODLevels = new Array();
  14100. this._onBeforeRenderCallbacks = new Array();
  14101. this._onAfterRenderCallbacks = new Array();
  14102. this._visibleInstances = {};
  14103. this._renderIdForInstances = new Array();
  14104. this._batchCache = new _InstancesBatch();
  14105. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  14106. this._sideOrientation = Mesh._DEFAULTSIDE;
  14107. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  14108. if (source) {
  14109. // Geometry
  14110. if (source._geometry) {
  14111. source._geometry.applyToMesh(this);
  14112. }
  14113. // Deep copy
  14114. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], []);
  14115. // Material
  14116. this.material = source.material;
  14117. if (!doNotCloneChildren) {
  14118. // Children
  14119. for (var index = 0; index < scene.meshes.length; index++) {
  14120. var mesh = scene.meshes[index];
  14121. if (mesh.parent === source) {
  14122. // doNotCloneChildren is always going to be False
  14123. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  14124. }
  14125. }
  14126. }
  14127. // Particles
  14128. for (index = 0; index < scene.particleSystems.length; index++) {
  14129. var system = scene.particleSystems[index];
  14130. if (system.emitter === source) {
  14131. system.clone(system.name, this);
  14132. }
  14133. }
  14134. this.computeWorldMatrix(true);
  14135. }
  14136. // Parent
  14137. if (parent !== null) {
  14138. this.parent = parent;
  14139. }
  14140. }
  14141. Object.defineProperty(Mesh, "FRONTSIDE", {
  14142. get: function () {
  14143. return Mesh._FRONTSIDE;
  14144. },
  14145. enumerable: true,
  14146. configurable: true
  14147. });
  14148. Object.defineProperty(Mesh, "BACKSIDE", {
  14149. get: function () {
  14150. return Mesh._BACKSIDE;
  14151. },
  14152. enumerable: true,
  14153. configurable: true
  14154. });
  14155. Object.defineProperty(Mesh, "DOUBLESIDE", {
  14156. get: function () {
  14157. return Mesh._DOUBLESIDE;
  14158. },
  14159. enumerable: true,
  14160. configurable: true
  14161. });
  14162. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  14163. get: function () {
  14164. return Mesh._DEFAULTSIDE;
  14165. },
  14166. enumerable: true,
  14167. configurable: true
  14168. });
  14169. Object.defineProperty(Mesh, "NO_CAP", {
  14170. get: function () {
  14171. return Mesh._NO_CAP;
  14172. },
  14173. enumerable: true,
  14174. configurable: true
  14175. });
  14176. Object.defineProperty(Mesh, "CAP_START", {
  14177. get: function () {
  14178. return Mesh._CAP_START;
  14179. },
  14180. enumerable: true,
  14181. configurable: true
  14182. });
  14183. Object.defineProperty(Mesh, "CAP_END", {
  14184. get: function () {
  14185. return Mesh._CAP_END;
  14186. },
  14187. enumerable: true,
  14188. configurable: true
  14189. });
  14190. Object.defineProperty(Mesh, "CAP_ALL", {
  14191. get: function () {
  14192. return Mesh._CAP_ALL;
  14193. },
  14194. enumerable: true,
  14195. configurable: true
  14196. });
  14197. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  14198. // Methods
  14199. get: function () {
  14200. return this._LODLevels.length > 0;
  14201. },
  14202. enumerable: true,
  14203. configurable: true
  14204. });
  14205. Mesh.prototype._sortLODLevels = function () {
  14206. this._LODLevels.sort(function (a, b) {
  14207. if (a.distance < b.distance) {
  14208. return 1;
  14209. }
  14210. if (a.distance > b.distance) {
  14211. return -1;
  14212. }
  14213. return 0;
  14214. });
  14215. };
  14216. /**
  14217. * Add a mesh as LOD level triggered at the given distance.
  14218. * @param {number} distance - the distance from the center of the object to show this level
  14219. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  14220. * @return {BABYLON.Mesh} this mesh (for chaining)
  14221. */
  14222. Mesh.prototype.addLODLevel = function (distance, mesh) {
  14223. if (mesh && mesh._masterMesh) {
  14224. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  14225. return this;
  14226. }
  14227. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  14228. this._LODLevels.push(level);
  14229. if (mesh) {
  14230. mesh._masterMesh = this;
  14231. }
  14232. this._sortLODLevels();
  14233. return this;
  14234. };
  14235. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  14236. for (var index = 0; index < this._LODLevels.length; index++) {
  14237. var level = this._LODLevels[index];
  14238. if (level.distance === distance) {
  14239. return level.mesh;
  14240. }
  14241. }
  14242. return null;
  14243. };
  14244. /**
  14245. * Remove a mesh from the LOD array
  14246. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  14247. * @return {BABYLON.Mesh} this mesh (for chaining)
  14248. */
  14249. Mesh.prototype.removeLODLevel = function (mesh) {
  14250. for (var index = 0; index < this._LODLevels.length; index++) {
  14251. if (this._LODLevels[index].mesh === mesh) {
  14252. this._LODLevels.splice(index, 1);
  14253. if (mesh) {
  14254. mesh._masterMesh = null;
  14255. }
  14256. }
  14257. }
  14258. this._sortLODLevels();
  14259. return this;
  14260. };
  14261. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  14262. if (!this._LODLevels || this._LODLevels.length === 0) {
  14263. return this;
  14264. }
  14265. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  14266. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  14267. if (this.onLODLevelSelection) {
  14268. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  14269. }
  14270. return this;
  14271. }
  14272. for (var index = 0; index < this._LODLevels.length; index++) {
  14273. var level = this._LODLevels[index];
  14274. if (level.distance < distanceToCamera) {
  14275. if (level.mesh) {
  14276. level.mesh._preActivate();
  14277. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  14278. }
  14279. if (this.onLODLevelSelection) {
  14280. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  14281. }
  14282. return level.mesh;
  14283. }
  14284. }
  14285. if (this.onLODLevelSelection) {
  14286. this.onLODLevelSelection(distanceToCamera, this, this);
  14287. }
  14288. return this;
  14289. };
  14290. Object.defineProperty(Mesh.prototype, "geometry", {
  14291. get: function () {
  14292. return this._geometry;
  14293. },
  14294. enumerable: true,
  14295. configurable: true
  14296. });
  14297. Mesh.prototype.getTotalVertices = function () {
  14298. if (!this._geometry) {
  14299. return 0;
  14300. }
  14301. return this._geometry.getTotalVertices();
  14302. };
  14303. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  14304. if (!this._geometry) {
  14305. return null;
  14306. }
  14307. return this._geometry.getVerticesData(kind, copyWhenShared);
  14308. };
  14309. Mesh.prototype.getVertexBuffer = function (kind) {
  14310. if (!this._geometry) {
  14311. return undefined;
  14312. }
  14313. return this._geometry.getVertexBuffer(kind);
  14314. };
  14315. Mesh.prototype.isVerticesDataPresent = function (kind) {
  14316. if (!this._geometry) {
  14317. if (this._delayInfo) {
  14318. return this._delayInfo.indexOf(kind) !== -1;
  14319. }
  14320. return false;
  14321. }
  14322. return this._geometry.isVerticesDataPresent(kind);
  14323. };
  14324. Mesh.prototype.getVerticesDataKinds = function () {
  14325. if (!this._geometry) {
  14326. var result = [];
  14327. if (this._delayInfo) {
  14328. for (var kind in this._delayInfo) {
  14329. result.push(kind);
  14330. }
  14331. }
  14332. return result;
  14333. }
  14334. return this._geometry.getVerticesDataKinds();
  14335. };
  14336. Mesh.prototype.getTotalIndices = function () {
  14337. if (!this._geometry) {
  14338. return 0;
  14339. }
  14340. return this._geometry.getTotalIndices();
  14341. };
  14342. Mesh.prototype.getIndices = function (copyWhenShared) {
  14343. if (!this._geometry) {
  14344. return [];
  14345. }
  14346. return this._geometry.getIndices(copyWhenShared);
  14347. };
  14348. Object.defineProperty(Mesh.prototype, "isBlocked", {
  14349. get: function () {
  14350. return this._masterMesh !== null && this._masterMesh !== undefined;
  14351. },
  14352. enumerable: true,
  14353. configurable: true
  14354. });
  14355. Mesh.prototype.isReady = function () {
  14356. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14357. return false;
  14358. }
  14359. return _super.prototype.isReady.call(this);
  14360. };
  14361. Mesh.prototype.isDisposed = function () {
  14362. return this._isDisposed;
  14363. };
  14364. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  14365. get: function () {
  14366. return this._sideOrientation;
  14367. },
  14368. set: function (sideO) {
  14369. this._sideOrientation = sideO;
  14370. },
  14371. enumerable: true,
  14372. configurable: true
  14373. });
  14374. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  14375. get: function () {
  14376. return this._areNormalsFrozen;
  14377. },
  14378. enumerable: true,
  14379. configurable: true
  14380. });
  14381. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14382. Mesh.prototype.freezeNormals = function () {
  14383. this._areNormalsFrozen = true;
  14384. };
  14385. /** This function affects parametric shapes on update only : ribbons, tubes, etc. It has no effect at all on other shapes */
  14386. Mesh.prototype.unfreezeNormals = function () {
  14387. this._areNormalsFrozen = false;
  14388. };
  14389. // Methods
  14390. Mesh.prototype._preActivate = function () {
  14391. var sceneRenderId = this.getScene().getRenderId();
  14392. if (this._preActivateId === sceneRenderId) {
  14393. return;
  14394. }
  14395. this._preActivateId = sceneRenderId;
  14396. this._visibleInstances = null;
  14397. };
  14398. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  14399. if (!this._visibleInstances) {
  14400. this._visibleInstances = {};
  14401. this._visibleInstances.defaultRenderId = renderId;
  14402. this._visibleInstances.selfDefaultRenderId = this._renderId;
  14403. }
  14404. if (!this._visibleInstances[renderId]) {
  14405. this._visibleInstances[renderId] = new Array();
  14406. }
  14407. this._visibleInstances[renderId].push(instance);
  14408. };
  14409. Mesh.prototype.refreshBoundingInfo = function () {
  14410. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14411. if (data) {
  14412. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  14413. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  14414. }
  14415. if (this.subMeshes) {
  14416. for (var index = 0; index < this.subMeshes.length; index++) {
  14417. this.subMeshes[index].refreshBoundingInfo();
  14418. }
  14419. }
  14420. this._updateBoundingInfo();
  14421. };
  14422. Mesh.prototype._createGlobalSubMesh = function () {
  14423. var totalVertices = this.getTotalVertices();
  14424. if (!totalVertices || !this.getIndices()) {
  14425. return null;
  14426. }
  14427. this.releaseSubMeshes();
  14428. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  14429. };
  14430. Mesh.prototype.subdivide = function (count) {
  14431. if (count < 1) {
  14432. return;
  14433. }
  14434. var totalIndices = this.getTotalIndices();
  14435. var subdivisionSize = (totalIndices / count) | 0;
  14436. var offset = 0;
  14437. // Ensure that subdivisionSize is a multiple of 3
  14438. while (subdivisionSize % 3 !== 0) {
  14439. subdivisionSize++;
  14440. }
  14441. this.releaseSubMeshes();
  14442. for (var index = 0; index < count; index++) {
  14443. if (offset >= totalIndices) {
  14444. break;
  14445. }
  14446. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  14447. offset += subdivisionSize;
  14448. }
  14449. this.synchronizeInstances();
  14450. };
  14451. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  14452. if (kind instanceof Array) {
  14453. var temp = data;
  14454. data = kind;
  14455. kind = temp;
  14456. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  14457. }
  14458. if (!this._geometry) {
  14459. var vertexData = new BABYLON.VertexData();
  14460. vertexData.set(data, kind);
  14461. var scene = this.getScene();
  14462. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  14463. }
  14464. else {
  14465. this._geometry.setVerticesData(kind, data, updatable, stride);
  14466. }
  14467. };
  14468. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  14469. if (!this._geometry) {
  14470. return;
  14471. }
  14472. if (!makeItUnique) {
  14473. this._geometry.updateVerticesData(kind, data, updateExtends);
  14474. }
  14475. else {
  14476. this.makeGeometryUnique();
  14477. this.updateVerticesData(kind, data, updateExtends, false);
  14478. }
  14479. };
  14480. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  14481. if (!this._geometry) {
  14482. return;
  14483. }
  14484. if (!makeItUnique) {
  14485. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  14486. }
  14487. else {
  14488. this.makeGeometryUnique();
  14489. this.updateVerticesDataDirectly(kind, data, offset, false);
  14490. }
  14491. };
  14492. // Mesh positions update function :
  14493. // updates the mesh positions according to the positionFunction returned values.
  14494. // The positionFunction argument must be a javascript function accepting the mesh "positions" array as parameter.
  14495. // This dedicated positionFunction computes new mesh positions according to the given mesh type.
  14496. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  14497. if (computeNormals === void 0) { computeNormals = true; }
  14498. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14499. positionFunction(positions);
  14500. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  14501. if (computeNormals) {
  14502. var indices = this.getIndices();
  14503. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14504. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  14505. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  14506. }
  14507. };
  14508. Mesh.prototype.makeGeometryUnique = function () {
  14509. if (!this._geometry) {
  14510. return;
  14511. }
  14512. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  14513. geometry.applyToMesh(this);
  14514. };
  14515. Mesh.prototype.setIndices = function (indices, totalVertices) {
  14516. if (!this._geometry) {
  14517. var vertexData = new BABYLON.VertexData();
  14518. vertexData.indices = indices;
  14519. var scene = this.getScene();
  14520. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  14521. }
  14522. else {
  14523. this._geometry.setIndices(indices, totalVertices);
  14524. }
  14525. };
  14526. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  14527. var engine = this.getScene().getEngine();
  14528. // Wireframe
  14529. var indexToBind;
  14530. switch (fillMode) {
  14531. case BABYLON.Material.PointFillMode:
  14532. indexToBind = null;
  14533. break;
  14534. case BABYLON.Material.WireFrameFillMode:
  14535. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  14536. break;
  14537. default:
  14538. case BABYLON.Material.TriangleFillMode:
  14539. indexToBind = this._geometry.getIndexBuffer();
  14540. break;
  14541. }
  14542. // VBOs
  14543. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  14544. };
  14545. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  14546. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14547. return;
  14548. }
  14549. var engine = this.getScene().getEngine();
  14550. // Draw order
  14551. switch (fillMode) {
  14552. case BABYLON.Material.PointFillMode:
  14553. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  14554. break;
  14555. case BABYLON.Material.WireFrameFillMode:
  14556. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  14557. break;
  14558. default:
  14559. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  14560. }
  14561. };
  14562. Mesh.prototype.registerBeforeRender = function (func) {
  14563. this._onBeforeRenderCallbacks.push(func);
  14564. };
  14565. Mesh.prototype.unregisterBeforeRender = function (func) {
  14566. var index = this._onBeforeRenderCallbacks.indexOf(func);
  14567. if (index > -1) {
  14568. this._onBeforeRenderCallbacks.splice(index, 1);
  14569. }
  14570. };
  14571. Mesh.prototype.registerAfterRender = function (func) {
  14572. this._onAfterRenderCallbacks.push(func);
  14573. };
  14574. Mesh.prototype.unregisterAfterRender = function (func) {
  14575. var index = this._onAfterRenderCallbacks.indexOf(func);
  14576. if (index > -1) {
  14577. this._onAfterRenderCallbacks.splice(index, 1);
  14578. }
  14579. };
  14580. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  14581. var scene = this.getScene();
  14582. this._batchCache.mustReturn = false;
  14583. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  14584. this._batchCache.visibleInstances[subMeshId] = null;
  14585. if (this._visibleInstances) {
  14586. var currentRenderId = scene.getRenderId();
  14587. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  14588. var selfRenderId = this._renderId;
  14589. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  14590. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  14591. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  14592. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  14593. }
  14594. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  14595. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  14596. this._batchCache.mustReturn = true;
  14597. return this._batchCache;
  14598. }
  14599. if (currentRenderId !== selfRenderId) {
  14600. this._batchCache.renderSelf[subMeshId] = false;
  14601. }
  14602. }
  14603. this._renderIdForInstances[subMeshId] = currentRenderId;
  14604. }
  14605. return this._batchCache;
  14606. };
  14607. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  14608. var visibleInstances = batch.visibleInstances[subMesh._id];
  14609. var matricesCount = visibleInstances.length + 1;
  14610. var bufferSize = matricesCount * 16 * 4;
  14611. while (this._instancesBufferSize < bufferSize) {
  14612. this._instancesBufferSize *= 2;
  14613. }
  14614. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  14615. if (this._worldMatricesInstancesBuffer) {
  14616. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14617. }
  14618. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  14619. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  14620. }
  14621. var offset = 0;
  14622. var instancesCount = 0;
  14623. var world = this.getWorldMatrix();
  14624. if (batch.renderSelf[subMesh._id]) {
  14625. world.copyToArray(this._worldMatricesInstancesArray, offset);
  14626. offset += 16;
  14627. instancesCount++;
  14628. }
  14629. if (visibleInstances) {
  14630. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  14631. var instance = visibleInstances[instanceIndex];
  14632. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  14633. offset += 16;
  14634. instancesCount++;
  14635. }
  14636. }
  14637. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  14638. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  14639. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  14640. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  14641. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  14642. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  14643. this._draw(subMesh, fillMode, instancesCount);
  14644. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  14645. };
  14646. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  14647. var scene = this.getScene();
  14648. var engine = scene.getEngine();
  14649. if (hardwareInstancedRendering) {
  14650. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  14651. }
  14652. else {
  14653. if (batch.renderSelf[subMesh._id]) {
  14654. // Draw
  14655. if (onBeforeDraw) {
  14656. onBeforeDraw(false, this.getWorldMatrix());
  14657. }
  14658. this._draw(subMesh, fillMode);
  14659. }
  14660. if (batch.visibleInstances[subMesh._id]) {
  14661. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  14662. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  14663. // World
  14664. var world = instance.getWorldMatrix();
  14665. if (onBeforeDraw) {
  14666. onBeforeDraw(true, world);
  14667. }
  14668. // Draw
  14669. this._draw(subMesh, fillMode);
  14670. }
  14671. }
  14672. }
  14673. };
  14674. Mesh.prototype.render = function (subMesh) {
  14675. var scene = this.getScene();
  14676. // Managing instances
  14677. var batch = this._getInstancesRenderList(subMesh._id);
  14678. if (batch.mustReturn) {
  14679. return;
  14680. }
  14681. // Checking geometry state
  14682. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  14683. return;
  14684. }
  14685. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  14686. this._onBeforeRenderCallbacks[callbackIndex](this);
  14687. }
  14688. var engine = scene.getEngine();
  14689. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  14690. // Material
  14691. var effectiveMaterial = subMesh.getMaterial();
  14692. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  14693. return;
  14694. }
  14695. // Outline - step 1
  14696. var savedDepthWrite = engine.getDepthWrite();
  14697. if (this.renderOutline) {
  14698. engine.setDepthWrite(false);
  14699. scene.getOutlineRenderer().render(subMesh, batch);
  14700. engine.setDepthWrite(savedDepthWrite);
  14701. }
  14702. effectiveMaterial._preBind();
  14703. var effect = effectiveMaterial.getEffect();
  14704. // Bind
  14705. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  14706. this._bind(subMesh, effect, fillMode);
  14707. var world = this.getWorldMatrix();
  14708. effectiveMaterial.bind(world, this);
  14709. // Draw
  14710. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  14711. if (isInstance) {
  14712. effectiveMaterial.bindOnlyWorldMatrix(world);
  14713. }
  14714. });
  14715. // Unbind
  14716. effectiveMaterial.unbind();
  14717. // Outline - step 2
  14718. if (this.renderOutline && savedDepthWrite) {
  14719. engine.setDepthWrite(true);
  14720. engine.setColorWrite(false);
  14721. scene.getOutlineRenderer().render(subMesh, batch);
  14722. engine.setColorWrite(true);
  14723. }
  14724. // Overlay
  14725. if (this.renderOverlay) {
  14726. var currentMode = engine.getAlphaMode();
  14727. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14728. scene.getOutlineRenderer().render(subMesh, batch, true);
  14729. engine.setAlphaMode(currentMode);
  14730. }
  14731. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  14732. this._onAfterRenderCallbacks[callbackIndex](this);
  14733. }
  14734. };
  14735. Mesh.prototype.getEmittedParticleSystems = function () {
  14736. var results = new Array();
  14737. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14738. var particleSystem = this.getScene().particleSystems[index];
  14739. if (particleSystem.emitter === this) {
  14740. results.push(particleSystem);
  14741. }
  14742. }
  14743. return results;
  14744. };
  14745. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  14746. var results = new Array();
  14747. var descendants = this.getDescendants();
  14748. descendants.push(this);
  14749. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  14750. var particleSystem = this.getScene().particleSystems[index];
  14751. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  14752. results.push(particleSystem);
  14753. }
  14754. }
  14755. return results;
  14756. };
  14757. Mesh.prototype.getChildren = function () {
  14758. var results = [];
  14759. for (var index = 0; index < this.getScene().meshes.length; index++) {
  14760. var mesh = this.getScene().meshes[index];
  14761. if (mesh.parent === this) {
  14762. results.push(mesh);
  14763. }
  14764. }
  14765. return results;
  14766. };
  14767. Mesh.prototype._checkDelayState = function () {
  14768. var _this = this;
  14769. var that = this;
  14770. var scene = this.getScene();
  14771. if (this._geometry) {
  14772. this._geometry.load(scene);
  14773. }
  14774. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  14775. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  14776. scene._addPendingData(that);
  14777. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  14778. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  14779. if (data instanceof ArrayBuffer) {
  14780. _this._delayLoadingFunction(data, _this);
  14781. }
  14782. else {
  14783. _this._delayLoadingFunction(JSON.parse(data), _this);
  14784. }
  14785. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  14786. scene._removePendingData(_this);
  14787. }, function () { }, scene.database, getBinaryData);
  14788. }
  14789. };
  14790. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  14791. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  14792. return false;
  14793. }
  14794. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  14795. return false;
  14796. }
  14797. this._checkDelayState();
  14798. return true;
  14799. };
  14800. Mesh.prototype.setMaterialByID = function (id) {
  14801. var materials = this.getScene().materials;
  14802. for (var index = 0; index < materials.length; index++) {
  14803. if (materials[index].id === id) {
  14804. this.material = materials[index];
  14805. return;
  14806. }
  14807. }
  14808. // Multi
  14809. var multiMaterials = this.getScene().multiMaterials;
  14810. for (index = 0; index < multiMaterials.length; index++) {
  14811. if (multiMaterials[index].id === id) {
  14812. this.material = multiMaterials[index];
  14813. return;
  14814. }
  14815. }
  14816. };
  14817. Mesh.prototype.getAnimatables = function () {
  14818. var results = [];
  14819. if (this.material) {
  14820. results.push(this.material);
  14821. }
  14822. if (this.skeleton) {
  14823. results.push(this.skeleton);
  14824. }
  14825. return results;
  14826. };
  14827. // Geometry
  14828. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  14829. // Position
  14830. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  14831. return;
  14832. }
  14833. this._resetPointsArrayCache();
  14834. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14835. var temp = [];
  14836. for (var index = 0; index < data.length; index += 3) {
  14837. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  14838. }
  14839. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  14840. // Normals
  14841. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14842. return;
  14843. }
  14844. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14845. temp = [];
  14846. for (index = 0; index < data.length; index += 3) {
  14847. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  14848. }
  14849. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  14850. };
  14851. // Cache
  14852. Mesh.prototype._resetPointsArrayCache = function () {
  14853. this._positions = null;
  14854. };
  14855. Mesh.prototype._generatePointsArray = function () {
  14856. if (this._positions)
  14857. return true;
  14858. this._positions = [];
  14859. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14860. if (!data) {
  14861. return false;
  14862. }
  14863. for (var index = 0; index < data.length; index += 3) {
  14864. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  14865. }
  14866. return true;
  14867. };
  14868. // Clone
  14869. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  14870. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  14871. };
  14872. // Dispose
  14873. Mesh.prototype.dispose = function (doNotRecurse) {
  14874. if (this._geometry) {
  14875. this._geometry.releaseForMesh(this, true);
  14876. }
  14877. // Instances
  14878. if (this._worldMatricesInstancesBuffer) {
  14879. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  14880. this._worldMatricesInstancesBuffer = null;
  14881. }
  14882. while (this.instances.length) {
  14883. this.instances[0].dispose();
  14884. }
  14885. _super.prototype.dispose.call(this, doNotRecurse);
  14886. };
  14887. // Geometric tools
  14888. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  14889. var _this = this;
  14890. var scene = this.getScene();
  14891. var onload = function (img) {
  14892. // Getting height map data
  14893. var canvas = document.createElement("canvas");
  14894. var context = canvas.getContext("2d");
  14895. var heightMapWidth = img.width;
  14896. var heightMapHeight = img.height;
  14897. canvas.width = heightMapWidth;
  14898. canvas.height = heightMapHeight;
  14899. context.drawImage(img, 0, 0);
  14900. // Create VertexData from map data
  14901. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  14902. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  14903. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  14904. //execute success callback, if set
  14905. if (onSuccess) {
  14906. onSuccess(_this);
  14907. }
  14908. };
  14909. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  14910. };
  14911. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  14912. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  14913. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  14914. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14915. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  14916. return;
  14917. }
  14918. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  14919. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  14920. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  14921. var position = BABYLON.Vector3.Zero();
  14922. var normal = BABYLON.Vector3.Zero();
  14923. var uv = BABYLON.Vector2.Zero();
  14924. for (var index = 0; index < positions.length; index += 3) {
  14925. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  14926. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  14927. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  14928. // Compute height
  14929. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  14930. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  14931. var pos = (u + v * heightMapWidth) * 4;
  14932. var r = buffer[pos] / 255.0;
  14933. var g = buffer[pos + 1] / 255.0;
  14934. var b = buffer[pos + 2] / 255.0;
  14935. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  14936. normal.normalize();
  14937. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  14938. position = position.add(normal);
  14939. position.toArray(positions, index);
  14940. }
  14941. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  14942. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  14943. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  14944. };
  14945. Mesh.prototype.convertToFlatShadedMesh = function () {
  14946. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  14947. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  14948. var kinds = this.getVerticesDataKinds();
  14949. var vbs = [];
  14950. var data = [];
  14951. var newdata = [];
  14952. var updatableNormals = false;
  14953. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14954. var kind = kinds[kindIndex];
  14955. var vertexBuffer = this.getVertexBuffer(kind);
  14956. if (kind === BABYLON.VertexBuffer.NormalKind) {
  14957. updatableNormals = vertexBuffer.isUpdatable();
  14958. kinds.splice(kindIndex, 1);
  14959. kindIndex--;
  14960. continue;
  14961. }
  14962. vbs[kind] = vertexBuffer;
  14963. data[kind] = vbs[kind].getData();
  14964. newdata[kind] = [];
  14965. }
  14966. // Save previous submeshes
  14967. var previousSubmeshes = this.subMeshes.slice(0);
  14968. var indices = this.getIndices();
  14969. var totalIndices = this.getTotalIndices();
  14970. // Generating unique vertices per face
  14971. for (var index = 0; index < totalIndices; index++) {
  14972. var vertexIndex = indices[index];
  14973. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  14974. kind = kinds[kindIndex];
  14975. var stride = vbs[kind].getStrideSize();
  14976. for (var offset = 0; offset < stride; offset++) {
  14977. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  14978. }
  14979. }
  14980. }
  14981. // Updating faces & normal
  14982. var normals = [];
  14983. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  14984. for (index = 0; index < totalIndices; index += 3) {
  14985. indices[index] = index;
  14986. indices[index + 1] = index + 1;
  14987. indices[index + 2] = index + 2;
  14988. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  14989. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  14990. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  14991. var p1p2 = p1.subtract(p2);
  14992. var p3p2 = p3.subtract(p2);
  14993. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  14994. // Store same normals for every vertex
  14995. for (var localIndex = 0; localIndex < 3; localIndex++) {
  14996. normals.push(normal.x);
  14997. normals.push(normal.y);
  14998. normals.push(normal.z);
  14999. }
  15000. }
  15001. this.setIndices(indices);
  15002. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  15003. // Updating vertex buffers
  15004. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  15005. kind = kinds[kindIndex];
  15006. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  15007. }
  15008. // Updating submeshes
  15009. this.releaseSubMeshes();
  15010. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  15011. var previousOne = previousSubmeshes[submeshIndex];
  15012. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  15013. }
  15014. this.synchronizeInstances();
  15015. };
  15016. // Instances
  15017. Mesh.prototype.createInstance = function (name) {
  15018. return new BABYLON.InstancedMesh(name, this);
  15019. };
  15020. Mesh.prototype.synchronizeInstances = function () {
  15021. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  15022. var instance = this.instances[instanceIndex];
  15023. instance._syncSubMeshes();
  15024. }
  15025. };
  15026. /**
  15027. * Simplify the mesh according to the given array of settings.
  15028. * Function will return immediately and will simplify async.
  15029. * @param settings a collection of simplification settings.
  15030. * @param parallelProcessing should all levels calculate parallel or one after the other.
  15031. * @param type the type of simplification to run.
  15032. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  15033. */
  15034. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  15035. if (parallelProcessing === void 0) { parallelProcessing = true; }
  15036. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  15037. this.getScene().simplificationQueue.addTask({
  15038. settings: settings,
  15039. parallelProcessing: parallelProcessing,
  15040. mesh: this,
  15041. simplificationType: simplificationType,
  15042. successCallback: successCallback
  15043. });
  15044. };
  15045. /**
  15046. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  15047. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  15048. * This should be used together with the simplification to avoid disappearing triangles.
  15049. * @param successCallback an optional success callback to be called after the optimization finished.
  15050. */
  15051. Mesh.prototype.optimizeIndices = function (successCallback) {
  15052. var _this = this;
  15053. var indices = this.getIndices();
  15054. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15055. var vectorPositions = [];
  15056. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  15057. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  15058. }
  15059. var dupes = [];
  15060. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  15061. var realPos = vectorPositions.length - 1 - iteration;
  15062. var testedPosition = vectorPositions[realPos];
  15063. for (var j = 0; j < realPos; ++j) {
  15064. var againstPosition = vectorPositions[j];
  15065. if (testedPosition.equals(againstPosition)) {
  15066. dupes[realPos] = j;
  15067. break;
  15068. }
  15069. }
  15070. }, function () {
  15071. for (var i = 0; i < indices.length; ++i) {
  15072. indices[i] = dupes[indices[i]] || indices[i];
  15073. }
  15074. //indices are now reordered
  15075. var originalSubMeshes = _this.subMeshes.slice(0);
  15076. _this.setIndices(indices);
  15077. _this.subMeshes = originalSubMeshes;
  15078. if (successCallback) {
  15079. successCallback(_this);
  15080. }
  15081. });
  15082. };
  15083. // Statics
  15084. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, ribbonInstance) {
  15085. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15086. if (ribbonInstance === void 0) { ribbonInstance = null; }
  15087. if (ribbonInstance) {
  15088. // positionFunction : ribbon case
  15089. // only pathArray and sideOrientation parameters are taken into account for positions update
  15090. var positionFunction = function (positions) {
  15091. var minlg = pathArray[0].length;
  15092. var i = 0;
  15093. var ns = (ribbonInstance.sideOrientation === Mesh.DOUBLESIDE) ? 2 : 1;
  15094. for (var si = 1; si <= ns; si++) {
  15095. for (var p = 0; p < pathArray.length; p++) {
  15096. var path = pathArray[p];
  15097. var l = path.length;
  15098. minlg = (minlg < l) ? minlg : l;
  15099. var j = 0;
  15100. while (j < minlg) {
  15101. positions[i] = path[j].x;
  15102. positions[i + 1] = path[j].y;
  15103. positions[i + 2] = path[j].z;
  15104. j++;
  15105. i += 3;
  15106. }
  15107. }
  15108. }
  15109. };
  15110. var computeNormals = !(ribbonInstance.areNormalsFrozen);
  15111. ribbonInstance.updateMeshPositions(positionFunction, computeNormals);
  15112. return ribbonInstance;
  15113. }
  15114. else {
  15115. var ribbon = new Mesh(name, scene);
  15116. ribbon.sideOrientation = sideOrientation;
  15117. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  15118. vertexData.applyToMesh(ribbon, updatable);
  15119. return ribbon;
  15120. }
  15121. };
  15122. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  15123. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15124. var disc = new Mesh(name, scene);
  15125. var vertexData = BABYLON.VertexData.CreateDisc(radius, tessellation, sideOrientation);
  15126. vertexData.applyToMesh(disc, updatable);
  15127. return disc;
  15128. };
  15129. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  15130. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15131. var box = new Mesh(name, scene);
  15132. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  15133. vertexData.applyToMesh(box, updatable);
  15134. return box;
  15135. };
  15136. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  15137. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15138. var sphere = new Mesh(name, scene);
  15139. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  15140. vertexData.applyToMesh(sphere, updatable);
  15141. return sphere;
  15142. };
  15143. // Cylinder and cone (Code inspired by SharpDX.org)
  15144. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  15145. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15146. // subdivisions is a new parameter, we need to support old signature
  15147. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  15148. if (scene !== undefined) {
  15149. updatable = scene;
  15150. }
  15151. scene = subdivisions;
  15152. subdivisions = 1;
  15153. }
  15154. var cylinder = new Mesh(name, scene);
  15155. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  15156. vertexData.applyToMesh(cylinder, updatable);
  15157. return cylinder;
  15158. };
  15159. // Torus (Code from SharpDX.org)
  15160. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  15161. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15162. var torus = new Mesh(name, scene);
  15163. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  15164. vertexData.applyToMesh(torus, updatable);
  15165. return torus;
  15166. };
  15167. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  15168. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15169. var torusKnot = new Mesh(name, scene);
  15170. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  15171. vertexData.applyToMesh(torusKnot, updatable);
  15172. return torusKnot;
  15173. };
  15174. // Lines
  15175. Mesh.CreateLines = function (name, points, scene, updatable, linesInstance) {
  15176. if (linesInstance === void 0) { linesInstance = null; }
  15177. if (linesInstance) {
  15178. var positionFunction = function (positions) {
  15179. var i = 0;
  15180. for (var p = 0; p < points.length; p++) {
  15181. positions[i] = points[p].x;
  15182. positions[i + 1] = points[p].y;
  15183. positions[i + 2] = points[p].z;
  15184. i += 3;
  15185. }
  15186. };
  15187. linesInstance.updateMeshPositions(positionFunction, false);
  15188. return linesInstance;
  15189. }
  15190. // lines creation
  15191. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  15192. var vertexData = BABYLON.VertexData.CreateLines(points);
  15193. vertexData.applyToMesh(lines, updatable);
  15194. return lines;
  15195. };
  15196. // Dashed Lines
  15197. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, linesInstance) {
  15198. if (linesInstance === void 0) { linesInstance = null; }
  15199. if (linesInstance) {
  15200. var positionFunction = function (positions) {
  15201. var curvect = BABYLON.Vector3.Zero();
  15202. var nbSeg = positions.length / 6;
  15203. var lg = 0;
  15204. var nb = 0;
  15205. var shft = 0;
  15206. var dashshft = 0;
  15207. var curshft = 0;
  15208. var p = 0;
  15209. var i = 0;
  15210. var j = 0;
  15211. for (i = 0; i < points.length - 1; i++) {
  15212. points[i + 1].subtractToRef(points[i], curvect);
  15213. lg += curvect.length();
  15214. }
  15215. shft = lg / nbSeg;
  15216. dashshft = linesInstance.dashSize * shft / (linesInstance.dashSize + linesInstance.gapSize);
  15217. for (i = 0; i < points.length - 1; i++) {
  15218. points[i + 1].subtractToRef(points[i], curvect);
  15219. nb = Math.floor(curvect.length() / shft);
  15220. curvect.normalize();
  15221. j = 0;
  15222. while (j < nb && p < positions.length) {
  15223. curshft = shft * j;
  15224. positions[p] = points[i].x + curshft * curvect.x;
  15225. positions[p + 1] = points[i].y + curshft * curvect.y;
  15226. positions[p + 2] = points[i].z + curshft * curvect.z;
  15227. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  15228. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  15229. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  15230. p += 6;
  15231. j++;
  15232. }
  15233. }
  15234. while (p < positions.length) {
  15235. positions[p] = points[i].x;
  15236. positions[p + 1] = points[i].y;
  15237. positions[p + 2] = points[i].z;
  15238. p += 3;
  15239. }
  15240. };
  15241. linesInstance.updateMeshPositions(positionFunction, false);
  15242. return linesInstance;
  15243. }
  15244. // dashed lines creation
  15245. var dashedLines = new BABYLON.LinesMesh(name, scene, updatable);
  15246. var vertexData = BABYLON.VertexData.CreateDashedLines(points, dashSize, gapSize, dashNb);
  15247. vertexData.applyToMesh(dashedLines, updatable);
  15248. dashedLines.dashSize = dashSize;
  15249. dashedLines.gapSize = gapSize;
  15250. return dashedLines;
  15251. };
  15252. // Extrusion
  15253. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15254. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15255. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15256. scale = scale || 1;
  15257. rotation = rotation || 0;
  15258. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, extrudedInstance);
  15259. return extruded;
  15260. };
  15261. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, extrudedInstance) {
  15262. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15263. if (extrudedInstance === void 0) { extrudedInstance = null; }
  15264. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, extrudedInstance);
  15265. return extrudedCustom;
  15266. };
  15267. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance) {
  15268. // extrusion geometry
  15269. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  15270. var tangents = path3D.getTangents();
  15271. var normals = path3D.getNormals();
  15272. var binormals = path3D.getBinormals();
  15273. var distances = path3D.getDistances();
  15274. var angle = 0;
  15275. var returnScale = function (i, distance) { return scale; };
  15276. var returnRotation = function (i, distance) { return rotation; };
  15277. var rotate = custom ? rotateFunction : returnRotation;
  15278. var scl = custom ? scaleFunction : returnScale;
  15279. var index = 0;
  15280. for (var i = 0; i < curve.length; i++) {
  15281. var shapePath = new Array();
  15282. var angleStep = rotate(i, distances[i]);
  15283. var scaleRatio = scl(i, distances[i]);
  15284. for (var p = 0; p < shape.length; p++) {
  15285. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  15286. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  15287. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  15288. shapePath.push(rotated);
  15289. }
  15290. shapePaths[index] = shapePath;
  15291. angle += angleStep;
  15292. index++;
  15293. }
  15294. // cap
  15295. var capPath = function (shapePath) {
  15296. var pointCap = Array();
  15297. var barycenter = BABYLON.Vector3.Zero();
  15298. var i;
  15299. for (i = 0; i < shapePath.length; i++) {
  15300. barycenter.addInPlace(shapePath[i]);
  15301. }
  15302. barycenter.scaleInPlace(1 / shapePath.length);
  15303. for (i = 0; i < shapePath.length; i++) {
  15304. pointCap.push(barycenter);
  15305. }
  15306. return pointCap;
  15307. };
  15308. switch (cap) {
  15309. case Mesh.NO_CAP:
  15310. break;
  15311. case Mesh.CAP_START:
  15312. shapePaths.unshift(capPath(shapePaths[0]));
  15313. break;
  15314. case Mesh.CAP_END:
  15315. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15316. break;
  15317. case Mesh.CAP_ALL:
  15318. shapePaths.unshift(capPath(shapePaths[0]));
  15319. shapePaths.push(capPath(shapePaths[shapePaths.length - 1]));
  15320. break;
  15321. default:
  15322. break;
  15323. }
  15324. return shapePaths;
  15325. };
  15326. if (instance) {
  15327. var path3D = (instance.path3D).update(curve);
  15328. var pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  15329. instance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, instance);
  15330. return instance;
  15331. }
  15332. // extruded shape creation
  15333. var path3D = new BABYLON.Path3D(curve);
  15334. var newShapePaths = new Array();
  15335. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15336. var pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  15337. var extrudedGeneric = Mesh.CreateRibbon(name, pathArray, rbCA, rbCP, 0, scene, updtbl, side);
  15338. extrudedGeneric.pathArray = pathArray;
  15339. extrudedGeneric.path3D = path3D;
  15340. extrudedGeneric.cap = cap;
  15341. return extrudedGeneric;
  15342. };
  15343. // Lathe
  15344. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  15345. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15346. radius = radius || 1;
  15347. tessellation = tessellation || radius * 60;
  15348. var pi2 = Math.PI * 2;
  15349. var Y = BABYLON.Axis.Y;
  15350. var shapeLathe = new Array();
  15351. // first rotatable point
  15352. var i = 0;
  15353. while (shape[i].x === 0) {
  15354. i++;
  15355. }
  15356. var pt = shape[i];
  15357. for (i = 0; i < shape.length; i++) {
  15358. shapeLathe.push(shape[i].subtract(pt));
  15359. }
  15360. // circle path
  15361. var step = pi2 / tessellation;
  15362. var rotated;
  15363. var path = new Array();
  15364. ;
  15365. for (i = 0; i < tessellation; i++) {
  15366. rotated = new BABYLON.Vector3(Math.cos(i * step) * radius, 0, Math.sin(i * step) * radius);
  15367. path.push(rotated);
  15368. }
  15369. path.push(path[0]);
  15370. // extrusion
  15371. var scaleFunction = function () { return 1; };
  15372. var rotateFunction = function () { return 0; };
  15373. var lathe = Mesh.ExtrudeShapeCustom(name, shapeLathe, path, scaleFunction, rotateFunction, true, false, Mesh.NO_CAP, scene, updatable, sideOrientation);
  15374. return lathe;
  15375. };
  15376. // Plane & ground
  15377. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  15378. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15379. var plane = new Mesh(name, scene);
  15380. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  15381. vertexData.applyToMesh(plane, updatable);
  15382. return plane;
  15383. };
  15384. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  15385. var ground = new BABYLON.GroundMesh(name, scene);
  15386. ground._setReady(false);
  15387. ground._subdivisions = subdivisions;
  15388. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  15389. vertexData.applyToMesh(ground, updatable);
  15390. ground._setReady(true);
  15391. return ground;
  15392. };
  15393. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  15394. var tiledGround = new Mesh(name, scene);
  15395. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  15396. vertexData.applyToMesh(tiledGround, updatable);
  15397. return tiledGround;
  15398. };
  15399. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  15400. var ground = new BABYLON.GroundMesh(name, scene);
  15401. ground._subdivisions = subdivisions;
  15402. ground._setReady(false);
  15403. var onload = function (img) {
  15404. // Getting height map data
  15405. var canvas = document.createElement("canvas");
  15406. var context = canvas.getContext("2d");
  15407. var heightMapWidth = img.width;
  15408. var heightMapHeight = img.height;
  15409. canvas.width = heightMapWidth;
  15410. canvas.height = heightMapHeight;
  15411. context.drawImage(img, 0, 0);
  15412. // Create VertexData from map data
  15413. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  15414. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  15415. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  15416. vertexData.applyToMesh(ground, updatable);
  15417. ground._setReady(true);
  15418. //execute ready callback, if set
  15419. if (onReady) {
  15420. onReady(ground);
  15421. }
  15422. };
  15423. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  15424. return ground;
  15425. };
  15426. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, tubeInstance) {
  15427. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  15428. if (tubeInstance === void 0) { tubeInstance = null; }
  15429. // tube geometry
  15430. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap) {
  15431. var tangents = path3D.getTangents();
  15432. var normals = path3D.getNormals();
  15433. var distances = path3D.getDistances();
  15434. var pi2 = Math.PI * 2;
  15435. var step = pi2 / tessellation;
  15436. var returnRadius = function (i, distance) { return radius; };
  15437. var radiusFunctionFinal = radiusFunction || returnRadius;
  15438. var circlePath;
  15439. var rad;
  15440. var normal;
  15441. var rotated;
  15442. var rotationMatrix;
  15443. var index = 0;
  15444. for (var i = 0; i < path.length; i++) {
  15445. rad = radiusFunctionFinal(i, distances[i]); // current radius
  15446. circlePath = Array(); // current circle array
  15447. normal = normals[i]; // current normal
  15448. for (var t = 0; t < tessellation; t++) {
  15449. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], step * t);
  15450. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  15451. circlePath.push(rotated);
  15452. }
  15453. circlePath.push(circlePath[0]);
  15454. circlePaths[index] = circlePath;
  15455. index++;
  15456. }
  15457. // cap
  15458. var capPath = function (nbPoints, pathIndex) {
  15459. var pointCap = Array();
  15460. for (var i = 0; i < nbPoints; i++) {
  15461. pointCap.push(path[pathIndex]);
  15462. }
  15463. return pointCap;
  15464. };
  15465. switch (cap) {
  15466. case Mesh.NO_CAP:
  15467. break;
  15468. case Mesh.CAP_START:
  15469. circlePaths.unshift(capPath(tessellation + 1, 0));
  15470. break;
  15471. case Mesh.CAP_END:
  15472. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  15473. break;
  15474. case Mesh.CAP_ALL:
  15475. circlePaths.unshift(capPath(tessellation + 1, 0));
  15476. circlePaths.push(capPath(tessellation + 1, path.length - 1));
  15477. break;
  15478. default:
  15479. break;
  15480. }
  15481. return circlePaths;
  15482. };
  15483. if (tubeInstance) {
  15484. var path3D = (tubeInstance.path3D).update(path);
  15485. var pathArray = tubePathArray(path, path3D, tubeInstance.pathArray, radius, tubeInstance.tessellation, radiusFunction, tubeInstance.cap);
  15486. tubeInstance = Mesh.CreateRibbon(null, pathArray, null, null, null, null, null, null, tubeInstance);
  15487. return tubeInstance;
  15488. }
  15489. // tube creation
  15490. var path3D = new BABYLON.Path3D(path);
  15491. var newPathArray = new Array();
  15492. cap = (cap < 0 || cap > 3) ? 0 : cap;
  15493. var pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap);
  15494. var tube = Mesh.CreateRibbon(name, pathArray, false, true, 0, scene, updatable, sideOrientation);
  15495. tube.pathArray = pathArray;
  15496. tube.path3D = path3D;
  15497. tube.tessellation = tessellation;
  15498. tube.cap = cap;
  15499. return tube;
  15500. };
  15501. // Decals
  15502. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  15503. if (angle === void 0) { angle = 0; }
  15504. var indices = sourceMesh.getIndices();
  15505. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15506. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  15507. // Getting correct rotation
  15508. if (!normal) {
  15509. var target = new BABYLON.Vector3(0, 0, 1);
  15510. var camera = sourceMesh.getScene().activeCamera;
  15511. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  15512. normal = camera.globalPosition.subtract(cameraWorldTarget);
  15513. }
  15514. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  15515. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  15516. var pitch = Math.atan2(normal.y, len);
  15517. // Matrix
  15518. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  15519. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  15520. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  15521. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  15522. var vertexData = new BABYLON.VertexData();
  15523. vertexData.indices = [];
  15524. vertexData.positions = [];
  15525. vertexData.normals = [];
  15526. vertexData.uvs = [];
  15527. var currentVertexDataIndex = 0;
  15528. var extractDecalVector3 = function (indexId) {
  15529. var vertexId = indices[indexId];
  15530. var result = new BABYLON.PositionNormalVertex();
  15531. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  15532. // Send vector to decal local world
  15533. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  15534. // Get normal
  15535. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  15536. return result;
  15537. };
  15538. // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  15539. var clip = function (vertices, axis) {
  15540. if (vertices.length === 0) {
  15541. return vertices;
  15542. }
  15543. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  15544. var clipVertices = function (v0, v1) {
  15545. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  15546. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  15547. };
  15548. var result = new Array();
  15549. for (var index = 0; index < vertices.length; index += 3) {
  15550. var v1Out;
  15551. var v2Out;
  15552. var v3Out;
  15553. var total = 0;
  15554. var nV1, nV2, nV3, nV4;
  15555. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  15556. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  15557. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  15558. v1Out = d1 > 0;
  15559. v2Out = d2 > 0;
  15560. v3Out = d3 > 0;
  15561. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  15562. switch (total) {
  15563. case 0:
  15564. result.push(vertices[index]);
  15565. result.push(vertices[index + 1]);
  15566. result.push(vertices[index + 2]);
  15567. break;
  15568. case 1:
  15569. if (v1Out) {
  15570. nV1 = vertices[index + 1];
  15571. nV2 = vertices[index + 2];
  15572. nV3 = clipVertices(vertices[index], nV1);
  15573. nV4 = clipVertices(vertices[index], nV2);
  15574. }
  15575. if (v2Out) {
  15576. nV1 = vertices[index];
  15577. nV2 = vertices[index + 2];
  15578. nV3 = clipVertices(vertices[index + 1], nV1);
  15579. nV4 = clipVertices(vertices[index + 1], nV2);
  15580. result.push(nV3);
  15581. result.push(nV2.clone());
  15582. result.push(nV1.clone());
  15583. result.push(nV2.clone());
  15584. result.push(nV3.clone());
  15585. result.push(nV4);
  15586. break;
  15587. }
  15588. if (v3Out) {
  15589. nV1 = vertices[index];
  15590. nV2 = vertices[index + 1];
  15591. nV3 = clipVertices(vertices[index + 2], nV1);
  15592. nV4 = clipVertices(vertices[index + 2], nV2);
  15593. }
  15594. result.push(nV1.clone());
  15595. result.push(nV2.clone());
  15596. result.push(nV3);
  15597. result.push(nV4);
  15598. result.push(nV3.clone());
  15599. result.push(nV2.clone());
  15600. break;
  15601. case 2:
  15602. if (!v1Out) {
  15603. nV1 = vertices[index].clone();
  15604. nV2 = clipVertices(nV1, vertices[index + 1]);
  15605. nV3 = clipVertices(nV1, vertices[index + 2]);
  15606. result.push(nV1);
  15607. result.push(nV2);
  15608. result.push(nV3);
  15609. }
  15610. if (!v2Out) {
  15611. nV1 = vertices[index + 1].clone();
  15612. nV2 = clipVertices(nV1, vertices[index + 2]);
  15613. nV3 = clipVertices(nV1, vertices[index]);
  15614. result.push(nV1);
  15615. result.push(nV2);
  15616. result.push(nV3);
  15617. }
  15618. if (!v3Out) {
  15619. nV1 = vertices[index + 2].clone();
  15620. nV2 = clipVertices(nV1, vertices[index]);
  15621. nV3 = clipVertices(nV1, vertices[index + 1]);
  15622. result.push(nV1);
  15623. result.push(nV2);
  15624. result.push(nV3);
  15625. }
  15626. break;
  15627. case 3:
  15628. break;
  15629. }
  15630. }
  15631. return result;
  15632. };
  15633. for (var index = 0; index < indices.length; index += 3) {
  15634. var faceVertices = new Array();
  15635. faceVertices.push(extractDecalVector3(index));
  15636. faceVertices.push(extractDecalVector3(index + 1));
  15637. faceVertices.push(extractDecalVector3(index + 2));
  15638. // Clip
  15639. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  15640. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  15641. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  15642. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  15643. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  15644. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  15645. if (faceVertices.length === 0) {
  15646. continue;
  15647. }
  15648. // Add UVs and get back to world
  15649. var localRotationMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle);
  15650. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  15651. var vertex = faceVertices[vIndex];
  15652. vertexData.indices.push(currentVertexDataIndex);
  15653. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  15654. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  15655. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  15656. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  15657. currentVertexDataIndex++;
  15658. }
  15659. }
  15660. // Return mesh
  15661. var decal = new Mesh(name, sourceMesh.getScene());
  15662. vertexData.applyToMesh(decal);
  15663. decal.position = position.clone();
  15664. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  15665. return decal;
  15666. };
  15667. // Tools
  15668. Mesh.MinMax = function (meshes) {
  15669. var minVector = null;
  15670. var maxVector = null;
  15671. for (var i in meshes) {
  15672. var mesh = meshes[i];
  15673. var boundingBox = mesh.getBoundingInfo().boundingBox;
  15674. if (!minVector) {
  15675. minVector = boundingBox.minimumWorld;
  15676. maxVector = boundingBox.maximumWorld;
  15677. continue;
  15678. }
  15679. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  15680. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  15681. }
  15682. return {
  15683. min: minVector,
  15684. max: maxVector
  15685. };
  15686. };
  15687. Mesh.Center = function (meshesOrMinMaxVector) {
  15688. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  15689. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  15690. };
  15691. /**
  15692. * Merge the array of meshes into a single mesh for performance reasons.
  15693. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  15694. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  15695. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  15696. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  15697. */
  15698. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  15699. if (disposeSource === void 0) { disposeSource = true; }
  15700. if (!allow32BitsIndices) {
  15701. var totalVertices = 0;
  15702. // Counting vertices
  15703. for (var index = 0; index < meshes.length; index++) {
  15704. if (meshes[index]) {
  15705. totalVertices += meshes[index].getTotalVertices();
  15706. if (totalVertices > 65536) {
  15707. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  15708. return null;
  15709. }
  15710. }
  15711. }
  15712. }
  15713. // Merge
  15714. var vertexData;
  15715. var otherVertexData;
  15716. var source;
  15717. for (index = 0; index < meshes.length; index++) {
  15718. if (meshes[index]) {
  15719. meshes[index].computeWorldMatrix(true);
  15720. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  15721. otherVertexData.transform(meshes[index].getWorldMatrix());
  15722. if (vertexData) {
  15723. vertexData.merge(otherVertexData);
  15724. }
  15725. else {
  15726. vertexData = otherVertexData;
  15727. source = meshes[index];
  15728. }
  15729. }
  15730. }
  15731. if (!meshSubclass) {
  15732. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  15733. }
  15734. vertexData.applyToMesh(meshSubclass);
  15735. // Setting properties
  15736. meshSubclass.material = source.material;
  15737. meshSubclass.checkCollisions = source.checkCollisions;
  15738. // Cleaning
  15739. if (disposeSource) {
  15740. for (index = 0; index < meshes.length; index++) {
  15741. if (meshes[index]) {
  15742. meshes[index].dispose();
  15743. }
  15744. }
  15745. }
  15746. return meshSubclass;
  15747. };
  15748. // Consts
  15749. Mesh._FRONTSIDE = 0;
  15750. Mesh._BACKSIDE = 1;
  15751. Mesh._DOUBLESIDE = 2;
  15752. Mesh._DEFAULTSIDE = 0;
  15753. Mesh._NO_CAP = 0;
  15754. Mesh._CAP_START = 1;
  15755. Mesh._CAP_END = 2;
  15756. Mesh._CAP_ALL = 3;
  15757. return Mesh;
  15758. })(BABYLON.AbstractMesh);
  15759. BABYLON.Mesh = Mesh;
  15760. })(BABYLON || (BABYLON = {}));
  15761. //# sourceMappingURL=babylon.mesh.js.map
  15762. var BABYLON;
  15763. (function (BABYLON) {
  15764. var SubMesh = (function () {
  15765. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  15766. if (createBoundingBox === void 0) { createBoundingBox = true; }
  15767. this.materialIndex = materialIndex;
  15768. this.verticesStart = verticesStart;
  15769. this.verticesCount = verticesCount;
  15770. this.indexStart = indexStart;
  15771. this.indexCount = indexCount;
  15772. this._renderId = 0;
  15773. this._mesh = mesh;
  15774. this._renderingMesh = renderingMesh || mesh;
  15775. mesh.subMeshes.push(this);
  15776. this._trianglePlanes = [];
  15777. this._id = mesh.subMeshes.length - 1;
  15778. if (createBoundingBox) {
  15779. this.refreshBoundingInfo();
  15780. mesh.computeWorldMatrix(true);
  15781. }
  15782. }
  15783. SubMesh.prototype.getBoundingInfo = function () {
  15784. return this._boundingInfo;
  15785. };
  15786. SubMesh.prototype.getMesh = function () {
  15787. return this._mesh;
  15788. };
  15789. SubMesh.prototype.getRenderingMesh = function () {
  15790. return this._renderingMesh;
  15791. };
  15792. SubMesh.prototype.getMaterial = function () {
  15793. var rootMaterial = this._renderingMesh.material;
  15794. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  15795. var multiMaterial = rootMaterial;
  15796. return multiMaterial.getSubMaterial(this.materialIndex);
  15797. }
  15798. if (!rootMaterial) {
  15799. return this._mesh.getScene().defaultMaterial;
  15800. }
  15801. return rootMaterial;
  15802. };
  15803. // Methods
  15804. SubMesh.prototype.refreshBoundingInfo = function () {
  15805. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  15806. if (!data) {
  15807. this._boundingInfo = this._mesh._boundingInfo;
  15808. return;
  15809. }
  15810. var indices = this._renderingMesh.getIndices();
  15811. var extend;
  15812. if (this.indexStart === 0 && this.indexCount === indices.length) {
  15813. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  15814. }
  15815. else {
  15816. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  15817. }
  15818. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  15819. };
  15820. SubMesh.prototype._checkCollision = function (collider) {
  15821. return this._boundingInfo._checkCollision(collider);
  15822. };
  15823. SubMesh.prototype.updateBoundingInfo = function (world) {
  15824. if (!this._boundingInfo) {
  15825. this.refreshBoundingInfo();
  15826. }
  15827. this._boundingInfo._update(world);
  15828. };
  15829. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  15830. return this._boundingInfo.isInFrustum(frustumPlanes);
  15831. };
  15832. SubMesh.prototype.render = function () {
  15833. this._renderingMesh.render(this);
  15834. };
  15835. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  15836. if (!this._linesIndexBuffer) {
  15837. var linesIndices = [];
  15838. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15839. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  15840. }
  15841. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  15842. this.linesIndexCount = linesIndices.length;
  15843. }
  15844. return this._linesIndexBuffer;
  15845. };
  15846. SubMesh.prototype.canIntersects = function (ray) {
  15847. return ray.intersectsBox(this._boundingInfo.boundingBox);
  15848. };
  15849. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  15850. var intersectInfo = null;
  15851. // Triangles test
  15852. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  15853. var p0 = positions[indices[index]];
  15854. var p1 = positions[indices[index + 1]];
  15855. var p2 = positions[indices[index + 2]];
  15856. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  15857. if (currentIntersectInfo) {
  15858. if (currentIntersectInfo.distance < 0) {
  15859. continue;
  15860. }
  15861. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  15862. intersectInfo = currentIntersectInfo;
  15863. intersectInfo.faceId = index / 3;
  15864. if (fastCheck) {
  15865. break;
  15866. }
  15867. }
  15868. }
  15869. }
  15870. return intersectInfo;
  15871. };
  15872. // Clone
  15873. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  15874. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  15875. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  15876. return result;
  15877. };
  15878. // Dispose
  15879. SubMesh.prototype.dispose = function () {
  15880. if (this._linesIndexBuffer) {
  15881. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  15882. this._linesIndexBuffer = null;
  15883. }
  15884. // Remove from mesh
  15885. var index = this._mesh.subMeshes.indexOf(this);
  15886. this._mesh.subMeshes.splice(index, 1);
  15887. };
  15888. // Statics
  15889. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  15890. var minVertexIndex = Number.MAX_VALUE;
  15891. var maxVertexIndex = -Number.MAX_VALUE;
  15892. renderingMesh = renderingMesh || mesh;
  15893. var indices = renderingMesh.getIndices();
  15894. for (var index = startIndex; index < startIndex + indexCount; index++) {
  15895. var vertexIndex = indices[index];
  15896. if (vertexIndex < minVertexIndex)
  15897. minVertexIndex = vertexIndex;
  15898. if (vertexIndex > maxVertexIndex)
  15899. maxVertexIndex = vertexIndex;
  15900. }
  15901. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  15902. };
  15903. return SubMesh;
  15904. })();
  15905. BABYLON.SubMesh = SubMesh;
  15906. })(BABYLON || (BABYLON = {}));
  15907. //# sourceMappingURL=babylon.subMesh.js.map
  15908. var BABYLON;
  15909. (function (BABYLON) {
  15910. var BaseTexture = (function () {
  15911. function BaseTexture(scene) {
  15912. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  15913. this.hasAlpha = false;
  15914. this.getAlphaFromRGB = false;
  15915. this.level = 1;
  15916. this.isCube = false;
  15917. this.isRenderTarget = false;
  15918. this.animations = new Array();
  15919. this.coordinatesIndex = 0;
  15920. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  15921. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  15922. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  15923. this.anisotropicFilteringLevel = 4;
  15924. this._scene = scene;
  15925. this._scene.textures.push(this);
  15926. }
  15927. BaseTexture.prototype.getScene = function () {
  15928. return this._scene;
  15929. };
  15930. BaseTexture.prototype.getTextureMatrix = function () {
  15931. return null;
  15932. };
  15933. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  15934. return null;
  15935. };
  15936. BaseTexture.prototype.getInternalTexture = function () {
  15937. return this._texture;
  15938. };
  15939. BaseTexture.prototype.isReady = function () {
  15940. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  15941. return true;
  15942. }
  15943. if (this._texture) {
  15944. return this._texture.isReady;
  15945. }
  15946. return false;
  15947. };
  15948. BaseTexture.prototype.getSize = function () {
  15949. if (this._texture._width) {
  15950. return { width: this._texture._width, height: this._texture._height };
  15951. }
  15952. if (this._texture._size) {
  15953. return { width: this._texture._size, height: this._texture._size };
  15954. }
  15955. return { width: 0, height: 0 };
  15956. };
  15957. BaseTexture.prototype.getBaseSize = function () {
  15958. if (!this.isReady())
  15959. return { width: 0, height: 0 };
  15960. if (this._texture._size) {
  15961. return { width: this._texture._size, height: this._texture._size };
  15962. }
  15963. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  15964. };
  15965. BaseTexture.prototype.scale = function (ratio) {
  15966. };
  15967. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  15968. get: function () {
  15969. return false;
  15970. },
  15971. enumerable: true,
  15972. configurable: true
  15973. });
  15974. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  15975. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  15976. for (var index = 0; index < texturesCache.length; index++) {
  15977. var texturesCacheEntry = texturesCache[index];
  15978. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  15979. texturesCache.splice(index, 1);
  15980. return;
  15981. }
  15982. }
  15983. };
  15984. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  15985. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  15986. for (var index = 0; index < texturesCache.length; index++) {
  15987. var texturesCacheEntry = texturesCache[index];
  15988. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  15989. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  15990. texturesCacheEntry.references++;
  15991. return texturesCacheEntry;
  15992. }
  15993. }
  15994. }
  15995. return null;
  15996. };
  15997. BaseTexture.prototype.delayLoad = function () {
  15998. };
  15999. BaseTexture.prototype.releaseInternalTexture = function () {
  16000. if (!this._texture) {
  16001. return;
  16002. }
  16003. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  16004. this._texture.references--;
  16005. // Final reference ?
  16006. if (this._texture.references === 0) {
  16007. var index = texturesCache.indexOf(this._texture);
  16008. texturesCache.splice(index, 1);
  16009. this._scene.getEngine()._releaseTexture(this._texture);
  16010. delete this._texture;
  16011. }
  16012. };
  16013. BaseTexture.prototype.clone = function () {
  16014. return null;
  16015. };
  16016. BaseTexture.prototype.dispose = function () {
  16017. // Remove from scene
  16018. var index = this._scene.textures.indexOf(this);
  16019. if (index >= 0) {
  16020. this._scene.textures.splice(index, 1);
  16021. }
  16022. if (this._texture === undefined) {
  16023. return;
  16024. }
  16025. this.releaseInternalTexture();
  16026. // Callback
  16027. if (this.onDispose) {
  16028. this.onDispose();
  16029. }
  16030. };
  16031. return BaseTexture;
  16032. })();
  16033. BABYLON.BaseTexture = BaseTexture;
  16034. })(BABYLON || (BABYLON = {}));
  16035. //# sourceMappingURL=babylon.baseTexture.js.map
  16036. var BABYLON;
  16037. (function (BABYLON) {
  16038. var Texture = (function (_super) {
  16039. __extends(Texture, _super);
  16040. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  16041. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16042. if (onLoad === void 0) { onLoad = null; }
  16043. if (onError === void 0) { onError = null; }
  16044. if (buffer === void 0) { buffer = null; }
  16045. if (deleteBuffer === void 0) { deleteBuffer = false; }
  16046. _super.call(this, scene);
  16047. this.uOffset = 0;
  16048. this.vOffset = 0;
  16049. this.uScale = 1.0;
  16050. this.vScale = 1.0;
  16051. this.uAng = 0;
  16052. this.vAng = 0;
  16053. this.wAng = 0;
  16054. this.name = url;
  16055. this.url = url;
  16056. this._noMipmap = noMipmap;
  16057. this._invertY = invertY;
  16058. this._samplingMode = samplingMode;
  16059. this._buffer = buffer;
  16060. this._deleteBuffer = deleteBuffer;
  16061. if (!url) {
  16062. return;
  16063. }
  16064. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  16065. if (!this._texture) {
  16066. if (!scene.useDelayedTextureLoading) {
  16067. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  16068. if (deleteBuffer) {
  16069. delete this._buffer;
  16070. }
  16071. }
  16072. else {
  16073. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16074. }
  16075. }
  16076. else {
  16077. BABYLON.Tools.SetImmediate(function () {
  16078. if (onLoad) {
  16079. onLoad();
  16080. }
  16081. });
  16082. }
  16083. }
  16084. Texture.prototype.delayLoad = function () {
  16085. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16086. return;
  16087. }
  16088. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16089. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  16090. if (!this._texture) {
  16091. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  16092. if (this._deleteBuffer) {
  16093. delete this._buffer;
  16094. }
  16095. }
  16096. };
  16097. Texture.prototype.updateSamplingMode = function (samplingMode) {
  16098. if (!this._texture) {
  16099. return;
  16100. }
  16101. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  16102. };
  16103. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  16104. x -= this.uOffset + 0.5;
  16105. y -= this.vOffset + 0.5;
  16106. z -= 0.5;
  16107. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  16108. t.x *= this.uScale;
  16109. t.y *= this.vScale;
  16110. t.x += 0.5;
  16111. t.y += 0.5;
  16112. t.z += 0.5;
  16113. };
  16114. Texture.prototype.getTextureMatrix = function () {
  16115. if (this.uOffset === this._cachedUOffset &&
  16116. this.vOffset === this._cachedVOffset &&
  16117. this.uScale === this._cachedUScale &&
  16118. this.vScale === this._cachedVScale &&
  16119. this.uAng === this._cachedUAng &&
  16120. this.vAng === this._cachedVAng &&
  16121. this.wAng === this._cachedWAng) {
  16122. return this._cachedTextureMatrix;
  16123. }
  16124. this._cachedUOffset = this.uOffset;
  16125. this._cachedVOffset = this.vOffset;
  16126. this._cachedUScale = this.uScale;
  16127. this._cachedVScale = this.vScale;
  16128. this._cachedUAng = this.uAng;
  16129. this._cachedVAng = this.vAng;
  16130. this._cachedWAng = this.wAng;
  16131. if (!this._cachedTextureMatrix) {
  16132. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16133. this._rowGenerationMatrix = new BABYLON.Matrix();
  16134. this._t0 = BABYLON.Vector3.Zero();
  16135. this._t1 = BABYLON.Vector3.Zero();
  16136. this._t2 = BABYLON.Vector3.Zero();
  16137. }
  16138. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  16139. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  16140. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  16141. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  16142. this._t1.subtractInPlace(this._t0);
  16143. this._t2.subtractInPlace(this._t0);
  16144. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16145. this._cachedTextureMatrix.m[0] = this._t1.x;
  16146. this._cachedTextureMatrix.m[1] = this._t1.y;
  16147. this._cachedTextureMatrix.m[2] = this._t1.z;
  16148. this._cachedTextureMatrix.m[4] = this._t2.x;
  16149. this._cachedTextureMatrix.m[5] = this._t2.y;
  16150. this._cachedTextureMatrix.m[6] = this._t2.z;
  16151. this._cachedTextureMatrix.m[8] = this._t0.x;
  16152. this._cachedTextureMatrix.m[9] = this._t0.y;
  16153. this._cachedTextureMatrix.m[10] = this._t0.z;
  16154. return this._cachedTextureMatrix;
  16155. };
  16156. Texture.prototype.getReflectionTextureMatrix = function () {
  16157. if (this.uOffset === this._cachedUOffset &&
  16158. this.vOffset === this._cachedVOffset &&
  16159. this.uScale === this._cachedUScale &&
  16160. this.vScale === this._cachedVScale &&
  16161. this.coordinatesMode === this._cachedCoordinatesMode) {
  16162. return this._cachedTextureMatrix;
  16163. }
  16164. if (!this._cachedTextureMatrix) {
  16165. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  16166. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  16167. }
  16168. this._cachedCoordinatesMode = this.coordinatesMode;
  16169. switch (this.coordinatesMode) {
  16170. case Texture.SPHERICAL_MODE:
  16171. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16172. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  16173. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  16174. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  16175. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  16176. break;
  16177. case Texture.PLANAR_MODE:
  16178. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16179. this._cachedTextureMatrix[0] = this.uScale;
  16180. this._cachedTextureMatrix[5] = this.vScale;
  16181. this._cachedTextureMatrix[12] = this.uOffset;
  16182. this._cachedTextureMatrix[13] = this.vOffset;
  16183. break;
  16184. case Texture.PROJECTION_MODE:
  16185. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  16186. this._projectionModeMatrix.m[0] = 0.5;
  16187. this._projectionModeMatrix.m[5] = -0.5;
  16188. this._projectionModeMatrix.m[10] = 0.0;
  16189. this._projectionModeMatrix.m[12] = 0.5;
  16190. this._projectionModeMatrix.m[13] = 0.5;
  16191. this._projectionModeMatrix.m[14] = 1.0;
  16192. this._projectionModeMatrix.m[15] = 1.0;
  16193. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  16194. break;
  16195. default:
  16196. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  16197. break;
  16198. }
  16199. return this._cachedTextureMatrix;
  16200. };
  16201. Texture.prototype.clone = function () {
  16202. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  16203. // Base texture
  16204. newTexture.hasAlpha = this.hasAlpha;
  16205. newTexture.level = this.level;
  16206. newTexture.wrapU = this.wrapU;
  16207. newTexture.wrapV = this.wrapV;
  16208. newTexture.coordinatesIndex = this.coordinatesIndex;
  16209. newTexture.coordinatesMode = this.coordinatesMode;
  16210. // Texture
  16211. newTexture.uOffset = this.uOffset;
  16212. newTexture.vOffset = this.vOffset;
  16213. newTexture.uScale = this.uScale;
  16214. newTexture.vScale = this.vScale;
  16215. newTexture.uAng = this.uAng;
  16216. newTexture.vAng = this.vAng;
  16217. newTexture.wAng = this.wAng;
  16218. return newTexture;
  16219. };
  16220. // Statics
  16221. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  16222. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  16223. if (onLoad === void 0) { onLoad = null; }
  16224. if (onError === void 0) { onError = null; }
  16225. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  16226. };
  16227. // Constants
  16228. Texture.NEAREST_SAMPLINGMODE = 1;
  16229. Texture.BILINEAR_SAMPLINGMODE = 2;
  16230. Texture.TRILINEAR_SAMPLINGMODE = 3;
  16231. Texture.EXPLICIT_MODE = 0;
  16232. Texture.SPHERICAL_MODE = 1;
  16233. Texture.PLANAR_MODE = 2;
  16234. Texture.CUBIC_MODE = 3;
  16235. Texture.PROJECTION_MODE = 4;
  16236. Texture.SKYBOX_MODE = 5;
  16237. Texture.CLAMP_ADDRESSMODE = 0;
  16238. Texture.WRAP_ADDRESSMODE = 1;
  16239. Texture.MIRROR_ADDRESSMODE = 2;
  16240. return Texture;
  16241. })(BABYLON.BaseTexture);
  16242. BABYLON.Texture = Texture;
  16243. })(BABYLON || (BABYLON = {}));
  16244. //# sourceMappingURL=babylon.texture.js.map
  16245. var BABYLON;
  16246. (function (BABYLON) {
  16247. var CubeTexture = (function (_super) {
  16248. __extends(CubeTexture, _super);
  16249. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  16250. _super.call(this, scene);
  16251. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  16252. this.name = rootUrl;
  16253. this.url = rootUrl;
  16254. this._noMipmap = noMipmap;
  16255. this.hasAlpha = false;
  16256. this._texture = this._getFromCache(rootUrl, noMipmap);
  16257. if (!extensions) {
  16258. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  16259. }
  16260. this._extensions = extensions;
  16261. if (!this._texture) {
  16262. if (!scene.useDelayedTextureLoading) {
  16263. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  16264. }
  16265. else {
  16266. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  16267. }
  16268. }
  16269. this.isCube = true;
  16270. this._textureMatrix = BABYLON.Matrix.Identity();
  16271. }
  16272. CubeTexture.prototype.clone = function () {
  16273. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  16274. // Base texture
  16275. newTexture.level = this.level;
  16276. newTexture.wrapU = this.wrapU;
  16277. newTexture.wrapV = this.wrapV;
  16278. newTexture.coordinatesIndex = this.coordinatesIndex;
  16279. newTexture.coordinatesMode = this.coordinatesMode;
  16280. return newTexture;
  16281. };
  16282. // Methods
  16283. CubeTexture.prototype.delayLoad = function () {
  16284. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  16285. return;
  16286. }
  16287. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  16288. this._texture = this._getFromCache(this.url, this._noMipmap);
  16289. if (!this._texture) {
  16290. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  16291. }
  16292. };
  16293. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  16294. return this._textureMatrix;
  16295. };
  16296. return CubeTexture;
  16297. })(BABYLON.BaseTexture);
  16298. BABYLON.CubeTexture = CubeTexture;
  16299. })(BABYLON || (BABYLON = {}));
  16300. //# sourceMappingURL=babylon.cubeTexture.js.map
  16301. var BABYLON;
  16302. (function (BABYLON) {
  16303. var RenderTargetTexture = (function (_super) {
  16304. __extends(RenderTargetTexture, _super);
  16305. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  16306. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  16307. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  16308. _super.call(this, null, scene, !generateMipMaps);
  16309. this.renderList = new Array();
  16310. this.renderParticles = true;
  16311. this.renderSprites = false;
  16312. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  16313. this._currentRefreshId = -1;
  16314. this._refreshRate = 1;
  16315. this.name = name;
  16316. this.isRenderTarget = true;
  16317. this._size = size;
  16318. this._generateMipMaps = generateMipMaps;
  16319. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  16320. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  16321. // Rendering groups
  16322. this._renderingManager = new BABYLON.RenderingManager(scene);
  16323. }
  16324. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  16325. this._currentRefreshId = -1;
  16326. };
  16327. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  16328. get: function () {
  16329. return this._refreshRate;
  16330. },
  16331. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16332. set: function (value) {
  16333. this._refreshRate = value;
  16334. this.resetRefreshCounter();
  16335. },
  16336. enumerable: true,
  16337. configurable: true
  16338. });
  16339. RenderTargetTexture.prototype._shouldRender = function () {
  16340. if (this._currentRefreshId === -1) {
  16341. this._currentRefreshId = 1;
  16342. return true;
  16343. }
  16344. if (this.refreshRate === this._currentRefreshId) {
  16345. this._currentRefreshId = 1;
  16346. return true;
  16347. }
  16348. this._currentRefreshId++;
  16349. return false;
  16350. };
  16351. RenderTargetTexture.prototype.isReady = function () {
  16352. if (!this.getScene().renderTargetsEnabled) {
  16353. return false;
  16354. }
  16355. return _super.prototype.isReady.call(this);
  16356. };
  16357. RenderTargetTexture.prototype.getRenderSize = function () {
  16358. return this._size;
  16359. };
  16360. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  16361. get: function () {
  16362. return true;
  16363. },
  16364. enumerable: true,
  16365. configurable: true
  16366. });
  16367. RenderTargetTexture.prototype.scale = function (ratio) {
  16368. var newSize = this._size * ratio;
  16369. this.resize(newSize, this._generateMipMaps);
  16370. };
  16371. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  16372. this.releaseInternalTexture();
  16373. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16374. };
  16375. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  16376. var scene = this.getScene();
  16377. var engine = scene.getEngine();
  16378. if (this._waitingRenderList) {
  16379. this.renderList = [];
  16380. for (var index = 0; index < this._waitingRenderList.length; index++) {
  16381. var id = this._waitingRenderList[index];
  16382. this.renderList.push(scene.getMeshByID(id));
  16383. }
  16384. delete this._waitingRenderList;
  16385. }
  16386. if (this.renderList && this.renderList.length === 0) {
  16387. return;
  16388. }
  16389. // Bind
  16390. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  16391. engine.bindFramebuffer(this._texture);
  16392. }
  16393. this._renderingManager.reset();
  16394. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  16395. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  16396. var mesh = currentRenderList[meshIndex];
  16397. if (mesh) {
  16398. if (!mesh.isReady()) {
  16399. // Reset _currentRefreshId
  16400. this.resetRefreshCounter();
  16401. continue;
  16402. }
  16403. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  16404. mesh._activate(scene.getRenderId());
  16405. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  16406. var subMesh = mesh.subMeshes[subIndex];
  16407. scene._activeIndices += subMesh.indexCount;
  16408. this._renderingManager.dispatch(subMesh);
  16409. }
  16410. }
  16411. }
  16412. }
  16413. if (this.onBeforeRender) {
  16414. this.onBeforeRender();
  16415. }
  16416. // Clear
  16417. if (this.onClear) {
  16418. this.onClear(engine);
  16419. }
  16420. else {
  16421. engine.clear(scene.clearColor, true, true);
  16422. }
  16423. if (!this._doNotChangeAspectRatio) {
  16424. scene.updateTransformMatrix(true);
  16425. }
  16426. // Render
  16427. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  16428. if (useCameraPostProcess) {
  16429. scene.postProcessManager._finalizeFrame(false, this._texture);
  16430. }
  16431. if (!this._doNotChangeAspectRatio) {
  16432. scene.updateTransformMatrix(true);
  16433. }
  16434. if (this.onAfterRender) {
  16435. this.onAfterRender();
  16436. }
  16437. // Dump ?
  16438. if (dumpForDebug) {
  16439. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  16440. }
  16441. // Unbind
  16442. engine.unBindFramebuffer(this._texture);
  16443. if (this.onAfterUnbind) {
  16444. this.onAfterUnbind();
  16445. }
  16446. };
  16447. RenderTargetTexture.prototype.clone = function () {
  16448. var textureSize = this.getSize();
  16449. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16450. // Base texture
  16451. newTexture.hasAlpha = this.hasAlpha;
  16452. newTexture.level = this.level;
  16453. // RenderTarget Texture
  16454. newTexture.coordinatesMode = this.coordinatesMode;
  16455. newTexture.renderList = this.renderList.slice(0);
  16456. return newTexture;
  16457. };
  16458. return RenderTargetTexture;
  16459. })(BABYLON.Texture);
  16460. BABYLON.RenderTargetTexture = RenderTargetTexture;
  16461. })(BABYLON || (BABYLON = {}));
  16462. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  16463. var BABYLON;
  16464. (function (BABYLON) {
  16465. var ProceduralTexture = (function (_super) {
  16466. __extends(ProceduralTexture, _super);
  16467. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  16468. if (generateMipMaps === void 0) { generateMipMaps = true; }
  16469. _super.call(this, null, scene, !generateMipMaps);
  16470. this._currentRefreshId = -1;
  16471. this._refreshRate = 1;
  16472. this._vertexDeclaration = [2];
  16473. this._vertexStrideSize = 2 * 4;
  16474. this._uniforms = new Array();
  16475. this._samplers = new Array();
  16476. this._textures = new Array();
  16477. this._floats = new Array();
  16478. this._floatsArrays = {};
  16479. this._colors3 = new Array();
  16480. this._colors4 = new Array();
  16481. this._vectors2 = new Array();
  16482. this._vectors3 = new Array();
  16483. this._matrices = new Array();
  16484. this._fallbackTextureUsed = false;
  16485. scene._proceduralTextures.push(this);
  16486. this.name = name;
  16487. this.isRenderTarget = true;
  16488. this._size = size;
  16489. this._generateMipMaps = generateMipMaps;
  16490. this.setFragment(fragment);
  16491. this._fallbackTexture = fallbackTexture;
  16492. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  16493. // VBO
  16494. var vertices = [];
  16495. vertices.push(1, 1);
  16496. vertices.push(-1, 1);
  16497. vertices.push(-1, -1);
  16498. vertices.push(1, -1);
  16499. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16500. // Indices
  16501. var indices = [];
  16502. indices.push(0);
  16503. indices.push(1);
  16504. indices.push(2);
  16505. indices.push(0);
  16506. indices.push(2);
  16507. indices.push(3);
  16508. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16509. }
  16510. ProceduralTexture.prototype.reset = function () {
  16511. if (this._effect === undefined) {
  16512. return;
  16513. }
  16514. var engine = this.getScene().getEngine();
  16515. engine._releaseEffect(this._effect);
  16516. };
  16517. ProceduralTexture.prototype.isReady = function () {
  16518. var _this = this;
  16519. var engine = this.getScene().getEngine();
  16520. var shaders;
  16521. if (!this._fragment) {
  16522. return false;
  16523. }
  16524. if (this._fallbackTextureUsed) {
  16525. return true;
  16526. }
  16527. if (this._fragment.fragmentElement !== undefined) {
  16528. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  16529. }
  16530. else {
  16531. shaders = { vertex: "procedural", fragment: this._fragment };
  16532. }
  16533. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  16534. _this.releaseInternalTexture();
  16535. if (_this._fallbackTexture) {
  16536. _this._texture = _this._fallbackTexture._texture;
  16537. _this._texture.references++;
  16538. }
  16539. _this._fallbackTextureUsed = true;
  16540. });
  16541. return this._effect.isReady();
  16542. };
  16543. ProceduralTexture.prototype.resetRefreshCounter = function () {
  16544. this._currentRefreshId = -1;
  16545. };
  16546. ProceduralTexture.prototype.setFragment = function (fragment) {
  16547. this._fragment = fragment;
  16548. };
  16549. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  16550. get: function () {
  16551. return this._refreshRate;
  16552. },
  16553. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  16554. set: function (value) {
  16555. this._refreshRate = value;
  16556. this.resetRefreshCounter();
  16557. },
  16558. enumerable: true,
  16559. configurable: true
  16560. });
  16561. ProceduralTexture.prototype._shouldRender = function () {
  16562. if (!this.isReady() || !this._texture) {
  16563. return false;
  16564. }
  16565. if (this._fallbackTextureUsed) {
  16566. return false;
  16567. }
  16568. if (this._currentRefreshId === -1) {
  16569. this._currentRefreshId = 1;
  16570. return true;
  16571. }
  16572. if (this.refreshRate === this._currentRefreshId) {
  16573. this._currentRefreshId = 1;
  16574. return true;
  16575. }
  16576. this._currentRefreshId++;
  16577. return false;
  16578. };
  16579. ProceduralTexture.prototype.getRenderSize = function () {
  16580. return this._size;
  16581. };
  16582. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  16583. if (this._fallbackTextureUsed) {
  16584. return;
  16585. }
  16586. this.releaseInternalTexture();
  16587. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  16588. };
  16589. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  16590. if (this._uniforms.indexOf(uniformName) === -1) {
  16591. this._uniforms.push(uniformName);
  16592. }
  16593. };
  16594. ProceduralTexture.prototype.setTexture = function (name, texture) {
  16595. if (this._samplers.indexOf(name) === -1) {
  16596. this._samplers.push(name);
  16597. }
  16598. this._textures[name] = texture;
  16599. return this;
  16600. };
  16601. ProceduralTexture.prototype.setFloat = function (name, value) {
  16602. this._checkUniform(name);
  16603. this._floats[name] = value;
  16604. return this;
  16605. };
  16606. ProceduralTexture.prototype.setFloats = function (name, value) {
  16607. this._checkUniform(name);
  16608. this._floatsArrays[name] = value;
  16609. return this;
  16610. };
  16611. ProceduralTexture.prototype.setColor3 = function (name, value) {
  16612. this._checkUniform(name);
  16613. this._colors3[name] = value;
  16614. return this;
  16615. };
  16616. ProceduralTexture.prototype.setColor4 = function (name, value) {
  16617. this._checkUniform(name);
  16618. this._colors4[name] = value;
  16619. return this;
  16620. };
  16621. ProceduralTexture.prototype.setVector2 = function (name, value) {
  16622. this._checkUniform(name);
  16623. this._vectors2[name] = value;
  16624. return this;
  16625. };
  16626. ProceduralTexture.prototype.setVector3 = function (name, value) {
  16627. this._checkUniform(name);
  16628. this._vectors3[name] = value;
  16629. return this;
  16630. };
  16631. ProceduralTexture.prototype.setMatrix = function (name, value) {
  16632. this._checkUniform(name);
  16633. this._matrices[name] = value;
  16634. return this;
  16635. };
  16636. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  16637. var scene = this.getScene();
  16638. var engine = scene.getEngine();
  16639. engine.bindFramebuffer(this._texture);
  16640. // Clear
  16641. engine.clear(scene.clearColor, true, true);
  16642. // Render
  16643. engine.enableEffect(this._effect);
  16644. engine.setState(false);
  16645. // Texture
  16646. for (var name in this._textures) {
  16647. this._effect.setTexture(name, this._textures[name]);
  16648. }
  16649. // Float
  16650. for (name in this._floats) {
  16651. this._effect.setFloat(name, this._floats[name]);
  16652. }
  16653. // Floats
  16654. for (name in this._floatsArrays) {
  16655. this._effect.setArray(name, this._floatsArrays[name]);
  16656. }
  16657. // Color3
  16658. for (name in this._colors3) {
  16659. this._effect.setColor3(name, this._colors3[name]);
  16660. }
  16661. // Color4
  16662. for (name in this._colors4) {
  16663. var color = this._colors4[name];
  16664. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  16665. }
  16666. // Vector2
  16667. for (name in this._vectors2) {
  16668. this._effect.setVector2(name, this._vectors2[name]);
  16669. }
  16670. // Vector3
  16671. for (name in this._vectors3) {
  16672. this._effect.setVector3(name, this._vectors3[name]);
  16673. }
  16674. // Matrix
  16675. for (name in this._matrices) {
  16676. this._effect.setMatrix(name, this._matrices[name]);
  16677. }
  16678. // VBOs
  16679. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16680. // Draw order
  16681. engine.draw(true, 0, 6);
  16682. // Unbind
  16683. engine.unBindFramebuffer(this._texture);
  16684. };
  16685. ProceduralTexture.prototype.clone = function () {
  16686. var textureSize = this.getSize();
  16687. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  16688. // Base texture
  16689. newTexture.hasAlpha = this.hasAlpha;
  16690. newTexture.level = this.level;
  16691. // RenderTarget Texture
  16692. newTexture.coordinatesMode = this.coordinatesMode;
  16693. return newTexture;
  16694. };
  16695. ProceduralTexture.prototype.dispose = function () {
  16696. var index = this.getScene()._proceduralTextures.indexOf(this);
  16697. if (index >= 0) {
  16698. this.getScene()._proceduralTextures.splice(index, 1);
  16699. }
  16700. _super.prototype.dispose.call(this);
  16701. };
  16702. return ProceduralTexture;
  16703. })(BABYLON.Texture);
  16704. BABYLON.ProceduralTexture = ProceduralTexture;
  16705. })(BABYLON || (BABYLON = {}));
  16706. //# sourceMappingURL=babylon.proceduralTexture.js.map
  16707. var BABYLON;
  16708. (function (BABYLON) {
  16709. var MirrorTexture = (function (_super) {
  16710. __extends(MirrorTexture, _super);
  16711. function MirrorTexture(name, size, scene, generateMipMaps) {
  16712. var _this = this;
  16713. _super.call(this, name, size, scene, generateMipMaps, true);
  16714. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  16715. this._transformMatrix = BABYLON.Matrix.Zero();
  16716. this._mirrorMatrix = BABYLON.Matrix.Zero();
  16717. this.onBeforeRender = function () {
  16718. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  16719. _this._savedViewMatrix = scene.getViewMatrix();
  16720. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  16721. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  16722. scene.clipPlane = _this.mirrorPlane;
  16723. scene.getEngine().cullBackFaces = false;
  16724. };
  16725. this.onAfterRender = function () {
  16726. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  16727. scene.getEngine().cullBackFaces = true;
  16728. delete scene.clipPlane;
  16729. };
  16730. }
  16731. MirrorTexture.prototype.clone = function () {
  16732. var textureSize = this.getSize();
  16733. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16734. // Base texture
  16735. newTexture.hasAlpha = this.hasAlpha;
  16736. newTexture.level = this.level;
  16737. // Mirror Texture
  16738. newTexture.mirrorPlane = this.mirrorPlane.clone();
  16739. newTexture.renderList = this.renderList.slice(0);
  16740. return newTexture;
  16741. };
  16742. return MirrorTexture;
  16743. })(BABYLON.RenderTargetTexture);
  16744. BABYLON.MirrorTexture = MirrorTexture;
  16745. })(BABYLON || (BABYLON = {}));
  16746. //# sourceMappingURL=babylon.mirrorTexture.js.map
  16747. var BABYLON;
  16748. (function (BABYLON) {
  16749. var DynamicTexture = (function (_super) {
  16750. __extends(DynamicTexture, _super);
  16751. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  16752. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16753. _super.call(this, null, scene, !generateMipMaps);
  16754. this.name = name;
  16755. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16756. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16757. this._generateMipMaps = generateMipMaps;
  16758. if (options.getContext) {
  16759. this._canvas = options;
  16760. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  16761. }
  16762. else {
  16763. this._canvas = document.createElement("canvas");
  16764. if (options.width) {
  16765. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  16766. }
  16767. else {
  16768. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  16769. }
  16770. }
  16771. var textureSize = this.getSize();
  16772. this._canvas.width = textureSize.width;
  16773. this._canvas.height = textureSize.height;
  16774. this._context = this._canvas.getContext("2d");
  16775. }
  16776. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  16777. get: function () {
  16778. return true;
  16779. },
  16780. enumerable: true,
  16781. configurable: true
  16782. });
  16783. DynamicTexture.prototype.scale = function (ratio) {
  16784. var textureSize = this.getSize();
  16785. textureSize.width *= ratio;
  16786. textureSize.height *= ratio;
  16787. this._canvas.width = textureSize.width;
  16788. this._canvas.height = textureSize.height;
  16789. this.releaseInternalTexture();
  16790. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  16791. };
  16792. DynamicTexture.prototype.getContext = function () {
  16793. return this._context;
  16794. };
  16795. DynamicTexture.prototype.clear = function () {
  16796. var size = this.getSize();
  16797. this._context.fillRect(0, 0, size.width, size.height);
  16798. };
  16799. DynamicTexture.prototype.update = function (invertY) {
  16800. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  16801. };
  16802. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  16803. if (update === void 0) { update = true; }
  16804. var size = this.getSize();
  16805. if (clearColor) {
  16806. this._context.fillStyle = clearColor;
  16807. this._context.fillRect(0, 0, size.width, size.height);
  16808. }
  16809. this._context.font = font;
  16810. if (x === null) {
  16811. var textSize = this._context.measureText(text);
  16812. x = (size.width - textSize.width) / 2;
  16813. }
  16814. this._context.fillStyle = color;
  16815. this._context.fillText(text, x, y);
  16816. if (update) {
  16817. this.update(invertY);
  16818. }
  16819. };
  16820. DynamicTexture.prototype.clone = function () {
  16821. var textureSize = this.getSize();
  16822. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  16823. // Base texture
  16824. newTexture.hasAlpha = this.hasAlpha;
  16825. newTexture.level = this.level;
  16826. // Dynamic Texture
  16827. newTexture.wrapU = this.wrapU;
  16828. newTexture.wrapV = this.wrapV;
  16829. return newTexture;
  16830. };
  16831. return DynamicTexture;
  16832. })(BABYLON.Texture);
  16833. BABYLON.DynamicTexture = DynamicTexture;
  16834. })(BABYLON || (BABYLON = {}));
  16835. //# sourceMappingURL=babylon.dynamicTexture.js.map
  16836. var BABYLON;
  16837. (function (BABYLON) {
  16838. var VideoTexture = (function (_super) {
  16839. __extends(VideoTexture, _super);
  16840. function VideoTexture(name, urls, scene, generateMipMaps, invertY, samplingMode) {
  16841. var _this = this;
  16842. if (generateMipMaps === void 0) { generateMipMaps = false; }
  16843. if (invertY === void 0) { invertY = false; }
  16844. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16845. _super.call(this, null, scene, !generateMipMaps, invertY);
  16846. this._autoLaunch = true;
  16847. this.name = name;
  16848. this.video = document.createElement("video");
  16849. this.video.autoplay = false;
  16850. this.video.loop = true;
  16851. this.video.addEventListener("canplaythrough", function () {
  16852. if (BABYLON.Tools.IsExponantOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponantOfTwo(_this.video.videoHeight)) {
  16853. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  16854. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  16855. }
  16856. else {
  16857. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16858. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  16859. generateMipMaps = false;
  16860. }
  16861. _this._texture = scene.getEngine().createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, generateMipMaps, samplingMode, false);
  16862. _this._texture.isReady = true;
  16863. });
  16864. urls.forEach(function (url) {
  16865. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  16866. var source = document.createElement("source");
  16867. source.src = url;
  16868. _this.video.appendChild(source);
  16869. });
  16870. this._lastUpdate = BABYLON.Tools.Now;
  16871. }
  16872. VideoTexture.prototype.update = function () {
  16873. if (this._autoLaunch) {
  16874. this._autoLaunch = false;
  16875. this.video.play();
  16876. }
  16877. var now = BABYLON.Tools.Now;
  16878. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  16879. return false;
  16880. }
  16881. this._lastUpdate = now;
  16882. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  16883. return true;
  16884. };
  16885. return VideoTexture;
  16886. })(BABYLON.Texture);
  16887. BABYLON.VideoTexture = VideoTexture;
  16888. })(BABYLON || (BABYLON = {}));
  16889. //# sourceMappingURL=babylon.videoTexture.js.map
  16890. var BABYLON;
  16891. (function (BABYLON) {
  16892. var CustomProceduralTexture = (function (_super) {
  16893. __extends(CustomProceduralTexture, _super);
  16894. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  16895. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  16896. this._animate = true;
  16897. this._time = 0;
  16898. this._texturePath = texturePath;
  16899. //Try to load json
  16900. this.loadJson(texturePath);
  16901. this.refreshRate = 1;
  16902. }
  16903. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  16904. var _this = this;
  16905. var that = this;
  16906. function noConfigFile() {
  16907. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  16908. try {
  16909. that.setFragment(that._texturePath);
  16910. }
  16911. catch (ex) {
  16912. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  16913. }
  16914. }
  16915. var configFileUrl = jsonUrl + "/config.json";
  16916. var xhr = new XMLHttpRequest();
  16917. xhr.open("GET", configFileUrl, true);
  16918. xhr.addEventListener("load", function () {
  16919. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  16920. try {
  16921. _this._config = JSON.parse(xhr.response);
  16922. _this.updateShaderUniforms();
  16923. _this.updateTextures();
  16924. _this.setFragment(_this._texturePath + "/custom");
  16925. _this._animate = _this._config.animate;
  16926. _this.refreshRate = _this._config.refreshrate;
  16927. }
  16928. catch (ex) {
  16929. noConfigFile();
  16930. }
  16931. }
  16932. else {
  16933. noConfigFile();
  16934. }
  16935. }, false);
  16936. xhr.addEventListener("error", function () {
  16937. noConfigFile();
  16938. }, false);
  16939. try {
  16940. xhr.send();
  16941. }
  16942. catch (ex) {
  16943. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  16944. }
  16945. };
  16946. CustomProceduralTexture.prototype.isReady = function () {
  16947. if (!_super.prototype.isReady.call(this)) {
  16948. return false;
  16949. }
  16950. for (var name in this._textures) {
  16951. var texture = this._textures[name];
  16952. if (!texture.isReady()) {
  16953. return false;
  16954. }
  16955. }
  16956. return true;
  16957. };
  16958. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  16959. if (this._animate) {
  16960. this._time += this.getScene().getAnimationRatio() * 0.03;
  16961. this.updateShaderUniforms();
  16962. }
  16963. _super.prototype.render.call(this, useCameraPostProcess);
  16964. };
  16965. CustomProceduralTexture.prototype.updateTextures = function () {
  16966. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  16967. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  16968. }
  16969. };
  16970. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  16971. if (this._config) {
  16972. for (var j = 0; j < this._config.uniforms.length; j++) {
  16973. var uniform = this._config.uniforms[j];
  16974. switch (uniform.type) {
  16975. case "float":
  16976. this.setFloat(uniform.name, uniform.value);
  16977. break;
  16978. case "color3":
  16979. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  16980. break;
  16981. case "color4":
  16982. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  16983. break;
  16984. case "vector2":
  16985. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  16986. break;
  16987. case "vector3":
  16988. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  16989. break;
  16990. }
  16991. }
  16992. }
  16993. this.setFloat("time", this._time);
  16994. };
  16995. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  16996. get: function () {
  16997. return this._animate;
  16998. },
  16999. set: function (value) {
  17000. this._animate = value;
  17001. },
  17002. enumerable: true,
  17003. configurable: true
  17004. });
  17005. return CustomProceduralTexture;
  17006. })(BABYLON.ProceduralTexture);
  17007. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  17008. })(BABYLON || (BABYLON = {}));
  17009. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  17010. var BABYLON;
  17011. (function (BABYLON) {
  17012. var WoodProceduralTexture = (function (_super) {
  17013. __extends(WoodProceduralTexture, _super);
  17014. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17015. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  17016. this._ampScale = 100.0;
  17017. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  17018. this.updateShaderUniforms();
  17019. this.refreshRate = 0;
  17020. }
  17021. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  17022. this.setFloat("ampScale", this._ampScale);
  17023. this.setColor3("woodColor", this._woodColor);
  17024. };
  17025. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  17026. get: function () {
  17027. return this._ampScale;
  17028. },
  17029. set: function (value) {
  17030. this._ampScale = value;
  17031. this.updateShaderUniforms();
  17032. },
  17033. enumerable: true,
  17034. configurable: true
  17035. });
  17036. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  17037. get: function () {
  17038. return this._woodColor;
  17039. },
  17040. set: function (value) {
  17041. this._woodColor = value;
  17042. this.updateShaderUniforms();
  17043. },
  17044. enumerable: true,
  17045. configurable: true
  17046. });
  17047. return WoodProceduralTexture;
  17048. })(BABYLON.ProceduralTexture);
  17049. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  17050. var FireProceduralTexture = (function (_super) {
  17051. __extends(FireProceduralTexture, _super);
  17052. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17053. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  17054. this._time = 0.0;
  17055. this._speed = new BABYLON.Vector2(0.5, 0.3);
  17056. this._autoGenerateTime = true;
  17057. this._alphaThreshold = 0.5;
  17058. this._fireColors = FireProceduralTexture.RedFireColors;
  17059. this.updateShaderUniforms();
  17060. this.refreshRate = 1;
  17061. }
  17062. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  17063. this.setFloat("time", this._time);
  17064. this.setVector2("speed", this._speed);
  17065. this.setColor3("c1", this._fireColors[0]);
  17066. this.setColor3("c2", this._fireColors[1]);
  17067. this.setColor3("c3", this._fireColors[2]);
  17068. this.setColor3("c4", this._fireColors[3]);
  17069. this.setColor3("c5", this._fireColors[4]);
  17070. this.setColor3("c6", this._fireColors[5]);
  17071. this.setFloat("alphaThreshold", this._alphaThreshold);
  17072. };
  17073. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  17074. if (this._autoGenerateTime) {
  17075. this._time += this.getScene().getAnimationRatio() * 0.03;
  17076. this.updateShaderUniforms();
  17077. }
  17078. _super.prototype.render.call(this, useCameraPostProcess);
  17079. };
  17080. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  17081. get: function () {
  17082. return [
  17083. new BABYLON.Color3(0.5, 0.0, 1.0),
  17084. new BABYLON.Color3(0.9, 0.0, 1.0),
  17085. new BABYLON.Color3(0.2, 0.0, 1.0),
  17086. new BABYLON.Color3(1.0, 0.9, 1.0),
  17087. new BABYLON.Color3(0.1, 0.1, 1.0),
  17088. new BABYLON.Color3(0.9, 0.9, 1.0)
  17089. ];
  17090. },
  17091. enumerable: true,
  17092. configurable: true
  17093. });
  17094. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  17095. get: function () {
  17096. return [
  17097. new BABYLON.Color3(0.5, 1.0, 0.0),
  17098. new BABYLON.Color3(0.5, 1.0, 0.0),
  17099. new BABYLON.Color3(0.3, 0.4, 0.0),
  17100. new BABYLON.Color3(0.5, 1.0, 0.0),
  17101. new BABYLON.Color3(0.2, 0.0, 0.0),
  17102. new BABYLON.Color3(0.5, 1.0, 0.0)
  17103. ];
  17104. },
  17105. enumerable: true,
  17106. configurable: true
  17107. });
  17108. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  17109. get: function () {
  17110. return [
  17111. new BABYLON.Color3(0.5, 0.0, 0.1),
  17112. new BABYLON.Color3(0.9, 0.0, 0.0),
  17113. new BABYLON.Color3(0.2, 0.0, 0.0),
  17114. new BABYLON.Color3(1.0, 0.9, 0.0),
  17115. new BABYLON.Color3(0.1, 0.1, 0.1),
  17116. new BABYLON.Color3(0.9, 0.9, 0.9)
  17117. ];
  17118. },
  17119. enumerable: true,
  17120. configurable: true
  17121. });
  17122. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  17123. get: function () {
  17124. return [
  17125. new BABYLON.Color3(0.1, 0.0, 0.5),
  17126. new BABYLON.Color3(0.0, 0.0, 0.5),
  17127. new BABYLON.Color3(0.1, 0.0, 0.2),
  17128. new BABYLON.Color3(0.0, 0.0, 1.0),
  17129. new BABYLON.Color3(0.1, 0.2, 0.3),
  17130. new BABYLON.Color3(0.0, 0.2, 0.9)
  17131. ];
  17132. },
  17133. enumerable: true,
  17134. configurable: true
  17135. });
  17136. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  17137. get: function () {
  17138. return this._fireColors;
  17139. },
  17140. set: function (value) {
  17141. this._fireColors = value;
  17142. this.updateShaderUniforms();
  17143. },
  17144. enumerable: true,
  17145. configurable: true
  17146. });
  17147. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  17148. get: function () {
  17149. return this._time;
  17150. },
  17151. set: function (value) {
  17152. this._time = value;
  17153. this.updateShaderUniforms();
  17154. },
  17155. enumerable: true,
  17156. configurable: true
  17157. });
  17158. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  17159. get: function () {
  17160. return this._speed;
  17161. },
  17162. set: function (value) {
  17163. this._speed = value;
  17164. this.updateShaderUniforms();
  17165. },
  17166. enumerable: true,
  17167. configurable: true
  17168. });
  17169. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  17170. get: function () {
  17171. return this._alphaThreshold;
  17172. },
  17173. set: function (value) {
  17174. this._alphaThreshold = value;
  17175. this.updateShaderUniforms();
  17176. },
  17177. enumerable: true,
  17178. configurable: true
  17179. });
  17180. return FireProceduralTexture;
  17181. })(BABYLON.ProceduralTexture);
  17182. BABYLON.FireProceduralTexture = FireProceduralTexture;
  17183. var CloudProceduralTexture = (function (_super) {
  17184. __extends(CloudProceduralTexture, _super);
  17185. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17186. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  17187. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  17188. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  17189. this.updateShaderUniforms();
  17190. this.refreshRate = 0;
  17191. }
  17192. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  17193. this.setColor3("skyColor", this._skyColor);
  17194. this.setColor3("cloudColor", this._cloudColor);
  17195. };
  17196. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  17197. get: function () {
  17198. return this._skyColor;
  17199. },
  17200. set: function (value) {
  17201. this._skyColor = value;
  17202. this.updateShaderUniforms();
  17203. },
  17204. enumerable: true,
  17205. configurable: true
  17206. });
  17207. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  17208. get: function () {
  17209. return this._cloudColor;
  17210. },
  17211. set: function (value) {
  17212. this._cloudColor = value;
  17213. this.updateShaderUniforms();
  17214. },
  17215. enumerable: true,
  17216. configurable: true
  17217. });
  17218. return CloudProceduralTexture;
  17219. })(BABYLON.ProceduralTexture);
  17220. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  17221. var GrassProceduralTexture = (function (_super) {
  17222. __extends(GrassProceduralTexture, _super);
  17223. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17224. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  17225. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  17226. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  17227. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  17228. this._groundColor = new BABYLON.Color3(1, 1, 1);
  17229. this._grassColors = [
  17230. new BABYLON.Color3(0.29, 0.38, 0.02),
  17231. new BABYLON.Color3(0.36, 0.49, 0.09),
  17232. new BABYLON.Color3(0.51, 0.6, 0.28)
  17233. ];
  17234. this.updateShaderUniforms();
  17235. this.refreshRate = 0;
  17236. }
  17237. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  17238. this.setColor3("herb1Color", this._grassColors[0]);
  17239. this.setColor3("herb2Color", this._grassColors[1]);
  17240. this.setColor3("herb3Color", this._grassColors[2]);
  17241. this.setColor3("groundColor", this._groundColor);
  17242. };
  17243. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  17244. get: function () {
  17245. return this._grassColors;
  17246. },
  17247. set: function (value) {
  17248. this._grassColors = value;
  17249. this.updateShaderUniforms();
  17250. },
  17251. enumerable: true,
  17252. configurable: true
  17253. });
  17254. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  17255. get: function () {
  17256. return this._groundColor;
  17257. },
  17258. set: function (value) {
  17259. this.groundColor = value;
  17260. this.updateShaderUniforms();
  17261. },
  17262. enumerable: true,
  17263. configurable: true
  17264. });
  17265. return GrassProceduralTexture;
  17266. })(BABYLON.ProceduralTexture);
  17267. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  17268. var RoadProceduralTexture = (function (_super) {
  17269. __extends(RoadProceduralTexture, _super);
  17270. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17271. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  17272. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  17273. this.updateShaderUniforms();
  17274. this.refreshRate = 0;
  17275. }
  17276. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  17277. this.setColor3("roadColor", this._roadColor);
  17278. };
  17279. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  17280. get: function () {
  17281. return this._roadColor;
  17282. },
  17283. set: function (value) {
  17284. this._roadColor = value;
  17285. this.updateShaderUniforms();
  17286. },
  17287. enumerable: true,
  17288. configurable: true
  17289. });
  17290. return RoadProceduralTexture;
  17291. })(BABYLON.ProceduralTexture);
  17292. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  17293. var BrickProceduralTexture = (function (_super) {
  17294. __extends(BrickProceduralTexture, _super);
  17295. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17296. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  17297. this._numberOfBricksHeight = 15;
  17298. this._numberOfBricksWidth = 5;
  17299. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17300. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17301. this.updateShaderUniforms();
  17302. this.refreshRate = 0;
  17303. }
  17304. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  17305. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  17306. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  17307. this.setColor3("brickColor", this._brickColor);
  17308. this.setColor3("jointColor", this._jointColor);
  17309. };
  17310. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  17311. get: function () {
  17312. return this._numberOfBricksHeight;
  17313. },
  17314. set: function (value) {
  17315. this._numberOfBricksHeight = value;
  17316. this.updateShaderUniforms();
  17317. },
  17318. enumerable: true,
  17319. configurable: true
  17320. });
  17321. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  17322. get: function () {
  17323. return this._numberOfBricksWidth;
  17324. },
  17325. set: function (value) {
  17326. this._numberOfBricksHeight = value;
  17327. this.updateShaderUniforms();
  17328. },
  17329. enumerable: true,
  17330. configurable: true
  17331. });
  17332. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  17333. get: function () {
  17334. return this._jointColor;
  17335. },
  17336. set: function (value) {
  17337. this._jointColor = value;
  17338. this.updateShaderUniforms();
  17339. },
  17340. enumerable: true,
  17341. configurable: true
  17342. });
  17343. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  17344. get: function () {
  17345. return this._brickColor;
  17346. },
  17347. set: function (value) {
  17348. this._brickColor = value;
  17349. this.updateShaderUniforms();
  17350. },
  17351. enumerable: true,
  17352. configurable: true
  17353. });
  17354. return BrickProceduralTexture;
  17355. })(BABYLON.ProceduralTexture);
  17356. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  17357. var MarbleProceduralTexture = (function (_super) {
  17358. __extends(MarbleProceduralTexture, _super);
  17359. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  17360. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  17361. this._numberOfTilesHeight = 3;
  17362. this._numberOfTilesWidth = 3;
  17363. this._amplitude = 9.0;
  17364. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  17365. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  17366. this.updateShaderUniforms();
  17367. this.refreshRate = 0;
  17368. }
  17369. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  17370. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  17371. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  17372. this.setFloat("amplitude", this._amplitude);
  17373. this.setColor3("marbleColor", this._marbleColor);
  17374. this.setColor3("jointColor", this._jointColor);
  17375. };
  17376. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  17377. get: function () {
  17378. return this._numberOfTilesHeight;
  17379. },
  17380. set: function (value) {
  17381. this._numberOfTilesHeight = value;
  17382. this.updateShaderUniforms();
  17383. },
  17384. enumerable: true,
  17385. configurable: true
  17386. });
  17387. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  17388. get: function () {
  17389. return this._numberOfTilesWidth;
  17390. },
  17391. set: function (value) {
  17392. this._numberOfTilesWidth = value;
  17393. this.updateShaderUniforms();
  17394. },
  17395. enumerable: true,
  17396. configurable: true
  17397. });
  17398. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  17399. get: function () {
  17400. return this._jointColor;
  17401. },
  17402. set: function (value) {
  17403. this._jointColor = value;
  17404. this.updateShaderUniforms();
  17405. },
  17406. enumerable: true,
  17407. configurable: true
  17408. });
  17409. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  17410. get: function () {
  17411. return this._marbleColor;
  17412. },
  17413. set: function (value) {
  17414. this._marbleColor = value;
  17415. this.updateShaderUniforms();
  17416. },
  17417. enumerable: true,
  17418. configurable: true
  17419. });
  17420. return MarbleProceduralTexture;
  17421. })(BABYLON.ProceduralTexture);
  17422. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  17423. })(BABYLON || (BABYLON = {}));
  17424. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  17425. var BABYLON;
  17426. (function (BABYLON) {
  17427. var EffectFallbacks = (function () {
  17428. function EffectFallbacks() {
  17429. this._defines = {};
  17430. this._currentRank = 32;
  17431. this._maxRank = -1;
  17432. }
  17433. EffectFallbacks.prototype.addFallback = function (rank, define) {
  17434. if (!this._defines[rank]) {
  17435. if (rank < this._currentRank) {
  17436. this._currentRank = rank;
  17437. }
  17438. if (rank > this._maxRank) {
  17439. this._maxRank = rank;
  17440. }
  17441. this._defines[rank] = new Array();
  17442. }
  17443. this._defines[rank].push(define);
  17444. };
  17445. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  17446. get: function () {
  17447. return this._currentRank <= this._maxRank;
  17448. },
  17449. enumerable: true,
  17450. configurable: true
  17451. });
  17452. EffectFallbacks.prototype.reduce = function (currentDefines) {
  17453. var currentFallbacks = this._defines[this._currentRank];
  17454. for (var index = 0; index < currentFallbacks.length; index++) {
  17455. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  17456. }
  17457. this._currentRank++;
  17458. return currentDefines;
  17459. };
  17460. return EffectFallbacks;
  17461. })();
  17462. BABYLON.EffectFallbacks = EffectFallbacks;
  17463. var Effect = (function () {
  17464. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  17465. var _this = this;
  17466. this._isReady = false;
  17467. this._compilationError = "";
  17468. this._valueCache = [];
  17469. this._engine = engine;
  17470. this.name = baseName;
  17471. this.defines = defines;
  17472. this._uniformsNames = uniformsNames.concat(samplers);
  17473. this._samplers = samplers;
  17474. this._attributesNames = attributesNames;
  17475. this.onError = onError;
  17476. this.onCompiled = onCompiled;
  17477. var vertexSource;
  17478. var fragmentSource;
  17479. if (baseName.vertexElement) {
  17480. vertexSource = document.getElementById(baseName.vertexElement);
  17481. if (!vertexSource) {
  17482. vertexSource = baseName.vertexElement;
  17483. }
  17484. }
  17485. else {
  17486. vertexSource = baseName.vertex || baseName;
  17487. }
  17488. if (baseName.fragmentElement) {
  17489. fragmentSource = document.getElementById(baseName.fragmentElement);
  17490. if (!fragmentSource) {
  17491. fragmentSource = baseName.fragmentElement;
  17492. }
  17493. }
  17494. else {
  17495. fragmentSource = baseName.fragment || baseName;
  17496. }
  17497. this._loadVertexShader(vertexSource, function (vertexCode) {
  17498. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  17499. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  17500. });
  17501. });
  17502. }
  17503. // Properties
  17504. Effect.prototype.isReady = function () {
  17505. return this._isReady;
  17506. };
  17507. Effect.prototype.getProgram = function () {
  17508. return this._program;
  17509. };
  17510. Effect.prototype.getAttributesNames = function () {
  17511. return this._attributesNames;
  17512. };
  17513. Effect.prototype.getAttributeLocation = function (index) {
  17514. return this._attributes[index];
  17515. };
  17516. Effect.prototype.getAttributeLocationByName = function (name) {
  17517. var index = this._attributesNames.indexOf(name);
  17518. return this._attributes[index];
  17519. };
  17520. Effect.prototype.getAttributesCount = function () {
  17521. return this._attributes.length;
  17522. };
  17523. Effect.prototype.getUniformIndex = function (uniformName) {
  17524. return this._uniformsNames.indexOf(uniformName);
  17525. };
  17526. Effect.prototype.getUniform = function (uniformName) {
  17527. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  17528. };
  17529. Effect.prototype.getSamplers = function () {
  17530. return this._samplers;
  17531. };
  17532. Effect.prototype.getCompilationError = function () {
  17533. return this._compilationError;
  17534. };
  17535. // Methods
  17536. Effect.prototype._loadVertexShader = function (vertex, callback) {
  17537. // DOM element ?
  17538. if (vertex instanceof HTMLElement) {
  17539. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  17540. callback(vertexCode);
  17541. return;
  17542. }
  17543. // Is in local store ?
  17544. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  17545. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  17546. return;
  17547. }
  17548. var vertexShaderUrl;
  17549. if (vertex[0] === "." || vertex[0] === "/") {
  17550. vertexShaderUrl = vertex;
  17551. }
  17552. else {
  17553. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  17554. }
  17555. // Vertex shader
  17556. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  17557. };
  17558. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  17559. // DOM element ?
  17560. if (fragment instanceof HTMLElement) {
  17561. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  17562. callback(fragmentCode);
  17563. return;
  17564. }
  17565. // Is in local store ?
  17566. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  17567. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  17568. return;
  17569. }
  17570. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  17571. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  17572. return;
  17573. }
  17574. var fragmentShaderUrl;
  17575. if (fragment[0] === "." || fragment[0] === "/") {
  17576. fragmentShaderUrl = fragment;
  17577. }
  17578. else {
  17579. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  17580. }
  17581. // Fragment shader
  17582. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  17583. };
  17584. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  17585. try {
  17586. var engine = this._engine;
  17587. if (!engine.getCaps().highPrecisionShaderSupported) {
  17588. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17589. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17590. }
  17591. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  17592. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  17593. this._attributes = engine.getAttributes(this._program, attributesNames);
  17594. for (var index = 0; index < this._samplers.length; index++) {
  17595. var sampler = this.getUniform(this._samplers[index]);
  17596. if (sampler == null) {
  17597. this._samplers.splice(index, 1);
  17598. index--;
  17599. }
  17600. }
  17601. engine.bindSamplers(this);
  17602. this._isReady = true;
  17603. if (this.onCompiled) {
  17604. this.onCompiled(this);
  17605. }
  17606. }
  17607. catch (e) {
  17608. // Is it a problem with precision?
  17609. if (e.message.indexOf("highp") !== -1) {
  17610. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  17611. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  17612. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17613. return;
  17614. }
  17615. // Let's go through fallbacks then
  17616. if (fallbacks && fallbacks.isMoreFallbacks) {
  17617. defines = fallbacks.reduce(defines);
  17618. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  17619. }
  17620. else {
  17621. BABYLON.Tools.Error("Unable to compile effect: ");
  17622. if (this.name.vertexElement) {
  17623. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  17624. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  17625. }
  17626. else if (this.name.vertex) {
  17627. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  17628. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  17629. }
  17630. else {
  17631. BABYLON.Tools.Error("Vertex shader:" + this.name);
  17632. BABYLON.Tools.Error("Fragment shader:" + this.name);
  17633. }
  17634. BABYLON.Tools.Error("Defines: " + defines);
  17635. BABYLON.Tools.Error("Error: " + e.message);
  17636. this._compilationError = e.message;
  17637. if (this.onError) {
  17638. this.onError(this, this._compilationError);
  17639. }
  17640. }
  17641. }
  17642. };
  17643. Effect.prototype._bindTexture = function (channel, texture) {
  17644. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  17645. };
  17646. Effect.prototype.setTexture = function (channel, texture) {
  17647. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  17648. };
  17649. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17650. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  17651. };
  17652. //public _cacheMatrix(uniformName, matrix) {
  17653. // if (!this._valueCache[uniformName]) {
  17654. // this._valueCache[uniformName] = new BABYLON.Matrix();
  17655. // }
  17656. // for (var index = 0; index < 16; index++) {
  17657. // this._valueCache[uniformName].m[index] = matrix.m[index];
  17658. // }
  17659. //};
  17660. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  17661. if (!this._valueCache[uniformName]) {
  17662. this._valueCache[uniformName] = [x, y];
  17663. return;
  17664. }
  17665. this._valueCache[uniformName][0] = x;
  17666. this._valueCache[uniformName][1] = y;
  17667. };
  17668. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  17669. if (!this._valueCache[uniformName]) {
  17670. this._valueCache[uniformName] = [x, y, z];
  17671. return;
  17672. }
  17673. this._valueCache[uniformName][0] = x;
  17674. this._valueCache[uniformName][1] = y;
  17675. this._valueCache[uniformName][2] = z;
  17676. };
  17677. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  17678. if (!this._valueCache[uniformName]) {
  17679. this._valueCache[uniformName] = [x, y, z, w];
  17680. return;
  17681. }
  17682. this._valueCache[uniformName][0] = x;
  17683. this._valueCache[uniformName][1] = y;
  17684. this._valueCache[uniformName][2] = z;
  17685. this._valueCache[uniformName][3] = w;
  17686. };
  17687. Effect.prototype.setArray = function (uniformName, array) {
  17688. this._engine.setArray(this.getUniform(uniformName), array);
  17689. return this;
  17690. };
  17691. Effect.prototype.setArray2 = function (uniformName, array) {
  17692. this._engine.setArray2(this.getUniform(uniformName), array);
  17693. return this;
  17694. };
  17695. Effect.prototype.setArray3 = function (uniformName, array) {
  17696. this._engine.setArray3(this.getUniform(uniformName), array);
  17697. return this;
  17698. };
  17699. Effect.prototype.setArray4 = function (uniformName, array) {
  17700. this._engine.setArray4(this.getUniform(uniformName), array);
  17701. return this;
  17702. };
  17703. Effect.prototype.setMatrices = function (uniformName, matrices) {
  17704. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  17705. return this;
  17706. };
  17707. Effect.prototype.setMatrix = function (uniformName, matrix) {
  17708. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  17709. // return;
  17710. //this._cacheMatrix(uniformName, matrix);
  17711. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  17712. return this;
  17713. };
  17714. Effect.prototype.setFloat = function (uniformName, value) {
  17715. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  17716. return this;
  17717. this._valueCache[uniformName] = value;
  17718. this._engine.setFloat(this.getUniform(uniformName), value);
  17719. return this;
  17720. };
  17721. Effect.prototype.setBool = function (uniformName, bool) {
  17722. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  17723. return this;
  17724. this._valueCache[uniformName] = bool;
  17725. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  17726. return this;
  17727. };
  17728. Effect.prototype.setVector2 = function (uniformName, vector2) {
  17729. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  17730. return this;
  17731. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  17732. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  17733. return this;
  17734. };
  17735. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  17736. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  17737. return this;
  17738. this._cacheFloat2(uniformName, x, y);
  17739. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  17740. return this;
  17741. };
  17742. Effect.prototype.setVector3 = function (uniformName, vector3) {
  17743. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  17744. return this;
  17745. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  17746. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  17747. return this;
  17748. };
  17749. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  17750. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  17751. return this;
  17752. this._cacheFloat3(uniformName, x, y, z);
  17753. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  17754. return this;
  17755. };
  17756. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  17757. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  17758. return this;
  17759. this._cacheFloat4(uniformName, x, y, z, w);
  17760. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  17761. return this;
  17762. };
  17763. Effect.prototype.setColor3 = function (uniformName, color3) {
  17764. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  17765. return this;
  17766. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  17767. this._engine.setColor3(this.getUniform(uniformName), color3);
  17768. return this;
  17769. };
  17770. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  17771. 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)
  17772. return this;
  17773. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  17774. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  17775. return this;
  17776. };
  17777. // Statics
  17778. Effect.ShadersStore = {};
  17779. return Effect;
  17780. })();
  17781. BABYLON.Effect = Effect;
  17782. })(BABYLON || (BABYLON = {}));
  17783. //# sourceMappingURL=babylon.effect.js.map
  17784. var BABYLON;
  17785. (function (BABYLON) {
  17786. var Material = (function () {
  17787. function Material(name, scene, doNotAdd) {
  17788. this.name = name;
  17789. this.checkReadyOnEveryCall = true;
  17790. this.checkReadyOnlyOnce = false;
  17791. this.state = "";
  17792. this.alpha = 1.0;
  17793. this.backFaceCulling = true;
  17794. this._wasPreviouslyReady = false;
  17795. this._fillMode = Material.TriangleFillMode;
  17796. this.pointSize = 1.0;
  17797. this.zOffset = 0;
  17798. this.id = name;
  17799. this._scene = scene;
  17800. if (!doNotAdd) {
  17801. scene.materials.push(this);
  17802. }
  17803. }
  17804. Object.defineProperty(Material, "TriangleFillMode", {
  17805. get: function () {
  17806. return Material._TriangleFillMode;
  17807. },
  17808. enumerable: true,
  17809. configurable: true
  17810. });
  17811. Object.defineProperty(Material, "WireFrameFillMode", {
  17812. get: function () {
  17813. return Material._WireFrameFillMode;
  17814. },
  17815. enumerable: true,
  17816. configurable: true
  17817. });
  17818. Object.defineProperty(Material, "PointFillMode", {
  17819. get: function () {
  17820. return Material._PointFillMode;
  17821. },
  17822. enumerable: true,
  17823. configurable: true
  17824. });
  17825. Object.defineProperty(Material.prototype, "wireframe", {
  17826. get: function () {
  17827. return this._fillMode === Material.WireFrameFillMode;
  17828. },
  17829. set: function (value) {
  17830. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  17831. },
  17832. enumerable: true,
  17833. configurable: true
  17834. });
  17835. Object.defineProperty(Material.prototype, "pointsCloud", {
  17836. get: function () {
  17837. return this._fillMode === Material.PointFillMode;
  17838. },
  17839. set: function (value) {
  17840. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  17841. },
  17842. enumerable: true,
  17843. configurable: true
  17844. });
  17845. Object.defineProperty(Material.prototype, "fillMode", {
  17846. get: function () {
  17847. return this._fillMode;
  17848. },
  17849. set: function (value) {
  17850. this._fillMode = value;
  17851. },
  17852. enumerable: true,
  17853. configurable: true
  17854. });
  17855. Material.prototype.isReady = function (mesh, useInstances) {
  17856. return true;
  17857. };
  17858. Material.prototype.getEffect = function () {
  17859. return this._effect;
  17860. };
  17861. Material.prototype.getScene = function () {
  17862. return this._scene;
  17863. };
  17864. Material.prototype.needAlphaBlending = function () {
  17865. return (this.alpha < 1.0);
  17866. };
  17867. Material.prototype.needAlphaTesting = function () {
  17868. return false;
  17869. };
  17870. Material.prototype.getAlphaTestTexture = function () {
  17871. return null;
  17872. };
  17873. Material.prototype.trackCreation = function (onCompiled, onError) {
  17874. };
  17875. Material.prototype._preBind = function () {
  17876. var engine = this._scene.getEngine();
  17877. engine.enableEffect(this._effect);
  17878. engine.setState(this.backFaceCulling, this.zOffset);
  17879. };
  17880. Material.prototype.bind = function (world, mesh) {
  17881. this._scene._cachedMaterial = this;
  17882. if (this.onBind) {
  17883. this.onBind(this, mesh);
  17884. }
  17885. };
  17886. Material.prototype.bindOnlyWorldMatrix = function (world) {
  17887. };
  17888. Material.prototype.unbind = function () {
  17889. };
  17890. Material.prototype.dispose = function (forceDisposeEffect) {
  17891. // Remove from scene
  17892. var index = this._scene.materials.indexOf(this);
  17893. this._scene.materials.splice(index, 1);
  17894. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  17895. if (forceDisposeEffect && this._effect) {
  17896. this._scene.getEngine()._releaseEffect(this._effect);
  17897. this._effect = null;
  17898. }
  17899. // Callback
  17900. if (this.onDispose) {
  17901. this.onDispose();
  17902. }
  17903. };
  17904. Material._TriangleFillMode = 0;
  17905. Material._WireFrameFillMode = 1;
  17906. Material._PointFillMode = 2;
  17907. return Material;
  17908. })();
  17909. BABYLON.Material = Material;
  17910. })(BABYLON || (BABYLON = {}));
  17911. //# sourceMappingURL=babylon.material.js.map
  17912. var BABYLON;
  17913. (function (BABYLON) {
  17914. var maxSimultaneousLights = 4;
  17915. var FresnelParameters = (function () {
  17916. function FresnelParameters() {
  17917. this.isEnabled = true;
  17918. this.leftColor = BABYLON.Color3.White();
  17919. this.rightColor = BABYLON.Color3.Black();
  17920. this.bias = 0;
  17921. this.power = 1;
  17922. }
  17923. return FresnelParameters;
  17924. })();
  17925. BABYLON.FresnelParameters = FresnelParameters;
  17926. var StandardMaterial = (function (_super) {
  17927. __extends(StandardMaterial, _super);
  17928. function StandardMaterial(name, scene) {
  17929. var _this = this;
  17930. _super.call(this, name, scene);
  17931. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  17932. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  17933. this.specularColor = new BABYLON.Color3(1, 1, 1);
  17934. this.specularPower = 64;
  17935. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  17936. this.useAlphaFromDiffuseTexture = false;
  17937. this.useSpecularOverAlpha = true;
  17938. this.fogEnabled = true;
  17939. this._cachedDefines = null;
  17940. this._renderTargets = new BABYLON.SmartArray(16);
  17941. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  17942. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  17943. this._scaledDiffuse = new BABYLON.Color3();
  17944. this._scaledSpecular = new BABYLON.Color3();
  17945. this.getRenderTargetTextures = function () {
  17946. _this._renderTargets.reset();
  17947. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  17948. _this._renderTargets.push(_this.reflectionTexture);
  17949. }
  17950. return _this._renderTargets;
  17951. };
  17952. }
  17953. StandardMaterial.prototype.needAlphaBlending = function () {
  17954. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  17955. };
  17956. StandardMaterial.prototype.needAlphaTesting = function () {
  17957. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  17958. };
  17959. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  17960. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  17961. };
  17962. StandardMaterial.prototype.getAlphaTestTexture = function () {
  17963. return this.diffuseTexture;
  17964. };
  17965. // Methods
  17966. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  17967. if (this.checkReadyOnlyOnce) {
  17968. if (this._wasPreviouslyReady) {
  17969. return true;
  17970. }
  17971. }
  17972. var scene = this.getScene();
  17973. if (!this.checkReadyOnEveryCall) {
  17974. if (this._renderId === scene.getRenderId()) {
  17975. return true;
  17976. }
  17977. }
  17978. var engine = scene.getEngine();
  17979. var defines = [];
  17980. var fallbacks = new BABYLON.EffectFallbacks();
  17981. var needNormals = false;
  17982. var needUVs = false;
  17983. // Textures
  17984. if (scene.texturesEnabled) {
  17985. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  17986. if (!this.diffuseTexture.isReady()) {
  17987. return false;
  17988. }
  17989. else {
  17990. needUVs = true;
  17991. defines.push("#define DIFFUSE");
  17992. }
  17993. }
  17994. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  17995. if (!this.ambientTexture.isReady()) {
  17996. return false;
  17997. }
  17998. else {
  17999. needUVs = true;
  18000. defines.push("#define AMBIENT");
  18001. }
  18002. }
  18003. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18004. if (!this.opacityTexture.isReady()) {
  18005. return false;
  18006. }
  18007. else {
  18008. needUVs = true;
  18009. defines.push("#define OPACITY");
  18010. if (this.opacityTexture.getAlphaFromRGB) {
  18011. defines.push("#define OPACITYRGB");
  18012. }
  18013. }
  18014. }
  18015. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18016. if (!this.reflectionTexture.isReady()) {
  18017. return false;
  18018. }
  18019. else {
  18020. needNormals = true;
  18021. needUVs = true;
  18022. defines.push("#define REFLECTION");
  18023. fallbacks.addFallback(0, "REFLECTION");
  18024. }
  18025. }
  18026. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18027. if (!this.emissiveTexture.isReady()) {
  18028. return false;
  18029. }
  18030. else {
  18031. needUVs = true;
  18032. defines.push("#define EMISSIVE");
  18033. }
  18034. }
  18035. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18036. if (!this.specularTexture.isReady()) {
  18037. return false;
  18038. }
  18039. else {
  18040. needUVs = true;
  18041. defines.push("#define SPECULAR");
  18042. fallbacks.addFallback(0, "SPECULAR");
  18043. }
  18044. }
  18045. }
  18046. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  18047. if (!this.bumpTexture.isReady()) {
  18048. return false;
  18049. }
  18050. else {
  18051. needUVs = true;
  18052. defines.push("#define BUMP");
  18053. fallbacks.addFallback(0, "BUMP");
  18054. }
  18055. }
  18056. // Effect
  18057. if (this.useSpecularOverAlpha) {
  18058. defines.push("#define SPECULAROVERALPHA");
  18059. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  18060. }
  18061. if (scene.clipPlane) {
  18062. defines.push("#define CLIPPLANE");
  18063. }
  18064. if (engine.getAlphaTesting()) {
  18065. defines.push("#define ALPHATEST");
  18066. }
  18067. if (this._shouldUseAlphaFromDiffuseTexture()) {
  18068. defines.push("#define ALPHAFROMDIFFUSE");
  18069. }
  18070. // Point size
  18071. if (this.pointsCloud || scene.forcePointsCloud) {
  18072. defines.push("#define POINTSIZE");
  18073. }
  18074. // Fog
  18075. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  18076. defines.push("#define FOG");
  18077. fallbacks.addFallback(1, "FOG");
  18078. }
  18079. var shadowsActivated = false;
  18080. var lightIndex = 0;
  18081. if (scene.lightsEnabled) {
  18082. for (var index = 0; index < scene.lights.length; index++) {
  18083. var light = scene.lights[index];
  18084. if (!light.isEnabled()) {
  18085. continue;
  18086. }
  18087. // Excluded check
  18088. if (light._excludedMeshesIds.length > 0) {
  18089. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  18090. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  18091. if (excludedMesh) {
  18092. light.excludedMeshes.push(excludedMesh);
  18093. }
  18094. }
  18095. light._excludedMeshesIds = [];
  18096. }
  18097. // Included check
  18098. if (light._includedOnlyMeshesIds.length > 0) {
  18099. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  18100. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  18101. if (includedOnlyMesh) {
  18102. light.includedOnlyMeshes.push(includedOnlyMesh);
  18103. }
  18104. }
  18105. light._includedOnlyMeshesIds = [];
  18106. }
  18107. if (!light.canAffectMesh(mesh)) {
  18108. continue;
  18109. }
  18110. needNormals = true;
  18111. defines.push("#define LIGHT" + lightIndex);
  18112. if (lightIndex > 0) {
  18113. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  18114. }
  18115. var type;
  18116. if (light instanceof BABYLON.SpotLight) {
  18117. type = "#define SPOTLIGHT" + lightIndex;
  18118. }
  18119. else if (light instanceof BABYLON.HemisphericLight) {
  18120. type = "#define HEMILIGHT" + lightIndex;
  18121. }
  18122. else {
  18123. type = "#define POINTDIRLIGHT" + lightIndex;
  18124. }
  18125. defines.push(type);
  18126. if (lightIndex > 0) {
  18127. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  18128. }
  18129. // Shadows
  18130. if (scene.shadowsEnabled) {
  18131. var shadowGenerator = light.getShadowGenerator();
  18132. if (mesh && mesh.receiveShadows && shadowGenerator) {
  18133. defines.push("#define SHADOW" + lightIndex);
  18134. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  18135. if (!shadowsActivated) {
  18136. defines.push("#define SHADOWS");
  18137. shadowsActivated = true;
  18138. }
  18139. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  18140. defines.push("#define SHADOWVSM" + lightIndex);
  18141. if (lightIndex > 0) {
  18142. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  18143. }
  18144. }
  18145. if (shadowGenerator.usePoissonSampling) {
  18146. defines.push("#define SHADOWPCF" + lightIndex);
  18147. if (lightIndex > 0) {
  18148. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  18149. }
  18150. }
  18151. }
  18152. }
  18153. lightIndex++;
  18154. if (lightIndex === maxSimultaneousLights)
  18155. break;
  18156. }
  18157. }
  18158. if (StandardMaterial.FresnelEnabled) {
  18159. // Fresnel
  18160. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  18161. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  18162. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  18163. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18164. var fresnelRank = 1;
  18165. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18166. defines.push("#define DIFFUSEFRESNEL");
  18167. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  18168. fresnelRank++;
  18169. }
  18170. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18171. defines.push("#define OPACITYFRESNEL");
  18172. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  18173. fresnelRank++;
  18174. }
  18175. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18176. defines.push("#define REFLECTIONFRESNEL");
  18177. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  18178. fresnelRank++;
  18179. }
  18180. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18181. defines.push("#define EMISSIVEFRESNEL");
  18182. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  18183. fresnelRank++;
  18184. }
  18185. needNormals = true;
  18186. defines.push("#define FRESNEL");
  18187. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  18188. }
  18189. }
  18190. // Attribs
  18191. var attribs = [BABYLON.VertexBuffer.PositionKind];
  18192. if (mesh) {
  18193. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18194. attribs.push(BABYLON.VertexBuffer.NormalKind);
  18195. defines.push("#define NORMAL");
  18196. }
  18197. if (needUVs) {
  18198. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18199. attribs.push(BABYLON.VertexBuffer.UVKind);
  18200. defines.push("#define UV1");
  18201. }
  18202. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18203. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  18204. defines.push("#define UV2");
  18205. }
  18206. }
  18207. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18208. attribs.push(BABYLON.VertexBuffer.ColorKind);
  18209. defines.push("#define VERTEXCOLOR");
  18210. if (mesh.hasVertexAlpha) {
  18211. defines.push("#define VERTEXALPHA");
  18212. }
  18213. }
  18214. if (mesh.useBones) {
  18215. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18216. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18217. defines.push("#define BONES");
  18218. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  18219. defines.push("#define BONES4");
  18220. fallbacks.addFallback(0, "BONES4");
  18221. }
  18222. // Instances
  18223. if (useInstances) {
  18224. defines.push("#define INSTANCES");
  18225. attribs.push("world0");
  18226. attribs.push("world1");
  18227. attribs.push("world2");
  18228. attribs.push("world3");
  18229. }
  18230. }
  18231. // Get correct effect
  18232. var join = defines.join("\n");
  18233. if (this._cachedDefines !== join) {
  18234. this._cachedDefines = join;
  18235. scene.resetCachedMaterial();
  18236. // Legacy browser patch
  18237. var shaderName = "default";
  18238. if (!scene.getEngine().getCaps().standardDerivatives) {
  18239. shaderName = "legacydefault";
  18240. }
  18241. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  18242. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  18243. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  18244. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  18245. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  18246. "vFogInfos", "vFogColor", "pointSize",
  18247. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  18248. "mBones",
  18249. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  18250. "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3",
  18251. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  18252. ], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  18253. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  18254. ], join, fallbacks, this.onCompiled, this.onError);
  18255. }
  18256. if (!this._effect.isReady()) {
  18257. return false;
  18258. }
  18259. this._renderId = scene.getRenderId();
  18260. this._wasPreviouslyReady = true;
  18261. return true;
  18262. };
  18263. StandardMaterial.prototype.unbind = function () {
  18264. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  18265. this._effect.setTexture("reflection2DSampler", null);
  18266. }
  18267. };
  18268. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  18269. this._effect.setMatrix("world", world);
  18270. };
  18271. StandardMaterial.prototype.bind = function (world, mesh) {
  18272. var scene = this.getScene();
  18273. // Matrices
  18274. this.bindOnlyWorldMatrix(world);
  18275. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  18276. // Bones
  18277. if (mesh && mesh.useBones) {
  18278. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  18279. }
  18280. if (scene.getCachedMaterial() !== this) {
  18281. if (StandardMaterial.FresnelEnabled) {
  18282. // Fresnel
  18283. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  18284. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  18285. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  18286. }
  18287. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  18288. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  18289. }
  18290. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  18291. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  18292. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  18293. }
  18294. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  18295. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  18296. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  18297. }
  18298. }
  18299. // Textures
  18300. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  18301. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  18302. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  18303. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  18304. }
  18305. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  18306. this._effect.setTexture("ambientSampler", this.ambientTexture);
  18307. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  18308. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  18309. }
  18310. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  18311. this._effect.setTexture("opacitySampler", this.opacityTexture);
  18312. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  18313. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  18314. }
  18315. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  18316. if (this.reflectionTexture.isCube) {
  18317. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  18318. }
  18319. else {
  18320. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  18321. }
  18322. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  18323. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  18324. }
  18325. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  18326. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  18327. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  18328. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  18329. }
  18330. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  18331. this._effect.setTexture("specularSampler", this.specularTexture);
  18332. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  18333. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  18334. }
  18335. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  18336. this._effect.setTexture("bumpSampler", this.bumpTexture);
  18337. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  18338. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  18339. }
  18340. // Clip plane
  18341. if (scene.clipPlane) {
  18342. var clipPlane = scene.clipPlane;
  18343. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  18344. }
  18345. // Point size
  18346. if (this.pointsCloud) {
  18347. this._effect.setFloat("pointSize", this.pointSize);
  18348. }
  18349. // Colors
  18350. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  18351. // Scaling down color according to emissive
  18352. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  18353. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  18354. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  18355. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  18356. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  18357. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  18358. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  18359. }
  18360. // Scaling down color according to emissive
  18361. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  18362. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  18363. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  18364. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  18365. if (scene.lightsEnabled) {
  18366. var lightIndex = 0;
  18367. for (var index = 0; index < scene.lights.length; index++) {
  18368. var light = scene.lights[index];
  18369. if (!light.isEnabled()) {
  18370. continue;
  18371. }
  18372. if (!light.canAffectMesh(mesh)) {
  18373. continue;
  18374. }
  18375. if (light instanceof BABYLON.PointLight) {
  18376. // Point Light
  18377. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  18378. }
  18379. else if (light instanceof BABYLON.DirectionalLight) {
  18380. // Directional Light
  18381. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  18382. }
  18383. else if (light instanceof BABYLON.SpotLight) {
  18384. // Spot Light
  18385. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  18386. }
  18387. else if (light instanceof BABYLON.HemisphericLight) {
  18388. // Hemispheric Light
  18389. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  18390. }
  18391. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  18392. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  18393. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  18394. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  18395. // Shadows
  18396. if (scene.shadowsEnabled) {
  18397. var shadowGenerator = light.getShadowGenerator();
  18398. if (mesh.receiveShadows && shadowGenerator) {
  18399. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  18400. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  18401. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  18402. }
  18403. }
  18404. lightIndex++;
  18405. if (lightIndex === maxSimultaneousLights)
  18406. break;
  18407. }
  18408. }
  18409. // View
  18410. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  18411. this._effect.setMatrix("view", scene.getViewMatrix());
  18412. }
  18413. // Fog
  18414. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  18415. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  18416. this._effect.setColor3("vFogColor", scene.fogColor);
  18417. }
  18418. _super.prototype.bind.call(this, world, mesh);
  18419. };
  18420. StandardMaterial.prototype.getAnimatables = function () {
  18421. var results = [];
  18422. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  18423. results.push(this.diffuseTexture);
  18424. }
  18425. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  18426. results.push(this.ambientTexture);
  18427. }
  18428. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  18429. results.push(this.opacityTexture);
  18430. }
  18431. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  18432. results.push(this.reflectionTexture);
  18433. }
  18434. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  18435. results.push(this.emissiveTexture);
  18436. }
  18437. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  18438. results.push(this.specularTexture);
  18439. }
  18440. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  18441. results.push(this.bumpTexture);
  18442. }
  18443. return results;
  18444. };
  18445. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  18446. if (this.diffuseTexture) {
  18447. this.diffuseTexture.dispose();
  18448. }
  18449. if (this.ambientTexture) {
  18450. this.ambientTexture.dispose();
  18451. }
  18452. if (this.opacityTexture) {
  18453. this.opacityTexture.dispose();
  18454. }
  18455. if (this.reflectionTexture) {
  18456. this.reflectionTexture.dispose();
  18457. }
  18458. if (this.emissiveTexture) {
  18459. this.emissiveTexture.dispose();
  18460. }
  18461. if (this.specularTexture) {
  18462. this.specularTexture.dispose();
  18463. }
  18464. if (this.bumpTexture) {
  18465. this.bumpTexture.dispose();
  18466. }
  18467. _super.prototype.dispose.call(this, forceDisposeEffect);
  18468. };
  18469. StandardMaterial.prototype.clone = function (name) {
  18470. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  18471. // Base material
  18472. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  18473. newStandardMaterial.alpha = this.alpha;
  18474. newStandardMaterial.fillMode = this.fillMode;
  18475. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  18476. // Standard material
  18477. if (this.diffuseTexture && this.diffuseTexture.clone) {
  18478. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  18479. }
  18480. if (this.ambientTexture && this.ambientTexture.clone) {
  18481. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  18482. }
  18483. if (this.opacityTexture && this.opacityTexture.clone) {
  18484. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  18485. }
  18486. if (this.reflectionTexture && this.reflectionTexture.clone) {
  18487. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  18488. }
  18489. if (this.emissiveTexture && this.emissiveTexture.clone) {
  18490. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  18491. }
  18492. if (this.specularTexture && this.specularTexture.clone) {
  18493. newStandardMaterial.specularTexture = this.specularTexture.clone();
  18494. }
  18495. if (this.bumpTexture && this.bumpTexture.clone) {
  18496. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  18497. }
  18498. newStandardMaterial.ambientColor = this.ambientColor.clone();
  18499. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  18500. newStandardMaterial.specularColor = this.specularColor.clone();
  18501. newStandardMaterial.specularPower = this.specularPower;
  18502. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  18503. return newStandardMaterial;
  18504. };
  18505. // Statics
  18506. // Flags used to enable or disable a type of texture for all Standard Materials
  18507. StandardMaterial.DiffuseTextureEnabled = true;
  18508. StandardMaterial.AmbientTextureEnabled = true;
  18509. StandardMaterial.OpacityTextureEnabled = true;
  18510. StandardMaterial.ReflectionTextureEnabled = true;
  18511. StandardMaterial.EmissiveTextureEnabled = true;
  18512. StandardMaterial.SpecularTextureEnabled = true;
  18513. StandardMaterial.BumpTextureEnabled = true;
  18514. StandardMaterial.FresnelEnabled = true;
  18515. return StandardMaterial;
  18516. })(BABYLON.Material);
  18517. BABYLON.StandardMaterial = StandardMaterial;
  18518. })(BABYLON || (BABYLON = {}));
  18519. //# sourceMappingURL=babylon.standardMaterial.js.map
  18520. var BABYLON;
  18521. (function (BABYLON) {
  18522. var MultiMaterial = (function (_super) {
  18523. __extends(MultiMaterial, _super);
  18524. function MultiMaterial(name, scene) {
  18525. _super.call(this, name, scene, true);
  18526. this.subMaterials = new Array();
  18527. scene.multiMaterials.push(this);
  18528. }
  18529. // Properties
  18530. MultiMaterial.prototype.getSubMaterial = function (index) {
  18531. if (index < 0 || index >= this.subMaterials.length) {
  18532. return this.getScene().defaultMaterial;
  18533. }
  18534. return this.subMaterials[index];
  18535. };
  18536. // Methods
  18537. MultiMaterial.prototype.isReady = function (mesh) {
  18538. for (var index = 0; index < this.subMaterials.length; index++) {
  18539. var subMaterial = this.subMaterials[index];
  18540. if (subMaterial) {
  18541. if (!this.subMaterials[index].isReady(mesh)) {
  18542. return false;
  18543. }
  18544. }
  18545. }
  18546. return true;
  18547. };
  18548. MultiMaterial.prototype.clone = function (name) {
  18549. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  18550. for (var index = 0; index < this.subMaterials.length; index++) {
  18551. var subMaterial = this.subMaterials[index];
  18552. newMultiMaterial.subMaterials.push(subMaterial);
  18553. }
  18554. return newMultiMaterial;
  18555. };
  18556. return MultiMaterial;
  18557. })(BABYLON.Material);
  18558. BABYLON.MultiMaterial = MultiMaterial;
  18559. })(BABYLON || (BABYLON = {}));
  18560. //# sourceMappingURL=babylon.multiMaterial.js.map
  18561. var BABYLON;
  18562. (function (BABYLON) {
  18563. var SceneLoader = (function () {
  18564. function SceneLoader() {
  18565. }
  18566. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  18567. get: function () {
  18568. return SceneLoader._ForceFullSceneLoadingForIncremental;
  18569. },
  18570. set: function (value) {
  18571. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  18572. },
  18573. enumerable: true,
  18574. configurable: true
  18575. });
  18576. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  18577. get: function () {
  18578. return SceneLoader._ShowLoadingScreen;
  18579. },
  18580. set: function (value) {
  18581. SceneLoader._ShowLoadingScreen = value;
  18582. },
  18583. enumerable: true,
  18584. configurable: true
  18585. });
  18586. SceneLoader._getPluginForFilename = function (sceneFilename) {
  18587. var dotPosition = sceneFilename.lastIndexOf(".");
  18588. var queryStringPosition = sceneFilename.indexOf("?");
  18589. if (queryStringPosition === -1) {
  18590. queryStringPosition = sceneFilename.length;
  18591. }
  18592. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  18593. for (var index = 0; index < this._registeredPlugins.length; index++) {
  18594. var plugin = this._registeredPlugins[index];
  18595. if (plugin.extensions.indexOf(extension) !== -1) {
  18596. return plugin;
  18597. }
  18598. }
  18599. return this._registeredPlugins[this._registeredPlugins.length - 1];
  18600. };
  18601. // Public functions
  18602. SceneLoader.RegisterPlugin = function (plugin) {
  18603. plugin.extensions = plugin.extensions.toLowerCase();
  18604. SceneLoader._registeredPlugins.push(plugin);
  18605. };
  18606. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18607. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18608. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18609. return;
  18610. }
  18611. var loadingToken = {};
  18612. scene._addPendingData(loadingToken);
  18613. var manifestChecked = function (success) {
  18614. scene.database = database;
  18615. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  18616. var importMeshFromData = function (data) {
  18617. var meshes = [];
  18618. var particleSystems = [];
  18619. var skeletons = [];
  18620. try {
  18621. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  18622. if (onerror) {
  18623. onerror(scene, 'unable to load the scene');
  18624. }
  18625. scene._removePendingData(loadingToken);
  18626. return;
  18627. }
  18628. }
  18629. catch (e) {
  18630. if (onerror) {
  18631. onerror(scene, e);
  18632. }
  18633. scene._removePendingData(loadingToken);
  18634. return;
  18635. }
  18636. if (onsuccess) {
  18637. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  18638. onsuccess(meshes, particleSystems, skeletons);
  18639. scene._removePendingData(loadingToken);
  18640. }
  18641. };
  18642. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18643. // Direct load
  18644. importMeshFromData(sceneFilename.substr(5));
  18645. return;
  18646. }
  18647. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  18648. importMeshFromData(data);
  18649. }, progressCallBack, database);
  18650. };
  18651. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18652. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18653. };
  18654. /**
  18655. * Load a scene
  18656. * @param rootUrl a string that defines the root url for scene and resources
  18657. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18658. * @param engine is the instance of BABYLON.Engine to use to create the scene
  18659. */
  18660. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  18661. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  18662. };
  18663. /**
  18664. * Append a scene
  18665. * @param rootUrl a string that defines the root url for scene and resources
  18666. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18667. * @param scene is the instance of BABYLON.Scene to append to
  18668. */
  18669. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18670. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18671. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18672. return;
  18673. }
  18674. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  18675. var database;
  18676. var loadingToken = {};
  18677. scene._addPendingData(loadingToken);
  18678. if (SceneLoader.ShowLoadingScreen) {
  18679. scene.getEngine().displayLoadingUI();
  18680. }
  18681. var loadSceneFromData = function (data) {
  18682. scene.database = database;
  18683. if (!plugin.load(scene, data, rootUrl)) {
  18684. if (onerror) {
  18685. onerror(scene);
  18686. }
  18687. scene._removePendingData(loadingToken);
  18688. scene.getEngine().hideLoadingUI();
  18689. return;
  18690. }
  18691. if (onsuccess) {
  18692. onsuccess(scene);
  18693. }
  18694. scene._removePendingData(loadingToken);
  18695. if (SceneLoader.ShowLoadingScreen) {
  18696. scene.executeWhenReady(function () {
  18697. scene.getEngine().hideLoadingUI();
  18698. });
  18699. }
  18700. };
  18701. var manifestChecked = function (success) {
  18702. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  18703. };
  18704. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18705. // Direct load
  18706. loadSceneFromData(sceneFilename.substr(5));
  18707. return;
  18708. }
  18709. if (rootUrl.indexOf("file:") === -1) {
  18710. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18711. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18712. }
  18713. else {
  18714. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  18715. }
  18716. };
  18717. // Flags
  18718. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  18719. SceneLoader._ShowLoadingScreen = true;
  18720. // Members
  18721. SceneLoader._registeredPlugins = new Array();
  18722. return SceneLoader;
  18723. })();
  18724. BABYLON.SceneLoader = SceneLoader;
  18725. ;
  18726. })(BABYLON || (BABYLON = {}));
  18727. //# sourceMappingURL=babylon.sceneLoader.js.map
  18728. var BABYLON;
  18729. (function (BABYLON) {
  18730. var Internals;
  18731. (function (Internals) {
  18732. var checkColors4 = function (colors, count) {
  18733. // Check if color3 was used
  18734. if (colors.length === count * 3) {
  18735. var colors4 = [];
  18736. for (var index = 0; index < colors.length; index += 3) {
  18737. var newIndex = (index / 3) * 4;
  18738. colors4[newIndex] = colors[index];
  18739. colors4[newIndex + 1] = colors[index + 1];
  18740. colors4[newIndex + 2] = colors[index + 2];
  18741. colors4[newIndex + 3] = 1.0;
  18742. }
  18743. return colors4;
  18744. }
  18745. return colors;
  18746. };
  18747. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  18748. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  18749. texture.name = parsedTexture.name;
  18750. texture.hasAlpha = parsedTexture.hasAlpha;
  18751. texture.level = parsedTexture.level;
  18752. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18753. return texture;
  18754. };
  18755. var loadTexture = function (rootUrl, parsedTexture, scene) {
  18756. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18757. return null;
  18758. }
  18759. if (parsedTexture.isCube) {
  18760. return loadCubeTexture(rootUrl, parsedTexture, scene);
  18761. }
  18762. var texture;
  18763. if (parsedTexture.mirrorPlane) {
  18764. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18765. texture._waitingRenderList = parsedTexture.renderList;
  18766. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18767. }
  18768. else if (parsedTexture.isRenderTarget) {
  18769. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18770. texture._waitingRenderList = parsedTexture.renderList;
  18771. }
  18772. else {
  18773. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  18774. }
  18775. texture.name = parsedTexture.name;
  18776. texture.hasAlpha = parsedTexture.hasAlpha;
  18777. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  18778. texture.level = parsedTexture.level;
  18779. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  18780. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18781. texture.uOffset = parsedTexture.uOffset;
  18782. texture.vOffset = parsedTexture.vOffset;
  18783. texture.uScale = parsedTexture.uScale;
  18784. texture.vScale = parsedTexture.vScale;
  18785. texture.uAng = parsedTexture.uAng;
  18786. texture.vAng = parsedTexture.vAng;
  18787. texture.wAng = parsedTexture.wAng;
  18788. texture.wrapU = parsedTexture.wrapU;
  18789. texture.wrapV = parsedTexture.wrapV;
  18790. // Animations
  18791. if (parsedTexture.animations) {
  18792. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18793. var parsedAnimation = parsedTexture.animations[animationIndex];
  18794. texture.animations.push(parseAnimation(parsedAnimation));
  18795. }
  18796. }
  18797. return texture;
  18798. };
  18799. var parseSkeleton = function (parsedSkeleton, scene) {
  18800. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  18801. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  18802. var parsedBone = parsedSkeleton.bones[index];
  18803. var parentBone = null;
  18804. if (parsedBone.parentBoneIndex > -1) {
  18805. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  18806. }
  18807. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  18808. if (parsedBone.animation) {
  18809. bone.animations.push(parseAnimation(parsedBone.animation));
  18810. }
  18811. }
  18812. return skeleton;
  18813. };
  18814. var parseFresnelParameters = function (parsedFresnelParameters) {
  18815. var fresnelParameters = new BABYLON.FresnelParameters();
  18816. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18817. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18818. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18819. fresnelParameters.bias = parsedFresnelParameters.bias;
  18820. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18821. return fresnelParameters;
  18822. };
  18823. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  18824. var material;
  18825. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  18826. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  18827. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  18828. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  18829. material.specularPower = parsedMaterial.specularPower;
  18830. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  18831. material.alpha = parsedMaterial.alpha;
  18832. material.id = parsedMaterial.id;
  18833. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  18834. material.backFaceCulling = parsedMaterial.backFaceCulling;
  18835. material.wireframe = parsedMaterial.wireframe;
  18836. if (parsedMaterial.diffuseTexture) {
  18837. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  18838. }
  18839. if (parsedMaterial.diffuseFresnelParameters) {
  18840. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  18841. }
  18842. if (parsedMaterial.ambientTexture) {
  18843. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  18844. }
  18845. if (parsedMaterial.opacityTexture) {
  18846. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  18847. }
  18848. if (parsedMaterial.opacityFresnelParameters) {
  18849. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  18850. }
  18851. if (parsedMaterial.reflectionTexture) {
  18852. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  18853. }
  18854. if (parsedMaterial.reflectionFresnelParameters) {
  18855. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  18856. }
  18857. if (parsedMaterial.emissiveTexture) {
  18858. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  18859. }
  18860. if (parsedMaterial.emissiveFresnelParameters) {
  18861. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  18862. }
  18863. if (parsedMaterial.specularTexture) {
  18864. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  18865. }
  18866. if (parsedMaterial.bumpTexture) {
  18867. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  18868. }
  18869. return material;
  18870. };
  18871. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  18872. for (var index = 0; index < parsedData.materials.length; index++) {
  18873. var parsedMaterial = parsedData.materials[index];
  18874. if (parsedMaterial.id === id) {
  18875. return parseMaterial(parsedMaterial, scene, rootUrl);
  18876. }
  18877. }
  18878. return null;
  18879. };
  18880. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  18881. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18882. multiMaterial.id = parsedMultiMaterial.id;
  18883. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18884. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18885. var subMatId = parsedMultiMaterial.materials[matIndex];
  18886. if (subMatId) {
  18887. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18888. }
  18889. else {
  18890. multiMaterial.subMaterials.push(null);
  18891. }
  18892. }
  18893. return multiMaterial;
  18894. };
  18895. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  18896. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  18897. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  18898. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  18899. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  18900. var parsedFlare = parsedLensFlareSystem.flares[index];
  18901. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  18902. }
  18903. return lensFlareSystem;
  18904. };
  18905. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  18906. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  18907. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  18908. if (parsedParticleSystem.textureName) {
  18909. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  18910. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  18911. }
  18912. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  18913. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  18914. particleSystem.minSize = parsedParticleSystem.minSize;
  18915. particleSystem.maxSize = parsedParticleSystem.maxSize;
  18916. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  18917. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  18918. particleSystem.emitter = emitter;
  18919. particleSystem.emitRate = parsedParticleSystem.emitRate;
  18920. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  18921. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  18922. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  18923. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  18924. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  18925. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  18926. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  18927. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  18928. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  18929. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  18930. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  18931. particleSystem.blendMode = parsedParticleSystem.blendMode;
  18932. particleSystem.start();
  18933. return particleSystem;
  18934. };
  18935. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  18936. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  18937. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  18938. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  18939. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  18940. shadowGenerator.getShadowMap().renderList.push(mesh);
  18941. }
  18942. if (parsedShadowGenerator.usePoissonSampling) {
  18943. shadowGenerator.usePoissonSampling = true;
  18944. }
  18945. else if (parsedShadowGenerator.useVarianceShadowMap) {
  18946. shadowGenerator.useVarianceShadowMap = true;
  18947. }
  18948. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  18949. shadowGenerator.useBlurVarianceShadowMap = true;
  18950. if (parsedShadowGenerator.blurScale) {
  18951. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  18952. }
  18953. if (parsedShadowGenerator.blurBoxOffset) {
  18954. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  18955. }
  18956. }
  18957. if (parsedShadowGenerator.bias !== undefined) {
  18958. shadowGenerator.bias = parsedShadowGenerator.bias;
  18959. }
  18960. return shadowGenerator;
  18961. };
  18962. var parseAnimation = function (parsedAnimation) {
  18963. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  18964. var dataType = parsedAnimation.dataType;
  18965. var keys = [];
  18966. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  18967. var key = parsedAnimation.keys[index];
  18968. var data;
  18969. switch (dataType) {
  18970. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18971. data = key.values[0];
  18972. break;
  18973. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18974. data = BABYLON.Quaternion.FromArray(key.values);
  18975. break;
  18976. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18977. data = BABYLON.Matrix.FromArray(key.values);
  18978. break;
  18979. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18980. default:
  18981. data = BABYLON.Vector3.FromArray(key.values);
  18982. break;
  18983. }
  18984. keys.push({
  18985. frame: key.frame,
  18986. value: data
  18987. });
  18988. }
  18989. animation.setKeys(keys);
  18990. return animation;
  18991. };
  18992. var parseLight = function (parsedLight, scene) {
  18993. var light;
  18994. switch (parsedLight.type) {
  18995. case 0:
  18996. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  18997. break;
  18998. case 1:
  18999. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19000. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19001. break;
  19002. case 2:
  19003. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19004. break;
  19005. case 3:
  19006. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19007. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19008. break;
  19009. }
  19010. light.id = parsedLight.id;
  19011. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19012. if (parsedLight.intensity !== undefined) {
  19013. light.intensity = parsedLight.intensity;
  19014. }
  19015. if (parsedLight.range) {
  19016. light.range = parsedLight.range;
  19017. }
  19018. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19019. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19020. if (parsedLight.excludedMeshesIds) {
  19021. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19022. }
  19023. // Parent
  19024. if (parsedLight.parentId) {
  19025. light._waitingParentId = parsedLight.parentId;
  19026. }
  19027. if (parsedLight.includedOnlyMeshesIds) {
  19028. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19029. }
  19030. // Animations
  19031. if (parsedLight.animations) {
  19032. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19033. var parsedAnimation = parsedLight.animations[animationIndex];
  19034. light.animations.push(parseAnimation(parsedAnimation));
  19035. }
  19036. }
  19037. if (parsedLight.autoAnimate) {
  19038. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19039. }
  19040. };
  19041. var parseCamera = function (parsedCamera, scene) {
  19042. var camera;
  19043. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19044. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19045. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19046. var alpha = parsedCamera.alpha;
  19047. var beta = parsedCamera.beta;
  19048. var radius = parsedCamera.radius;
  19049. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19050. var interaxial_distance = parsedCamera.interaxial_distance;
  19051. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, interaxial_distance, scene);
  19052. }
  19053. else {
  19054. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19055. }
  19056. }
  19057. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19058. interaxial_distance = parsedCamera.interaxial_distance;
  19059. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, interaxial_distance, scene);
  19060. }
  19061. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19062. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19063. }
  19064. else if (parsedCamera.type === "FollowCamera") {
  19065. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19066. camera.heightOffset = parsedCamera.heightOffset;
  19067. camera.radius = parsedCamera.radius;
  19068. camera.rotationOffset = parsedCamera.rotationOffset;
  19069. if (lockedTargetMesh)
  19070. camera.target = lockedTargetMesh;
  19071. }
  19072. else if (parsedCamera.type === "GamepadCamera") {
  19073. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19074. }
  19075. else if (parsedCamera.type === "TouchCamera") {
  19076. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19077. }
  19078. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19079. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19080. }
  19081. else if (parsedCamera.type === "WebVRFreeCamera") {
  19082. camera = new BABYLON.WebVRFreeCamera(parsedCamera.name, position, scene);
  19083. }
  19084. else if (parsedCamera.type === "VRDeviceOrientationFreeCamera") {
  19085. camera = new BABYLON.VRDeviceOrientationFreeCamera(parsedCamera.name, position, scene);
  19086. }
  19087. else {
  19088. // Free Camera is the default value
  19089. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19090. }
  19091. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19092. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19093. camera.lockedTarget = lockedTargetMesh;
  19094. }
  19095. camera.id = parsedCamera.id;
  19096. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19097. // Parent
  19098. if (parsedCamera.parentId) {
  19099. camera._waitingParentId = parsedCamera.parentId;
  19100. }
  19101. // Target
  19102. if (parsedCamera.target) {
  19103. if (camera.setTarget) {
  19104. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19105. }
  19106. else {
  19107. //For ArcRotate
  19108. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19109. }
  19110. }
  19111. else {
  19112. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19113. }
  19114. camera.fov = parsedCamera.fov;
  19115. camera.minZ = parsedCamera.minZ;
  19116. camera.maxZ = parsedCamera.maxZ;
  19117. camera.speed = parsedCamera.speed;
  19118. camera.inertia = parsedCamera.inertia;
  19119. camera.checkCollisions = parsedCamera.checkCollisions;
  19120. camera.applyGravity = parsedCamera.applyGravity;
  19121. if (parsedCamera.ellipsoid) {
  19122. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19123. }
  19124. // Animations
  19125. if (parsedCamera.animations) {
  19126. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19127. var parsedAnimation = parsedCamera.animations[animationIndex];
  19128. camera.animations.push(parseAnimation(parsedAnimation));
  19129. }
  19130. }
  19131. if (parsedCamera.autoAnimate) {
  19132. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19133. }
  19134. // Layer Mask
  19135. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19136. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19137. }
  19138. else {
  19139. camera.layerMask = 0xFFFFFFFF;
  19140. }
  19141. return camera;
  19142. };
  19143. var parseGeometry = function (parsedGeometry, scene) {
  19144. var id = parsedGeometry.id;
  19145. return scene.getGeometryByID(id);
  19146. };
  19147. var parseBox = function (parsedBox, scene) {
  19148. if (parseGeometry(parsedBox, scene)) {
  19149. return null; // null since geometry could be something else than a box...
  19150. }
  19151. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19152. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19153. scene.pushGeometry(box, true);
  19154. return box;
  19155. };
  19156. var parseSphere = function (parsedSphere, scene) {
  19157. if (parseGeometry(parsedSphere, scene)) {
  19158. return null; // null since geometry could be something else than a sphere...
  19159. }
  19160. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19161. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19162. scene.pushGeometry(sphere, true);
  19163. return sphere;
  19164. };
  19165. var parseCylinder = function (parsedCylinder, scene) {
  19166. if (parseGeometry(parsedCylinder, scene)) {
  19167. return null; // null since geometry could be something else than a cylinder...
  19168. }
  19169. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19170. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19171. scene.pushGeometry(cylinder, true);
  19172. return cylinder;
  19173. };
  19174. var parseTorus = function (parsedTorus, scene) {
  19175. if (parseGeometry(parsedTorus, scene)) {
  19176. return null; // null since geometry could be something else than a torus...
  19177. }
  19178. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19179. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19180. scene.pushGeometry(torus, true);
  19181. return torus;
  19182. };
  19183. var parseGround = function (parsedGround, scene) {
  19184. if (parseGeometry(parsedGround, scene)) {
  19185. return null; // null since geometry could be something else than a ground...
  19186. }
  19187. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19188. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19189. scene.pushGeometry(ground, true);
  19190. return ground;
  19191. };
  19192. var parsePlane = function (parsedPlane, scene) {
  19193. if (parseGeometry(parsedPlane, scene)) {
  19194. return null; // null since geometry could be something else than a plane...
  19195. }
  19196. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19197. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19198. scene.pushGeometry(plane, true);
  19199. return plane;
  19200. };
  19201. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19202. if (parseGeometry(parsedTorusKnot, scene)) {
  19203. return null; // null since geometry could be something else than a torusKnot...
  19204. }
  19205. 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);
  19206. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19207. scene.pushGeometry(torusKnot, true);
  19208. return torusKnot;
  19209. };
  19210. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19211. if (parseGeometry(parsedVertexData, scene)) {
  19212. return null; // null since geometry could be a primitive
  19213. }
  19214. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19215. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19216. if (parsedVertexData.delayLoadingFile) {
  19217. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19218. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19219. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19220. geometry._delayInfo = [];
  19221. if (parsedVertexData.hasUVs) {
  19222. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19223. }
  19224. if (parsedVertexData.hasUVs2) {
  19225. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19226. }
  19227. if (parsedVertexData.hasColors) {
  19228. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19229. }
  19230. if (parsedVertexData.hasMatricesIndices) {
  19231. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19232. }
  19233. if (parsedVertexData.hasMatricesWeights) {
  19234. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19235. }
  19236. geometry._delayLoadingFunction = importVertexData;
  19237. }
  19238. else {
  19239. importVertexData(parsedVertexData, geometry);
  19240. }
  19241. scene.pushGeometry(geometry, true);
  19242. return geometry;
  19243. };
  19244. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19245. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19246. mesh.id = parsedMesh.id;
  19247. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19248. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19249. if (parsedMesh.rotationQuaternion) {
  19250. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19251. }
  19252. else if (parsedMesh.rotation) {
  19253. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19254. }
  19255. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19256. if (parsedMesh.localMatrix) {
  19257. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19258. }
  19259. else if (parsedMesh.pivotMatrix) {
  19260. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19261. }
  19262. mesh.setEnabled(parsedMesh.isEnabled);
  19263. mesh.isVisible = parsedMesh.isVisible;
  19264. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19265. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19266. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19267. if (parsedMesh.applyFog !== undefined) {
  19268. mesh.applyFog = parsedMesh.applyFog;
  19269. }
  19270. if (parsedMesh.pickable !== undefined) {
  19271. mesh.isPickable = parsedMesh.pickable;
  19272. }
  19273. if (parsedMesh.alphaIndex !== undefined) {
  19274. mesh.alphaIndex = parsedMesh.alphaIndex;
  19275. }
  19276. mesh.receiveShadows = parsedMesh.receiveShadows;
  19277. mesh.billboardMode = parsedMesh.billboardMode;
  19278. if (parsedMesh.visibility !== undefined) {
  19279. mesh.visibility = parsedMesh.visibility;
  19280. }
  19281. mesh.checkCollisions = parsedMesh.checkCollisions;
  19282. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19283. // Parent
  19284. if (parsedMesh.parentId) {
  19285. mesh._waitingParentId = parsedMesh.parentId;
  19286. }
  19287. // Actions
  19288. if (parsedMesh.actions !== undefined) {
  19289. mesh._waitingActions = parsedMesh.actions;
  19290. }
  19291. // Geometry
  19292. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19293. if (parsedMesh.delayLoadingFile) {
  19294. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19295. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19296. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19297. if (parsedMesh._binaryInfo) {
  19298. mesh._binaryInfo = parsedMesh._binaryInfo;
  19299. }
  19300. mesh._delayInfo = [];
  19301. if (parsedMesh.hasUVs) {
  19302. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19303. }
  19304. if (parsedMesh.hasUVs2) {
  19305. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19306. }
  19307. if (parsedMesh.hasColors) {
  19308. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19309. }
  19310. if (parsedMesh.hasMatricesIndices) {
  19311. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19312. }
  19313. if (parsedMesh.hasMatricesWeights) {
  19314. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19315. }
  19316. mesh._delayLoadingFunction = importGeometry;
  19317. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19318. mesh._checkDelayState();
  19319. }
  19320. }
  19321. else {
  19322. importGeometry(parsedMesh, mesh);
  19323. }
  19324. // Material
  19325. if (parsedMesh.materialId) {
  19326. mesh.setMaterialByID(parsedMesh.materialId);
  19327. }
  19328. else {
  19329. mesh.material = null;
  19330. }
  19331. // Skeleton
  19332. if (parsedMesh.skeletonId > -1) {
  19333. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19334. }
  19335. // Physics
  19336. if (parsedMesh.physicsImpostor) {
  19337. if (!scene.isPhysicsEnabled()) {
  19338. scene.enablePhysics();
  19339. }
  19340. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  19341. }
  19342. // Animations
  19343. if (parsedMesh.animations) {
  19344. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19345. var parsedAnimation = parsedMesh.animations[animationIndex];
  19346. mesh.animations.push(parseAnimation(parsedAnimation));
  19347. }
  19348. }
  19349. if (parsedMesh.autoAnimate) {
  19350. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  19351. }
  19352. // Layer Mask
  19353. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19354. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19355. }
  19356. else {
  19357. mesh.layerMask = 0xFFFFFFFF;
  19358. }
  19359. // Instances
  19360. if (parsedMesh.instances) {
  19361. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19362. var parsedInstance = parsedMesh.instances[index];
  19363. var instance = mesh.createInstance(parsedInstance.name);
  19364. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19365. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19366. if (parsedInstance.rotationQuaternion) {
  19367. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19368. }
  19369. else if (parsedInstance.rotation) {
  19370. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19371. }
  19372. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19373. instance.checkCollisions = mesh.checkCollisions;
  19374. if (parsedMesh.animations) {
  19375. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19376. parsedAnimation = parsedMesh.animations[animationIndex];
  19377. instance.animations.push(parseAnimation(parsedAnimation));
  19378. }
  19379. }
  19380. }
  19381. }
  19382. return mesh;
  19383. };
  19384. var parseActions = function (parsedActions, object, scene) {
  19385. var actionManager = new BABYLON.ActionManager(scene);
  19386. if (object === null)
  19387. scene.actionManager = actionManager;
  19388. else
  19389. object.actionManager = actionManager;
  19390. // instanciate a new object
  19391. var instanciate = function (name, params) {
  19392. var newInstance = Object.create(BABYLON[name].prototype);
  19393. newInstance.constructor.apply(newInstance, params);
  19394. return newInstance;
  19395. };
  19396. var parseParameter = function (name, value, target, propertyPath) {
  19397. if (propertyPath === null) {
  19398. // String, boolean or float
  19399. var floatValue = parseFloat(value);
  19400. if (value === "true" || value === "false")
  19401. return value === "true";
  19402. else
  19403. return isNaN(floatValue) ? value : floatValue;
  19404. }
  19405. var effectiveTarget = propertyPath.split(".");
  19406. var values = value.split(",");
  19407. // Get effective Target
  19408. for (var i = 0; i < effectiveTarget.length; i++) {
  19409. target = target[effectiveTarget[i]];
  19410. }
  19411. // Return appropriate value with its type
  19412. if (typeof (target) === "boolean")
  19413. return values[0] === "true";
  19414. if (typeof (target) === "string")
  19415. return values[0];
  19416. // Parameters with multiple values such as Vector3 etc.
  19417. var split = new Array();
  19418. for (var i = 0; i < values.length; i++)
  19419. split.push(parseFloat(values[i]));
  19420. if (target instanceof BABYLON.Vector3)
  19421. return BABYLON.Vector3.FromArray(split);
  19422. if (target instanceof BABYLON.Vector4)
  19423. return BABYLON.Vector4.FromArray(split);
  19424. if (target instanceof BABYLON.Color3)
  19425. return BABYLON.Color3.FromArray(split);
  19426. if (target instanceof BABYLON.Color4)
  19427. return BABYLON.Color4.FromArray(split);
  19428. return parseFloat(values[0]);
  19429. };
  19430. // traverse graph per trigger
  19431. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  19432. if (combineArray === void 0) { combineArray = null; }
  19433. if (parsedAction.detached)
  19434. return;
  19435. var parameters = new Array();
  19436. var target = null;
  19437. var propertyPath = null;
  19438. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  19439. // Parameters
  19440. if (parsedAction.type === 2)
  19441. parameters.push(actionManager);
  19442. else
  19443. parameters.push(trigger);
  19444. if (combine) {
  19445. var actions = new Array();
  19446. for (var j = 0; j < parsedAction.combine.length; j++) {
  19447. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  19448. }
  19449. parameters.push(actions);
  19450. }
  19451. else {
  19452. for (var i = 0; i < parsedAction.properties.length; i++) {
  19453. var value = parsedAction.properties[i].value;
  19454. var name = parsedAction.properties[i].name;
  19455. var targetType = parsedAction.properties[i].targetType;
  19456. if (name === "target")
  19457. if (targetType !== null && targetType === "SceneProperties")
  19458. value = target = scene;
  19459. else
  19460. value = target = scene.getNodeByName(value);
  19461. else if (name === "parent")
  19462. value = scene.getNodeByName(value);
  19463. else if (name === "sound")
  19464. value = scene.getSoundByName(value);
  19465. else if (name !== "propertyPath") {
  19466. if (parsedAction.type === 2 && name === "operator")
  19467. value = BABYLON.ValueCondition[value];
  19468. else
  19469. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  19470. }
  19471. else {
  19472. propertyPath = value;
  19473. }
  19474. parameters.push(value);
  19475. }
  19476. }
  19477. if (combineArray === null) {
  19478. parameters.push(condition);
  19479. }
  19480. else {
  19481. parameters.push(null);
  19482. }
  19483. // If interpolate value action
  19484. if (parsedAction.name === "InterpolateValueAction") {
  19485. var param = parameters[parameters.length - 2];
  19486. parameters[parameters.length - 1] = param;
  19487. parameters[parameters.length - 2] = condition;
  19488. }
  19489. // Action or condition(s) and not CombineAction
  19490. var newAction = instanciate(parsedAction.name, parameters);
  19491. if (combineArray === null) {
  19492. if (newAction instanceof BABYLON.Condition) {
  19493. condition = newAction;
  19494. newAction = action;
  19495. }
  19496. else {
  19497. condition = null;
  19498. if (action)
  19499. action.then(newAction);
  19500. else
  19501. actionManager.registerAction(newAction);
  19502. }
  19503. }
  19504. else {
  19505. combineArray.push(newAction);
  19506. }
  19507. for (var i = 0; i < parsedAction.children.length; i++)
  19508. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  19509. };
  19510. // triggers
  19511. for (var i = 0; i < parsedActions.children.length; i++) {
  19512. var triggerParams;
  19513. var trigger = parsedActions.children[i];
  19514. if (trigger.properties.length > 0) {
  19515. var param = trigger.properties[0].value;
  19516. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  19517. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  19518. }
  19519. else
  19520. triggerParams = BABYLON.ActionManager[trigger.name];
  19521. for (var j = 0; j < trigger.children.length; j++) {
  19522. if (!trigger.detached)
  19523. traverse(trigger.children[j], triggerParams, null, null);
  19524. }
  19525. }
  19526. };
  19527. var parseSound = function (parsedSound, scene, rootUrl) {
  19528. var soundName = parsedSound.name;
  19529. var soundUrl = rootUrl + soundName;
  19530. var options = {
  19531. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  19532. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  19533. rolloffFactor: parsedSound.rolloffFactor,
  19534. refDistance: parsedSound.refDistance,
  19535. distanceModel: parsedSound.distanceModel,
  19536. playbackRate: parsedSound.playbackRate
  19537. };
  19538. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  19539. scene._addPendingData(newSound);
  19540. if (parsedSound.position) {
  19541. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  19542. newSound.setPosition(soundPosition);
  19543. }
  19544. if (parsedSound.isDirectional) {
  19545. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  19546. if (parsedSound.localDirectionToMesh) {
  19547. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  19548. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  19549. }
  19550. }
  19551. if (parsedSound.connectedMeshId) {
  19552. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  19553. if (connectedMesh) {
  19554. newSound.attachToMesh(connectedMesh);
  19555. }
  19556. }
  19557. };
  19558. var isDescendantOf = function (mesh, names, hierarchyIds) {
  19559. names = (names instanceof Array) ? names : [names];
  19560. for (var i in names) {
  19561. if (mesh.name === names[i]) {
  19562. hierarchyIds.push(mesh.id);
  19563. return true;
  19564. }
  19565. }
  19566. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  19567. hierarchyIds.push(mesh.id);
  19568. return true;
  19569. }
  19570. return false;
  19571. };
  19572. var importVertexData = function (parsedVertexData, geometry) {
  19573. var vertexData = new BABYLON.VertexData();
  19574. // positions
  19575. var positions = parsedVertexData.positions;
  19576. if (positions) {
  19577. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  19578. }
  19579. // normals
  19580. var normals = parsedVertexData.normals;
  19581. if (normals) {
  19582. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  19583. }
  19584. // uvs
  19585. var uvs = parsedVertexData.uvs;
  19586. if (uvs) {
  19587. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  19588. }
  19589. // uv2s
  19590. var uv2s = parsedVertexData.uv2s;
  19591. if (uv2s) {
  19592. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  19593. }
  19594. // colors
  19595. var colors = parsedVertexData.colors;
  19596. if (colors) {
  19597. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  19598. }
  19599. // matricesIndices
  19600. var matricesIndices = parsedVertexData.matricesIndices;
  19601. if (matricesIndices) {
  19602. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  19603. }
  19604. // matricesWeights
  19605. var matricesWeights = parsedVertexData.matricesWeights;
  19606. if (matricesWeights) {
  19607. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  19608. }
  19609. // indices
  19610. var indices = parsedVertexData.indices;
  19611. if (indices) {
  19612. vertexData.indices = indices;
  19613. }
  19614. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  19615. };
  19616. var importGeometry = function (parsedGeometry, mesh) {
  19617. var scene = mesh.getScene();
  19618. // Geometry
  19619. var geometryId = parsedGeometry.geometryId;
  19620. if (geometryId) {
  19621. var geometry = scene.getGeometryByID(geometryId);
  19622. if (geometry) {
  19623. geometry.applyToMesh(mesh);
  19624. }
  19625. }
  19626. else if (parsedGeometry instanceof ArrayBuffer) {
  19627. var binaryInfo = mesh._binaryInfo;
  19628. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  19629. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  19630. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  19631. }
  19632. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  19633. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  19634. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  19635. }
  19636. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  19637. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  19638. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  19639. }
  19640. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  19641. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  19642. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  19643. }
  19644. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  19645. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  19646. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  19647. }
  19648. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  19649. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  19650. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  19651. }
  19652. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  19653. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  19654. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  19655. }
  19656. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  19657. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  19658. mesh.setIndices(indicesData);
  19659. }
  19660. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  19661. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  19662. mesh.subMeshes = [];
  19663. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  19664. var materialIndex = subMeshesData[(i * 5) + 0];
  19665. var verticesStart = subMeshesData[(i * 5) + 1];
  19666. var verticesCount = subMeshesData[(i * 5) + 2];
  19667. var indexStart = subMeshesData[(i * 5) + 3];
  19668. var indexCount = subMeshesData[(i * 5) + 4];
  19669. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  19670. }
  19671. }
  19672. }
  19673. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  19674. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  19675. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  19676. if (parsedGeometry.uvs) {
  19677. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  19678. }
  19679. if (parsedGeometry.uvs2) {
  19680. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  19681. }
  19682. if (parsedGeometry.colors) {
  19683. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  19684. }
  19685. if (parsedGeometry.matricesIndices) {
  19686. if (!parsedGeometry.matricesIndices._isExpanded) {
  19687. var floatIndices = [];
  19688. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  19689. var matricesIndex = parsedGeometry.matricesIndices[i];
  19690. floatIndices.push(matricesIndex & 0x000000FF);
  19691. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  19692. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  19693. floatIndices.push(matricesIndex >> 24);
  19694. }
  19695. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  19696. }
  19697. else {
  19698. delete parsedGeometry.matricesIndices._isExpanded;
  19699. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  19700. }
  19701. }
  19702. if (parsedGeometry.matricesWeights) {
  19703. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  19704. }
  19705. mesh.setIndices(parsedGeometry.indices);
  19706. // SubMeshes
  19707. if (parsedGeometry.subMeshes) {
  19708. mesh.subMeshes = [];
  19709. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  19710. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  19711. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  19712. }
  19713. }
  19714. }
  19715. // Flat shading
  19716. if (mesh._shouldGenerateFlatShading) {
  19717. mesh.convertToFlatShadedMesh();
  19718. delete mesh._shouldGenerateFlatShading;
  19719. }
  19720. // Update
  19721. mesh.computeWorldMatrix(true);
  19722. // Octree
  19723. if (scene._selectionOctree) {
  19724. scene._selectionOctree.addMesh(mesh);
  19725. }
  19726. };
  19727. BABYLON.SceneLoader.RegisterPlugin({
  19728. extensions: ".babylon",
  19729. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  19730. var parsedData = JSON.parse(data);
  19731. var loadedSkeletonsIds = [];
  19732. var loadedMaterialsIds = [];
  19733. var hierarchyIds = [];
  19734. for (var index = 0; index < parsedData.meshes.length; index++) {
  19735. var parsedMesh = parsedData.meshes[index];
  19736. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  19737. if (meshesNames instanceof Array) {
  19738. // Remove found mesh name from list.
  19739. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  19740. }
  19741. //Geometry?
  19742. if (parsedMesh.geometryId) {
  19743. //does the file contain geometries?
  19744. if (parsedData.geometries) {
  19745. //find the correct geometry and add it to the scene
  19746. var found = false;
  19747. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  19748. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  19749. return;
  19750. }
  19751. else {
  19752. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  19753. if (parsedGeometryData.id == parsedMesh.geometryId) {
  19754. switch (geometryType) {
  19755. case "boxes":
  19756. parseBox(parsedGeometryData, scene);
  19757. break;
  19758. case "spheres":
  19759. parseSphere(parsedGeometryData, scene);
  19760. break;
  19761. case "cylinders":
  19762. parseCylinder(parsedGeometryData, scene);
  19763. break;
  19764. case "toruses":
  19765. parseTorus(parsedGeometryData, scene);
  19766. break;
  19767. case "grounds":
  19768. parseGround(parsedGeometryData, scene);
  19769. break;
  19770. case "planes":
  19771. parsePlane(parsedGeometryData, scene);
  19772. break;
  19773. case "torusKnots":
  19774. parseTorusKnot(parsedGeometryData, scene);
  19775. break;
  19776. case "vertexData":
  19777. parseVertexData(parsedGeometryData, scene, rootUrl);
  19778. break;
  19779. }
  19780. found = true;
  19781. }
  19782. });
  19783. }
  19784. });
  19785. }
  19786. }
  19787. // Material ?
  19788. if (parsedMesh.materialId) {
  19789. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  19790. if (!materialFound) {
  19791. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  19792. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  19793. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  19794. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19795. var subMatId = parsedMultiMaterial.materials[matIndex];
  19796. loadedMaterialsIds.push(subMatId);
  19797. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  19798. }
  19799. loadedMaterialsIds.push(parsedMultiMaterial.id);
  19800. parseMultiMaterial(parsedMultiMaterial, scene);
  19801. materialFound = true;
  19802. break;
  19803. }
  19804. }
  19805. }
  19806. if (!materialFound) {
  19807. loadedMaterialsIds.push(parsedMesh.materialId);
  19808. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  19809. }
  19810. }
  19811. // Skeleton ?
  19812. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  19813. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  19814. if (!skeletonAlreadyLoaded) {
  19815. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  19816. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  19817. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  19818. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  19819. loadedSkeletonsIds.push(parsedSkeleton.id);
  19820. }
  19821. }
  19822. }
  19823. }
  19824. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  19825. meshes.push(mesh);
  19826. }
  19827. }
  19828. // Connecting parents
  19829. for (index = 0; index < scene.meshes.length; index++) {
  19830. var currentMesh = scene.meshes[index];
  19831. if (currentMesh._waitingParentId) {
  19832. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  19833. currentMesh._waitingParentId = undefined;
  19834. }
  19835. }
  19836. // Particles
  19837. if (parsedData.particleSystems) {
  19838. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19839. var parsedParticleSystem = parsedData.particleSystems[index];
  19840. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  19841. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  19842. }
  19843. }
  19844. }
  19845. return true;
  19846. },
  19847. load: function (scene, data, rootUrl) {
  19848. var parsedData = JSON.parse(data);
  19849. // Scene
  19850. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  19851. scene.autoClear = parsedData.autoClear;
  19852. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  19853. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  19854. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  19855. // Fog
  19856. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  19857. scene.fogMode = parsedData.fogMode;
  19858. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  19859. scene.fogStart = parsedData.fogStart;
  19860. scene.fogEnd = parsedData.fogEnd;
  19861. scene.fogDensity = parsedData.fogDensity;
  19862. }
  19863. // Lights
  19864. for (var index = 0; index < parsedData.lights.length; index++) {
  19865. var parsedLight = parsedData.lights[index];
  19866. parseLight(parsedLight, scene);
  19867. }
  19868. // Materials
  19869. if (parsedData.materials) {
  19870. for (index = 0; index < parsedData.materials.length; index++) {
  19871. var parsedMaterial = parsedData.materials[index];
  19872. parseMaterial(parsedMaterial, scene, rootUrl);
  19873. }
  19874. }
  19875. if (parsedData.multiMaterials) {
  19876. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  19877. var parsedMultiMaterial = parsedData.multiMaterials[index];
  19878. parseMultiMaterial(parsedMultiMaterial, scene);
  19879. }
  19880. }
  19881. // Skeletons
  19882. if (parsedData.skeletons) {
  19883. for (index = 0; index < parsedData.skeletons.length; index++) {
  19884. var parsedSkeleton = parsedData.skeletons[index];
  19885. parseSkeleton(parsedSkeleton, scene);
  19886. }
  19887. }
  19888. // Geometries
  19889. var geometries = parsedData.geometries;
  19890. if (geometries) {
  19891. // Boxes
  19892. var boxes = geometries.boxes;
  19893. if (boxes) {
  19894. for (index = 0; index < boxes.length; index++) {
  19895. var parsedBox = boxes[index];
  19896. parseBox(parsedBox, scene);
  19897. }
  19898. }
  19899. // Spheres
  19900. var spheres = geometries.spheres;
  19901. if (spheres) {
  19902. for (index = 0; index < spheres.length; index++) {
  19903. var parsedSphere = spheres[index];
  19904. parseSphere(parsedSphere, scene);
  19905. }
  19906. }
  19907. // Cylinders
  19908. var cylinders = geometries.cylinders;
  19909. if (cylinders) {
  19910. for (index = 0; index < cylinders.length; index++) {
  19911. var parsedCylinder = cylinders[index];
  19912. parseCylinder(parsedCylinder, scene);
  19913. }
  19914. }
  19915. // Toruses
  19916. var toruses = geometries.toruses;
  19917. if (toruses) {
  19918. for (index = 0; index < toruses.length; index++) {
  19919. var parsedTorus = toruses[index];
  19920. parseTorus(parsedTorus, scene);
  19921. }
  19922. }
  19923. // Grounds
  19924. var grounds = geometries.grounds;
  19925. if (grounds) {
  19926. for (index = 0; index < grounds.length; index++) {
  19927. var parsedGround = grounds[index];
  19928. parseGround(parsedGround, scene);
  19929. }
  19930. }
  19931. // Planes
  19932. var planes = geometries.planes;
  19933. if (planes) {
  19934. for (index = 0; index < planes.length; index++) {
  19935. var parsedPlane = planes[index];
  19936. parsePlane(parsedPlane, scene);
  19937. }
  19938. }
  19939. // TorusKnots
  19940. var torusKnots = geometries.torusKnots;
  19941. if (torusKnots) {
  19942. for (index = 0; index < torusKnots.length; index++) {
  19943. var parsedTorusKnot = torusKnots[index];
  19944. parseTorusKnot(parsedTorusKnot, scene);
  19945. }
  19946. }
  19947. // VertexData
  19948. var vertexData = geometries.vertexData;
  19949. if (vertexData) {
  19950. for (index = 0; index < vertexData.length; index++) {
  19951. var parsedVertexData = vertexData[index];
  19952. parseVertexData(parsedVertexData, scene, rootUrl);
  19953. }
  19954. }
  19955. }
  19956. // Meshes
  19957. for (index = 0; index < parsedData.meshes.length; index++) {
  19958. var parsedMesh = parsedData.meshes[index];
  19959. parseMesh(parsedMesh, scene, rootUrl);
  19960. }
  19961. // Cameras
  19962. for (index = 0; index < parsedData.cameras.length; index++) {
  19963. var parsedCamera = parsedData.cameras[index];
  19964. parseCamera(parsedCamera, scene);
  19965. }
  19966. if (parsedData.activeCameraID) {
  19967. scene.setActiveCameraByID(parsedData.activeCameraID);
  19968. }
  19969. // Browsing all the graph to connect the dots
  19970. for (index = 0; index < scene.cameras.length; index++) {
  19971. var camera = scene.cameras[index];
  19972. if (camera._waitingParentId) {
  19973. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  19974. camera._waitingParentId = undefined;
  19975. }
  19976. }
  19977. for (index = 0; index < scene.lights.length; index++) {
  19978. var light = scene.lights[index];
  19979. if (light._waitingParentId) {
  19980. light.parent = scene.getLastEntryByID(light._waitingParentId);
  19981. light._waitingParentId = undefined;
  19982. }
  19983. }
  19984. // Sounds
  19985. if (parsedData.sounds) {
  19986. for (index = 0; index < parsedData.sounds.length; index++) {
  19987. var parsedSound = parsedData.sounds[index];
  19988. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  19989. parseSound(parsedSound, scene, rootUrl);
  19990. }
  19991. else {
  19992. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  19993. }
  19994. }
  19995. }
  19996. // Connect parents & children and parse actions
  19997. for (index = 0; index < scene.meshes.length; index++) {
  19998. var mesh = scene.meshes[index];
  19999. if (mesh._waitingParentId) {
  20000. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20001. mesh._waitingParentId = undefined;
  20002. }
  20003. if (mesh._waitingActions) {
  20004. parseActions(mesh._waitingActions, mesh, scene);
  20005. mesh._waitingActions = undefined;
  20006. }
  20007. }
  20008. // Particles Systems
  20009. if (parsedData.particleSystems) {
  20010. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20011. var parsedParticleSystem = parsedData.particleSystems[index];
  20012. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20013. }
  20014. }
  20015. // Lens flares
  20016. if (parsedData.lensFlareSystems) {
  20017. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20018. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20019. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20020. }
  20021. }
  20022. // Shadows
  20023. if (parsedData.shadowGenerators) {
  20024. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20025. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20026. parseShadowGenerator(parsedShadowGenerator, scene);
  20027. }
  20028. }
  20029. // Actions (scene)
  20030. if (parsedData.actions) {
  20031. parseActions(parsedData.actions, null, scene);
  20032. }
  20033. // Finish
  20034. return true;
  20035. }
  20036. });
  20037. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20038. })(BABYLON || (BABYLON = {}));
  20039. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  20040. var BABYLON;
  20041. (function (BABYLON) {
  20042. var SpriteManager = (function () {
  20043. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  20044. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  20045. this.name = name;
  20046. this.cellSize = cellSize;
  20047. this.sprites = new Array();
  20048. this.renderingGroupId = 0;
  20049. this.fogEnabled = true;
  20050. this._vertexDeclaration = [4, 4, 4, 4];
  20051. this._vertexStrideSize = 16 * 4; // 15 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  20052. this._capacity = capacity;
  20053. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  20054. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20055. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  20056. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  20057. this._scene = scene;
  20058. this._scene.spriteManagers.push(this);
  20059. // VBO
  20060. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20061. var indices = [];
  20062. var index = 0;
  20063. for (var count = 0; count < capacity; count++) {
  20064. indices.push(index);
  20065. indices.push(index + 1);
  20066. indices.push(index + 2);
  20067. indices.push(index);
  20068. indices.push(index + 2);
  20069. indices.push(index + 3);
  20070. index += 4;
  20071. }
  20072. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20073. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20074. // Effects
  20075. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  20076. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  20077. }
  20078. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  20079. var arrayOffset = index * 16;
  20080. if (offsetX === 0)
  20081. offsetX = this._epsilon;
  20082. else if (offsetX === 1)
  20083. offsetX = 1 - this._epsilon;
  20084. if (offsetY === 0)
  20085. offsetY = this._epsilon;
  20086. else if (offsetY === 1)
  20087. offsetY = 1 - this._epsilon;
  20088. this._vertices[arrayOffset] = sprite.position.x;
  20089. this._vertices[arrayOffset + 1] = sprite.position.y;
  20090. this._vertices[arrayOffset + 2] = sprite.position.z;
  20091. this._vertices[arrayOffset + 3] = sprite.angle;
  20092. this._vertices[arrayOffset + 4] = sprite.width;
  20093. this._vertices[arrayOffset + 5] = sprite.height;
  20094. this._vertices[arrayOffset + 6] = offsetX;
  20095. this._vertices[arrayOffset + 7] = offsetY;
  20096. this._vertices[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  20097. this._vertices[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  20098. var offset = (sprite.cellIndex / rowSize) >> 0;
  20099. this._vertices[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  20100. this._vertices[arrayOffset + 11] = offset;
  20101. // Color
  20102. this._vertices[arrayOffset + 12] = sprite.color.r;
  20103. this._vertices[arrayOffset + 13] = sprite.color.g;
  20104. this._vertices[arrayOffset + 14] = sprite.color.b;
  20105. this._vertices[arrayOffset + 15] = sprite.color.a;
  20106. };
  20107. SpriteManager.prototype.render = function () {
  20108. // Check
  20109. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  20110. return;
  20111. var engine = this._scene.getEngine();
  20112. var baseSize = this._spriteTexture.getBaseSize();
  20113. // Sprites
  20114. var deltaTime = engine.getDeltaTime();
  20115. var max = Math.min(this._capacity, this.sprites.length);
  20116. var rowSize = baseSize.width / this.cellSize;
  20117. var offset = 0;
  20118. for (var index = 0; index < max; index++) {
  20119. var sprite = this.sprites[index];
  20120. if (!sprite) {
  20121. continue;
  20122. }
  20123. sprite._animate(deltaTime);
  20124. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  20125. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  20126. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  20127. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  20128. }
  20129. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20130. // Render
  20131. var effect = this._effectBase;
  20132. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20133. effect = this._effectFog;
  20134. }
  20135. engine.enableEffect(effect);
  20136. var viewMatrix = this._scene.getViewMatrix();
  20137. effect.setTexture("diffuseSampler", this._spriteTexture);
  20138. effect.setMatrix("view", viewMatrix);
  20139. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20140. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  20141. // Fog
  20142. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  20143. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  20144. effect.setColor3("vFogColor", this._scene.fogColor);
  20145. }
  20146. // VBOs
  20147. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20148. // Draw order
  20149. engine.setDepthFunctionToLessOrEqual();
  20150. effect.setBool("alphaTest", true);
  20151. engine.setColorWrite(false);
  20152. engine.draw(true, 0, max * 6);
  20153. engine.setColorWrite(true);
  20154. effect.setBool("alphaTest", false);
  20155. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20156. engine.draw(true, 0, max * 6);
  20157. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20158. };
  20159. SpriteManager.prototype.dispose = function () {
  20160. if (this._vertexBuffer) {
  20161. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20162. this._vertexBuffer = null;
  20163. }
  20164. if (this._indexBuffer) {
  20165. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20166. this._indexBuffer = null;
  20167. }
  20168. if (this._spriteTexture) {
  20169. this._spriteTexture.dispose();
  20170. this._spriteTexture = null;
  20171. }
  20172. // Remove from scene
  20173. var index = this._scene.spriteManagers.indexOf(this);
  20174. this._scene.spriteManagers.splice(index, 1);
  20175. // Callback
  20176. if (this.onDispose) {
  20177. this.onDispose();
  20178. }
  20179. };
  20180. return SpriteManager;
  20181. })();
  20182. BABYLON.SpriteManager = SpriteManager;
  20183. })(BABYLON || (BABYLON = {}));
  20184. //# sourceMappingURL=babylon.spriteManager.js.map
  20185. var BABYLON;
  20186. (function (BABYLON) {
  20187. var Sprite = (function () {
  20188. function Sprite(name, manager) {
  20189. this.name = name;
  20190. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20191. this.width = 1.0;
  20192. this.height = 1.0;
  20193. this.angle = 0;
  20194. this.cellIndex = 0;
  20195. this.invertU = 0;
  20196. this.invertV = 0;
  20197. this.animations = new Array();
  20198. this._animationStarted = false;
  20199. this._loopAnimation = false;
  20200. this._fromIndex = 0;
  20201. this._toIndex = 0;
  20202. this._delay = 0;
  20203. this._direction = 1;
  20204. this._frameCount = 0;
  20205. this._time = 0;
  20206. this._manager = manager;
  20207. this._manager.sprites.push(this);
  20208. this.position = BABYLON.Vector3.Zero();
  20209. }
  20210. Object.defineProperty(Sprite.prototype, "size", {
  20211. get: function () {
  20212. return this.width;
  20213. },
  20214. set: function (value) {
  20215. this.width = value;
  20216. this.height = value;
  20217. },
  20218. enumerable: true,
  20219. configurable: true
  20220. });
  20221. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  20222. this._fromIndex = from;
  20223. this._toIndex = to;
  20224. this._loopAnimation = loop;
  20225. this._delay = delay;
  20226. this._animationStarted = true;
  20227. this._direction = from < to ? 1 : -1;
  20228. this.cellIndex = from;
  20229. this._time = 0;
  20230. };
  20231. Sprite.prototype.stopAnimation = function () {
  20232. this._animationStarted = false;
  20233. };
  20234. Sprite.prototype._animate = function (deltaTime) {
  20235. if (!this._animationStarted)
  20236. return;
  20237. this._time += deltaTime;
  20238. if (this._time > this._delay) {
  20239. this._time = this._time % this._delay;
  20240. this.cellIndex += this._direction;
  20241. if (this.cellIndex == this._toIndex) {
  20242. if (this._loopAnimation) {
  20243. this.cellIndex = this._fromIndex;
  20244. }
  20245. else {
  20246. this._animationStarted = false;
  20247. if (this.disposeWhenFinishedAnimating) {
  20248. this.dispose();
  20249. }
  20250. }
  20251. }
  20252. }
  20253. };
  20254. Sprite.prototype.dispose = function () {
  20255. for (var i = 0; i < this._manager.sprites.length; i++) {
  20256. if (this._manager.sprites[i] == this) {
  20257. this._manager.sprites.splice(i, 1);
  20258. }
  20259. }
  20260. };
  20261. return Sprite;
  20262. })();
  20263. BABYLON.Sprite = Sprite;
  20264. })(BABYLON || (BABYLON = {}));
  20265. //# sourceMappingURL=babylon.sprite.js.map
  20266. var BABYLON;
  20267. (function (BABYLON) {
  20268. var Layer = (function () {
  20269. function Layer(name, imgUrl, scene, isBackground, color) {
  20270. this.name = name;
  20271. this._vertexDeclaration = [2];
  20272. this._vertexStrideSize = 2 * 4;
  20273. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  20274. this.isBackground = isBackground === undefined ? true : isBackground;
  20275. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  20276. this._scene = scene;
  20277. this._scene.layers.push(this);
  20278. // VBO
  20279. var vertices = [];
  20280. vertices.push(1, 1);
  20281. vertices.push(-1, 1);
  20282. vertices.push(-1, -1);
  20283. vertices.push(1, -1);
  20284. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  20285. // Indices
  20286. var indices = [];
  20287. indices.push(0);
  20288. indices.push(1);
  20289. indices.push(2);
  20290. indices.push(0);
  20291. indices.push(2);
  20292. indices.push(3);
  20293. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20294. // Effects
  20295. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  20296. }
  20297. Layer.prototype.render = function () {
  20298. // Check
  20299. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  20300. return;
  20301. var engine = this._scene.getEngine();
  20302. // Render
  20303. engine.enableEffect(this._effect);
  20304. engine.setState(false);
  20305. // Texture
  20306. this._effect.setTexture("textureSampler", this.texture);
  20307. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  20308. // Color
  20309. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  20310. // VBOs
  20311. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  20312. // Draw order
  20313. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20314. engine.draw(true, 0, 6);
  20315. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20316. };
  20317. Layer.prototype.dispose = function () {
  20318. if (this._vertexBuffer) {
  20319. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20320. this._vertexBuffer = null;
  20321. }
  20322. if (this._indexBuffer) {
  20323. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20324. this._indexBuffer = null;
  20325. }
  20326. if (this.texture) {
  20327. this.texture.dispose();
  20328. this.texture = null;
  20329. }
  20330. // Remove from scene
  20331. var index = this._scene.layers.indexOf(this);
  20332. this._scene.layers.splice(index, 1);
  20333. // Callback
  20334. if (this.onDispose) {
  20335. this.onDispose();
  20336. }
  20337. };
  20338. return Layer;
  20339. })();
  20340. BABYLON.Layer = Layer;
  20341. })(BABYLON || (BABYLON = {}));
  20342. //# sourceMappingURL=babylon.layer.js.map
  20343. var BABYLON;
  20344. (function (BABYLON) {
  20345. var Particle = (function () {
  20346. function Particle() {
  20347. this.position = BABYLON.Vector3.Zero();
  20348. this.direction = BABYLON.Vector3.Zero();
  20349. this.color = new BABYLON.Color4(0, 0, 0, 0);
  20350. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  20351. this.lifeTime = 1.0;
  20352. this.age = 0;
  20353. this.size = 0;
  20354. this.angle = 0;
  20355. this.angularSpeed = 0;
  20356. }
  20357. Particle.prototype.copyTo = function (other) {
  20358. other.position.copyFrom(this.position);
  20359. other.direction.copyFrom(this.direction);
  20360. other.color.copyFrom(this.color);
  20361. other.colorStep.copyFrom(this.colorStep);
  20362. other.lifeTime = this.lifeTime;
  20363. other.age = this.age;
  20364. other.size = this.size;
  20365. other.angle = this.angle;
  20366. other.angularSpeed = this.angularSpeed;
  20367. };
  20368. return Particle;
  20369. })();
  20370. BABYLON.Particle = Particle;
  20371. })(BABYLON || (BABYLON = {}));
  20372. //# sourceMappingURL=babylon.particle.js.map
  20373. var BABYLON;
  20374. (function (BABYLON) {
  20375. var randomNumber = function (min, max) {
  20376. if (min === max) {
  20377. return (min);
  20378. }
  20379. var random = Math.random();
  20380. return ((random * (max - min)) + min);
  20381. };
  20382. var ParticleSystem = (function () {
  20383. function ParticleSystem(name, capacity, scene, customEffect) {
  20384. var _this = this;
  20385. this.name = name;
  20386. this.renderingGroupId = 0;
  20387. this.emitter = null;
  20388. this.emitRate = 10;
  20389. this.manualEmitCount = -1;
  20390. this.updateSpeed = 0.01;
  20391. this.targetStopDuration = 0;
  20392. this.disposeOnStop = false;
  20393. this.minEmitPower = 1;
  20394. this.maxEmitPower = 1;
  20395. this.minLifeTime = 1;
  20396. this.maxLifeTime = 1;
  20397. this.minSize = 1;
  20398. this.maxSize = 1;
  20399. this.minAngularSpeed = 0;
  20400. this.maxAngularSpeed = 0;
  20401. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  20402. this.forceDepthWrite = false;
  20403. this.gravity = BABYLON.Vector3.Zero();
  20404. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  20405. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  20406. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  20407. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  20408. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20409. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20410. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  20411. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  20412. this.particles = new Array();
  20413. this._vertexDeclaration = [3, 4, 4];
  20414. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  20415. this._stockParticles = new Array();
  20416. this._newPartsExcess = 0;
  20417. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  20418. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  20419. this._scaledDirection = BABYLON.Vector3.Zero();
  20420. this._scaledGravity = BABYLON.Vector3.Zero();
  20421. this._currentRenderId = -1;
  20422. this._started = false;
  20423. this._stopped = false;
  20424. this._actualFrame = 0;
  20425. this.id = name;
  20426. this._capacity = capacity;
  20427. this._scene = scene;
  20428. this._customEffect = customEffect;
  20429. scene.particleSystems.push(this);
  20430. // VBO
  20431. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  20432. var indices = [];
  20433. var index = 0;
  20434. for (var count = 0; count < capacity; count++) {
  20435. indices.push(index);
  20436. indices.push(index + 1);
  20437. indices.push(index + 2);
  20438. indices.push(index);
  20439. indices.push(index + 2);
  20440. indices.push(index + 3);
  20441. index += 4;
  20442. }
  20443. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  20444. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  20445. // Default behaviors
  20446. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  20447. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  20448. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  20449. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  20450. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  20451. };
  20452. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  20453. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  20454. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  20455. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  20456. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  20457. };
  20458. this.updateFunction = function (particles) {
  20459. for (var index = 0; index < particles.length; index++) {
  20460. var particle = particles[index];
  20461. particle.age += _this._scaledUpdateSpeed;
  20462. if (particle.age >= particle.lifeTime) {
  20463. _this.recycleParticle(particle);
  20464. index--;
  20465. continue;
  20466. }
  20467. else {
  20468. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  20469. particle.color.addInPlace(_this._scaledColorStep);
  20470. if (particle.color.a < 0)
  20471. particle.color.a = 0;
  20472. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  20473. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  20474. particle.position.addInPlace(_this._scaledDirection);
  20475. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  20476. particle.direction.addInPlace(_this._scaledGravity);
  20477. }
  20478. }
  20479. };
  20480. }
  20481. ParticleSystem.prototype.recycleParticle = function (particle) {
  20482. var lastParticle = this.particles.pop();
  20483. if (lastParticle !== particle) {
  20484. lastParticle.copyTo(particle);
  20485. this._stockParticles.push(lastParticle);
  20486. }
  20487. };
  20488. ParticleSystem.prototype.getCapacity = function () {
  20489. return this._capacity;
  20490. };
  20491. ParticleSystem.prototype.isAlive = function () {
  20492. return this._alive;
  20493. };
  20494. ParticleSystem.prototype.isStarted = function () {
  20495. return this._started;
  20496. };
  20497. ParticleSystem.prototype.start = function () {
  20498. this._started = true;
  20499. this._stopped = false;
  20500. this._actualFrame = 0;
  20501. };
  20502. ParticleSystem.prototype.stop = function () {
  20503. this._stopped = true;
  20504. };
  20505. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  20506. var offset = index * 11;
  20507. this._vertices[offset] = particle.position.x;
  20508. this._vertices[offset + 1] = particle.position.y;
  20509. this._vertices[offset + 2] = particle.position.z;
  20510. this._vertices[offset + 3] = particle.color.r;
  20511. this._vertices[offset + 4] = particle.color.g;
  20512. this._vertices[offset + 5] = particle.color.b;
  20513. this._vertices[offset + 6] = particle.color.a;
  20514. this._vertices[offset + 7] = particle.angle;
  20515. this._vertices[offset + 8] = particle.size;
  20516. this._vertices[offset + 9] = offsetX;
  20517. this._vertices[offset + 10] = offsetY;
  20518. };
  20519. ParticleSystem.prototype._update = function (newParticles) {
  20520. // Update current
  20521. this._alive = this.particles.length > 0;
  20522. this.updateFunction(this.particles);
  20523. // Add new ones
  20524. var worldMatrix;
  20525. if (this.emitter.position) {
  20526. worldMatrix = this.emitter.getWorldMatrix();
  20527. }
  20528. else {
  20529. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  20530. }
  20531. for (var index = 0; index < newParticles; index++) {
  20532. if (this.particles.length === this._capacity) {
  20533. break;
  20534. }
  20535. if (this._stockParticles.length !== 0) {
  20536. var particle = this._stockParticles.pop();
  20537. particle.age = 0;
  20538. }
  20539. else {
  20540. particle = new BABYLON.Particle();
  20541. }
  20542. this.particles.push(particle);
  20543. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  20544. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  20545. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  20546. particle.size = randomNumber(this.minSize, this.maxSize);
  20547. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  20548. this.startPositionFunction(worldMatrix, particle.position);
  20549. var step = randomNumber(0, 1.0);
  20550. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  20551. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  20552. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  20553. }
  20554. };
  20555. ParticleSystem.prototype._getEffect = function () {
  20556. if (this._customEffect) {
  20557. return this._customEffect;
  20558. }
  20559. ;
  20560. var defines = [];
  20561. if (this._scene.clipPlane) {
  20562. defines.push("#define CLIPPLANE");
  20563. }
  20564. // Effect
  20565. var join = defines.join("\n");
  20566. if (this._cachedDefines !== join) {
  20567. this._cachedDefines = join;
  20568. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  20569. }
  20570. return this._effect;
  20571. };
  20572. ParticleSystem.prototype.animate = function () {
  20573. if (!this._started)
  20574. return;
  20575. var effect = this._getEffect();
  20576. // Check
  20577. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  20578. return;
  20579. if (this._currentRenderId === this._scene.getRenderId()) {
  20580. return;
  20581. }
  20582. this._currentRenderId = this._scene.getRenderId();
  20583. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  20584. // determine the number of particles we need to create
  20585. var emitCout;
  20586. if (this.manualEmitCount > -1) {
  20587. emitCout = this.manualEmitCount;
  20588. this.manualEmitCount = 0;
  20589. }
  20590. else {
  20591. emitCout = this.emitRate;
  20592. }
  20593. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  20594. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  20595. if (this._newPartsExcess > 1.0) {
  20596. newParticles += this._newPartsExcess >> 0;
  20597. this._newPartsExcess -= this._newPartsExcess >> 0;
  20598. }
  20599. this._alive = false;
  20600. if (!this._stopped) {
  20601. this._actualFrame += this._scaledUpdateSpeed;
  20602. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  20603. this.stop();
  20604. }
  20605. else {
  20606. newParticles = 0;
  20607. }
  20608. this._update(newParticles);
  20609. // Stopped?
  20610. if (this._stopped) {
  20611. if (!this._alive) {
  20612. this._started = false;
  20613. if (this.disposeOnStop) {
  20614. this._scene._toBeDisposed.push(this);
  20615. }
  20616. }
  20617. }
  20618. // Update VBO
  20619. var offset = 0;
  20620. for (var index = 0; index < this.particles.length; index++) {
  20621. var particle = this.particles[index];
  20622. this._appendParticleVertex(offset++, particle, 0, 0);
  20623. this._appendParticleVertex(offset++, particle, 1, 0);
  20624. this._appendParticleVertex(offset++, particle, 1, 1);
  20625. this._appendParticleVertex(offset++, particle, 0, 1);
  20626. }
  20627. var engine = this._scene.getEngine();
  20628. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  20629. };
  20630. ParticleSystem.prototype.render = function () {
  20631. var effect = this._getEffect();
  20632. // Check
  20633. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  20634. return 0;
  20635. var engine = this._scene.getEngine();
  20636. // Render
  20637. engine.enableEffect(effect);
  20638. engine.setState(false);
  20639. var viewMatrix = this._scene.getViewMatrix();
  20640. effect.setTexture("diffuseSampler", this.particleTexture);
  20641. effect.setMatrix("view", viewMatrix);
  20642. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  20643. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  20644. if (this._scene.clipPlane) {
  20645. var clipPlane = this._scene.clipPlane;
  20646. var invView = viewMatrix.clone();
  20647. invView.invert();
  20648. effect.setMatrix("invView", invView);
  20649. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  20650. }
  20651. // VBOs
  20652. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  20653. // Draw order
  20654. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  20655. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  20656. }
  20657. else {
  20658. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20659. }
  20660. if (this.forceDepthWrite) {
  20661. engine.setDepthWrite(true);
  20662. }
  20663. engine.draw(true, 0, this.particles.length * 6);
  20664. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  20665. return this.particles.length;
  20666. };
  20667. ParticleSystem.prototype.dispose = function () {
  20668. if (this._vertexBuffer) {
  20669. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  20670. this._vertexBuffer = null;
  20671. }
  20672. if (this._indexBuffer) {
  20673. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  20674. this._indexBuffer = null;
  20675. }
  20676. if (this.particleTexture) {
  20677. this.particleTexture.dispose();
  20678. this.particleTexture = null;
  20679. }
  20680. // Remove from scene
  20681. var index = this._scene.particleSystems.indexOf(this);
  20682. this._scene.particleSystems.splice(index, 1);
  20683. // Callback
  20684. if (this.onDispose) {
  20685. this.onDispose();
  20686. }
  20687. };
  20688. // Clone
  20689. ParticleSystem.prototype.clone = function (name, newEmitter) {
  20690. var result = new ParticleSystem(name, this._capacity, this._scene);
  20691. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  20692. if (newEmitter === undefined) {
  20693. newEmitter = this.emitter;
  20694. }
  20695. result.emitter = newEmitter;
  20696. if (this.particleTexture) {
  20697. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  20698. }
  20699. result.start();
  20700. return result;
  20701. };
  20702. // Statics
  20703. ParticleSystem.BLENDMODE_ONEONE = 0;
  20704. ParticleSystem.BLENDMODE_STANDARD = 1;
  20705. return ParticleSystem;
  20706. })();
  20707. BABYLON.ParticleSystem = ParticleSystem;
  20708. })(BABYLON || (BABYLON = {}));
  20709. //# sourceMappingURL=babylon.particleSystem.js.map
  20710. var BABYLON;
  20711. (function (BABYLON) {
  20712. var Animation = (function () {
  20713. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  20714. this.name = name;
  20715. this.targetProperty = targetProperty;
  20716. this.framePerSecond = framePerSecond;
  20717. this.dataType = dataType;
  20718. this.loopMode = loopMode;
  20719. this._offsetsCache = {};
  20720. this._highLimitsCache = {};
  20721. this._stopped = false;
  20722. this.targetPropertyPath = targetProperty.split(".");
  20723. this.dataType = dataType;
  20724. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  20725. }
  20726. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  20727. var dataType = undefined;
  20728. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  20729. dataType = Animation.ANIMATIONTYPE_FLOAT;
  20730. }
  20731. else if (from instanceof BABYLON.Quaternion) {
  20732. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  20733. }
  20734. else if (from instanceof BABYLON.Vector3) {
  20735. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  20736. }
  20737. else if (from instanceof BABYLON.Vector2) {
  20738. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  20739. }
  20740. else if (from instanceof BABYLON.Color3) {
  20741. dataType = Animation.ANIMATIONTYPE_COLOR3;
  20742. }
  20743. if (dataType == undefined) {
  20744. return null;
  20745. }
  20746. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  20747. var keys = [];
  20748. keys.push({ frame: 0, value: from });
  20749. keys.push({ frame: totalFrame, value: to });
  20750. animation.setKeys(keys);
  20751. mesh.animations.push(animation);
  20752. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  20753. };
  20754. // Methods
  20755. Animation.prototype.isStopped = function () {
  20756. return this._stopped;
  20757. };
  20758. Animation.prototype.getKeys = function () {
  20759. return this._keys;
  20760. };
  20761. Animation.prototype.getEasingFunction = function () {
  20762. return this._easingFunction;
  20763. };
  20764. Animation.prototype.setEasingFunction = function (easingFunction) {
  20765. this._easingFunction = easingFunction;
  20766. };
  20767. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  20768. return startValue + (endValue - startValue) * gradient;
  20769. };
  20770. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  20771. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  20772. };
  20773. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  20774. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  20775. };
  20776. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  20777. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  20778. };
  20779. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  20780. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  20781. };
  20782. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  20783. var startScale = new BABYLON.Vector3(0, 0, 0);
  20784. var startRotation = new BABYLON.Quaternion();
  20785. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  20786. startValue.decompose(startScale, startRotation, startTranslation);
  20787. var endScale = new BABYLON.Vector3(0, 0, 0);
  20788. var endRotation = new BABYLON.Quaternion();
  20789. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  20790. endValue.decompose(endScale, endRotation, endTranslation);
  20791. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  20792. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  20793. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  20794. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  20795. return result;
  20796. };
  20797. Animation.prototype.clone = function () {
  20798. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  20799. clone.setKeys(this._keys);
  20800. return clone;
  20801. };
  20802. Animation.prototype.setKeys = function (values) {
  20803. this._keys = values.slice(0);
  20804. this._offsetsCache = {};
  20805. this._highLimitsCache = {};
  20806. };
  20807. Animation.prototype._getKeyValue = function (value) {
  20808. if (typeof value === "function") {
  20809. return value();
  20810. }
  20811. return value;
  20812. };
  20813. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  20814. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  20815. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  20816. }
  20817. this.currentFrame = currentFrame;
  20818. // Try to get a hash to find the right key
  20819. 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));
  20820. if (this._keys[startKey].frame >= currentFrame) {
  20821. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  20822. startKey--;
  20823. }
  20824. }
  20825. for (var key = startKey; key < this._keys.length; key++) {
  20826. if (this._keys[key + 1].frame >= currentFrame) {
  20827. var startValue = this._getKeyValue(this._keys[key].value);
  20828. var endValue = this._getKeyValue(this._keys[key + 1].value);
  20829. // gradient : percent of currentFrame between the frame inf and the frame sup
  20830. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  20831. // check for easingFunction and correction of gradient
  20832. if (this._easingFunction != null) {
  20833. gradient = this._easingFunction.ease(gradient);
  20834. }
  20835. switch (this.dataType) {
  20836. // Float
  20837. case Animation.ANIMATIONTYPE_FLOAT:
  20838. switch (loopMode) {
  20839. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20840. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20841. return this.floatInterpolateFunction(startValue, endValue, gradient);
  20842. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20843. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  20844. }
  20845. break;
  20846. // Quaternion
  20847. case Animation.ANIMATIONTYPE_QUATERNION:
  20848. var quaternion = null;
  20849. switch (loopMode) {
  20850. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20851. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20852. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  20853. break;
  20854. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20855. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20856. break;
  20857. }
  20858. return quaternion;
  20859. // Vector3
  20860. case Animation.ANIMATIONTYPE_VECTOR3:
  20861. switch (loopMode) {
  20862. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20863. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20864. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  20865. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20866. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20867. }
  20868. // Vector2
  20869. case Animation.ANIMATIONTYPE_VECTOR2:
  20870. switch (loopMode) {
  20871. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20872. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20873. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  20874. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20875. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20876. }
  20877. // Color3
  20878. case Animation.ANIMATIONTYPE_COLOR3:
  20879. switch (loopMode) {
  20880. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20881. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20882. return this.color3InterpolateFunction(startValue, endValue, gradient);
  20883. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20884. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  20885. }
  20886. // Matrix
  20887. case Animation.ANIMATIONTYPE_MATRIX:
  20888. switch (loopMode) {
  20889. case Animation.ANIMATIONLOOPMODE_CYCLE:
  20890. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  20891. // return this.matrixInterpolateFunction(startValue, endValue, gradient);
  20892. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  20893. return startValue;
  20894. }
  20895. default:
  20896. break;
  20897. }
  20898. break;
  20899. }
  20900. }
  20901. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  20902. };
  20903. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  20904. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  20905. this._stopped = true;
  20906. return false;
  20907. }
  20908. var returnValue = true;
  20909. // Adding a start key at frame 0 if missing
  20910. if (this._keys[0].frame !== 0) {
  20911. var newKey = { frame: 0, value: this._keys[0].value };
  20912. this._keys.splice(0, 0, newKey);
  20913. }
  20914. // Check limits
  20915. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  20916. from = this._keys[0].frame;
  20917. }
  20918. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  20919. to = this._keys[this._keys.length - 1].frame;
  20920. }
  20921. // Compute ratio
  20922. var range = to - from;
  20923. var offsetValue;
  20924. // ratio represents the frame delta between from and to
  20925. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  20926. var highLimitValue = 0;
  20927. if (ratio > range && !loop) {
  20928. returnValue = false;
  20929. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  20930. }
  20931. else {
  20932. // Get max value if required
  20933. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  20934. var keyOffset = to.toString() + from.toString();
  20935. if (!this._offsetsCache[keyOffset]) {
  20936. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  20937. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  20938. switch (this.dataType) {
  20939. // Float
  20940. case Animation.ANIMATIONTYPE_FLOAT:
  20941. this._offsetsCache[keyOffset] = toValue - fromValue;
  20942. break;
  20943. // Quaternion
  20944. case Animation.ANIMATIONTYPE_QUATERNION:
  20945. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  20946. break;
  20947. // Vector3
  20948. case Animation.ANIMATIONTYPE_VECTOR3:
  20949. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  20950. // Vector2
  20951. case Animation.ANIMATIONTYPE_VECTOR2:
  20952. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  20953. // Color3
  20954. case Animation.ANIMATIONTYPE_COLOR3:
  20955. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  20956. default:
  20957. break;
  20958. }
  20959. this._highLimitsCache[keyOffset] = toValue;
  20960. }
  20961. highLimitValue = this._highLimitsCache[keyOffset];
  20962. offsetValue = this._offsetsCache[keyOffset];
  20963. }
  20964. }
  20965. if (offsetValue === undefined) {
  20966. switch (this.dataType) {
  20967. // Float
  20968. case Animation.ANIMATIONTYPE_FLOAT:
  20969. offsetValue = 0;
  20970. break;
  20971. // Quaternion
  20972. case Animation.ANIMATIONTYPE_QUATERNION:
  20973. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  20974. break;
  20975. // Vector3
  20976. case Animation.ANIMATIONTYPE_VECTOR3:
  20977. offsetValue = BABYLON.Vector3.Zero();
  20978. break;
  20979. // Vector2
  20980. case Animation.ANIMATIONTYPE_VECTOR2:
  20981. offsetValue = BABYLON.Vector2.Zero();
  20982. break;
  20983. // Color3
  20984. case Animation.ANIMATIONTYPE_COLOR3:
  20985. offsetValue = BABYLON.Color3.Black();
  20986. }
  20987. }
  20988. // Compute value
  20989. var repeatCount = (ratio / range) >> 0;
  20990. var currentFrame = returnValue ? from + ratio % range : to;
  20991. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  20992. // Set value
  20993. if (this.targetPropertyPath.length > 1) {
  20994. var property = this._target[this.targetPropertyPath[0]];
  20995. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  20996. property = property[this.targetPropertyPath[index]];
  20997. }
  20998. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  20999. }
  21000. else {
  21001. this._target[this.targetPropertyPath[0]] = currentValue;
  21002. }
  21003. if (this._target.markAsDirty) {
  21004. this._target.markAsDirty(this.targetProperty);
  21005. }
  21006. if (!returnValue) {
  21007. this._stopped = true;
  21008. }
  21009. return returnValue;
  21010. };
  21011. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  21012. get: function () {
  21013. return Animation._ANIMATIONTYPE_FLOAT;
  21014. },
  21015. enumerable: true,
  21016. configurable: true
  21017. });
  21018. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  21019. get: function () {
  21020. return Animation._ANIMATIONTYPE_VECTOR3;
  21021. },
  21022. enumerable: true,
  21023. configurable: true
  21024. });
  21025. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  21026. get: function () {
  21027. return Animation._ANIMATIONTYPE_VECTOR2;
  21028. },
  21029. enumerable: true,
  21030. configurable: true
  21031. });
  21032. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  21033. get: function () {
  21034. return Animation._ANIMATIONTYPE_QUATERNION;
  21035. },
  21036. enumerable: true,
  21037. configurable: true
  21038. });
  21039. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  21040. get: function () {
  21041. return Animation._ANIMATIONTYPE_MATRIX;
  21042. },
  21043. enumerable: true,
  21044. configurable: true
  21045. });
  21046. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  21047. get: function () {
  21048. return Animation._ANIMATIONTYPE_COLOR3;
  21049. },
  21050. enumerable: true,
  21051. configurable: true
  21052. });
  21053. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  21054. get: function () {
  21055. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  21056. },
  21057. enumerable: true,
  21058. configurable: true
  21059. });
  21060. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  21061. get: function () {
  21062. return Animation._ANIMATIONLOOPMODE_CYCLE;
  21063. },
  21064. enumerable: true,
  21065. configurable: true
  21066. });
  21067. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  21068. get: function () {
  21069. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  21070. },
  21071. enumerable: true,
  21072. configurable: true
  21073. });
  21074. // Statics
  21075. Animation._ANIMATIONTYPE_FLOAT = 0;
  21076. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  21077. Animation._ANIMATIONTYPE_QUATERNION = 2;
  21078. Animation._ANIMATIONTYPE_MATRIX = 3;
  21079. Animation._ANIMATIONTYPE_COLOR3 = 4;
  21080. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  21081. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  21082. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  21083. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  21084. return Animation;
  21085. })();
  21086. BABYLON.Animation = Animation;
  21087. })(BABYLON || (BABYLON = {}));
  21088. //# sourceMappingURL=babylon.animation.js.map
  21089. var BABYLON;
  21090. (function (BABYLON) {
  21091. var Animatable = (function () {
  21092. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  21093. if (fromFrame === void 0) { fromFrame = 0; }
  21094. if (toFrame === void 0) { toFrame = 100; }
  21095. if (loopAnimation === void 0) { loopAnimation = false; }
  21096. if (speedRatio === void 0) { speedRatio = 1.0; }
  21097. this.target = target;
  21098. this.fromFrame = fromFrame;
  21099. this.toFrame = toFrame;
  21100. this.loopAnimation = loopAnimation;
  21101. this.speedRatio = speedRatio;
  21102. this.onAnimationEnd = onAnimationEnd;
  21103. this._animations = new Array();
  21104. this._paused = false;
  21105. this.animationStarted = false;
  21106. if (animations) {
  21107. this.appendAnimations(target, animations);
  21108. }
  21109. this._scene = scene;
  21110. scene._activeAnimatables.push(this);
  21111. }
  21112. // Methods
  21113. Animatable.prototype.appendAnimations = function (target, animations) {
  21114. for (var index = 0; index < animations.length; index++) {
  21115. var animation = animations[index];
  21116. animation._target = target;
  21117. this._animations.push(animation);
  21118. }
  21119. };
  21120. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  21121. var animations = this._animations;
  21122. for (var index = 0; index < animations.length; index++) {
  21123. if (animations[index].targetProperty === property) {
  21124. return animations[index];
  21125. }
  21126. }
  21127. return null;
  21128. };
  21129. Animatable.prototype.pause = function () {
  21130. if (this._paused) {
  21131. return;
  21132. }
  21133. this._paused = true;
  21134. };
  21135. Animatable.prototype.restart = function () {
  21136. this._paused = false;
  21137. };
  21138. Animatable.prototype.stop = function () {
  21139. var index = this._scene._activeAnimatables.indexOf(this);
  21140. if (index > -1) {
  21141. this._scene._activeAnimatables.splice(index, 1);
  21142. }
  21143. if (this.onAnimationEnd) {
  21144. this.onAnimationEnd();
  21145. }
  21146. };
  21147. Animatable.prototype._animate = function (delay) {
  21148. if (this._paused) {
  21149. if (!this._pausedDelay) {
  21150. this._pausedDelay = delay;
  21151. }
  21152. return true;
  21153. }
  21154. if (!this._localDelayOffset) {
  21155. this._localDelayOffset = delay;
  21156. }
  21157. else if (this._pausedDelay) {
  21158. this._localDelayOffset += delay - this._pausedDelay;
  21159. this._pausedDelay = null;
  21160. }
  21161. // Animating
  21162. var running = false;
  21163. var animations = this._animations;
  21164. for (var index = 0; index < animations.length; index++) {
  21165. var animation = animations[index];
  21166. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  21167. running = running || isRunning;
  21168. }
  21169. if (!running) {
  21170. // Remove from active animatables
  21171. index = this._scene._activeAnimatables.indexOf(this);
  21172. this._scene._activeAnimatables.splice(index, 1);
  21173. }
  21174. if (!running && this.onAnimationEnd) {
  21175. this.onAnimationEnd();
  21176. }
  21177. return running;
  21178. };
  21179. return Animatable;
  21180. })();
  21181. BABYLON.Animatable = Animatable;
  21182. })(BABYLON || (BABYLON = {}));
  21183. //# sourceMappingURL=babylon.animatable.js.map
  21184. var BABYLON;
  21185. (function (BABYLON) {
  21186. var EasingFunction = (function () {
  21187. function EasingFunction() {
  21188. // Properties
  21189. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  21190. }
  21191. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  21192. get: function () {
  21193. return EasingFunction._EASINGMODE_EASEIN;
  21194. },
  21195. enumerable: true,
  21196. configurable: true
  21197. });
  21198. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  21199. get: function () {
  21200. return EasingFunction._EASINGMODE_EASEOUT;
  21201. },
  21202. enumerable: true,
  21203. configurable: true
  21204. });
  21205. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  21206. get: function () {
  21207. return EasingFunction._EASINGMODE_EASEINOUT;
  21208. },
  21209. enumerable: true,
  21210. configurable: true
  21211. });
  21212. EasingFunction.prototype.setEasingMode = function (easingMode) {
  21213. var n = Math.min(Math.max(easingMode, 0), 2);
  21214. this._easingMode = n;
  21215. };
  21216. EasingFunction.prototype.getEasingMode = function () {
  21217. return this._easingMode;
  21218. };
  21219. EasingFunction.prototype.easeInCore = function (gradient) {
  21220. throw new Error('You must implement this method');
  21221. };
  21222. EasingFunction.prototype.ease = function (gradient) {
  21223. switch (this._easingMode) {
  21224. case EasingFunction.EASINGMODE_EASEIN:
  21225. return this.easeInCore(gradient);
  21226. case EasingFunction.EASINGMODE_EASEOUT:
  21227. return (1 - this.easeInCore(1 - gradient));
  21228. }
  21229. if (gradient >= 0.5) {
  21230. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  21231. }
  21232. return (this.easeInCore(gradient * 2) * 0.5);
  21233. };
  21234. //Statics
  21235. EasingFunction._EASINGMODE_EASEIN = 0;
  21236. EasingFunction._EASINGMODE_EASEOUT = 1;
  21237. EasingFunction._EASINGMODE_EASEINOUT = 2;
  21238. return EasingFunction;
  21239. })();
  21240. BABYLON.EasingFunction = EasingFunction;
  21241. var CircleEase = (function (_super) {
  21242. __extends(CircleEase, _super);
  21243. function CircleEase() {
  21244. _super.apply(this, arguments);
  21245. }
  21246. CircleEase.prototype.easeInCore = function (gradient) {
  21247. gradient = Math.max(0, Math.min(1, gradient));
  21248. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  21249. };
  21250. return CircleEase;
  21251. })(EasingFunction);
  21252. BABYLON.CircleEase = CircleEase;
  21253. var BackEase = (function (_super) {
  21254. __extends(BackEase, _super);
  21255. function BackEase(amplitude) {
  21256. if (amplitude === void 0) { amplitude = 1; }
  21257. _super.call(this);
  21258. this.amplitude = amplitude;
  21259. }
  21260. BackEase.prototype.easeInCore = function (gradient) {
  21261. var num = Math.max(0, this.amplitude);
  21262. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  21263. };
  21264. return BackEase;
  21265. })(EasingFunction);
  21266. BABYLON.BackEase = BackEase;
  21267. var BounceEase = (function (_super) {
  21268. __extends(BounceEase, _super);
  21269. function BounceEase(bounces, bounciness) {
  21270. if (bounces === void 0) { bounces = 3; }
  21271. if (bounciness === void 0) { bounciness = 2; }
  21272. _super.call(this);
  21273. this.bounces = bounces;
  21274. this.bounciness = bounciness;
  21275. }
  21276. BounceEase.prototype.easeInCore = function (gradient) {
  21277. var y = Math.max(0.0, this.bounces);
  21278. var bounciness = this.bounciness;
  21279. if (bounciness <= 1.0) {
  21280. bounciness = 1.001;
  21281. }
  21282. var num9 = Math.pow(bounciness, y);
  21283. var num5 = 1.0 - bounciness;
  21284. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  21285. var num15 = gradient * num4;
  21286. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  21287. var num3 = Math.floor(num65);
  21288. var num13 = num3 + 1.0;
  21289. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  21290. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  21291. var num7 = (num8 + num12) * 0.5;
  21292. var num6 = gradient - num7;
  21293. var num2 = num7 - num8;
  21294. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  21295. };
  21296. return BounceEase;
  21297. })(EasingFunction);
  21298. BABYLON.BounceEase = BounceEase;
  21299. var CubicEase = (function (_super) {
  21300. __extends(CubicEase, _super);
  21301. function CubicEase() {
  21302. _super.apply(this, arguments);
  21303. }
  21304. CubicEase.prototype.easeInCore = function (gradient) {
  21305. return (gradient * gradient * gradient);
  21306. };
  21307. return CubicEase;
  21308. })(EasingFunction);
  21309. BABYLON.CubicEase = CubicEase;
  21310. var ElasticEase = (function (_super) {
  21311. __extends(ElasticEase, _super);
  21312. function ElasticEase(oscillations, springiness) {
  21313. if (oscillations === void 0) { oscillations = 3; }
  21314. if (springiness === void 0) { springiness = 3; }
  21315. _super.call(this);
  21316. this.oscillations = oscillations;
  21317. this.springiness = springiness;
  21318. }
  21319. ElasticEase.prototype.easeInCore = function (gradient) {
  21320. var num2;
  21321. var num3 = Math.max(0.0, this.oscillations);
  21322. var num = Math.max(0.0, this.springiness);
  21323. if (num == 0) {
  21324. num2 = gradient;
  21325. }
  21326. else {
  21327. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  21328. }
  21329. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  21330. };
  21331. return ElasticEase;
  21332. })(EasingFunction);
  21333. BABYLON.ElasticEase = ElasticEase;
  21334. var ExponentialEase = (function (_super) {
  21335. __extends(ExponentialEase, _super);
  21336. function ExponentialEase(exponent) {
  21337. if (exponent === void 0) { exponent = 2; }
  21338. _super.call(this);
  21339. this.exponent = exponent;
  21340. }
  21341. ExponentialEase.prototype.easeInCore = function (gradient) {
  21342. if (this.exponent <= 0) {
  21343. return gradient;
  21344. }
  21345. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  21346. };
  21347. return ExponentialEase;
  21348. })(EasingFunction);
  21349. BABYLON.ExponentialEase = ExponentialEase;
  21350. var PowerEase = (function (_super) {
  21351. __extends(PowerEase, _super);
  21352. function PowerEase(power) {
  21353. if (power === void 0) { power = 2; }
  21354. _super.call(this);
  21355. this.power = power;
  21356. }
  21357. PowerEase.prototype.easeInCore = function (gradient) {
  21358. var y = Math.max(0.0, this.power);
  21359. return Math.pow(gradient, y);
  21360. };
  21361. return PowerEase;
  21362. })(EasingFunction);
  21363. BABYLON.PowerEase = PowerEase;
  21364. var QuadraticEase = (function (_super) {
  21365. __extends(QuadraticEase, _super);
  21366. function QuadraticEase() {
  21367. _super.apply(this, arguments);
  21368. }
  21369. QuadraticEase.prototype.easeInCore = function (gradient) {
  21370. return (gradient * gradient);
  21371. };
  21372. return QuadraticEase;
  21373. })(EasingFunction);
  21374. BABYLON.QuadraticEase = QuadraticEase;
  21375. var QuarticEase = (function (_super) {
  21376. __extends(QuarticEase, _super);
  21377. function QuarticEase() {
  21378. _super.apply(this, arguments);
  21379. }
  21380. QuarticEase.prototype.easeInCore = function (gradient) {
  21381. return (gradient * gradient * gradient * gradient);
  21382. };
  21383. return QuarticEase;
  21384. })(EasingFunction);
  21385. BABYLON.QuarticEase = QuarticEase;
  21386. var QuinticEase = (function (_super) {
  21387. __extends(QuinticEase, _super);
  21388. function QuinticEase() {
  21389. _super.apply(this, arguments);
  21390. }
  21391. QuinticEase.prototype.easeInCore = function (gradient) {
  21392. return (gradient * gradient * gradient * gradient * gradient);
  21393. };
  21394. return QuinticEase;
  21395. })(EasingFunction);
  21396. BABYLON.QuinticEase = QuinticEase;
  21397. var SineEase = (function (_super) {
  21398. __extends(SineEase, _super);
  21399. function SineEase() {
  21400. _super.apply(this, arguments);
  21401. }
  21402. SineEase.prototype.easeInCore = function (gradient) {
  21403. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  21404. };
  21405. return SineEase;
  21406. })(EasingFunction);
  21407. BABYLON.SineEase = SineEase;
  21408. var BezierCurveEase = (function (_super) {
  21409. __extends(BezierCurveEase, _super);
  21410. function BezierCurveEase(x1, y1, x2, y2) {
  21411. if (x1 === void 0) { x1 = 0; }
  21412. if (y1 === void 0) { y1 = 0; }
  21413. if (x2 === void 0) { x2 = 1; }
  21414. if (y2 === void 0) { y2 = 1; }
  21415. _super.call(this);
  21416. this.x1 = x1;
  21417. this.y1 = y1;
  21418. this.x2 = x2;
  21419. this.y2 = y2;
  21420. }
  21421. BezierCurveEase.prototype.easeInCore = function (gradient) {
  21422. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  21423. };
  21424. return BezierCurveEase;
  21425. })(EasingFunction);
  21426. BABYLON.BezierCurveEase = BezierCurveEase;
  21427. })(BABYLON || (BABYLON = {}));
  21428. //# sourceMappingURL=babylon.easing.js.map
  21429. var BABYLON;
  21430. (function (BABYLON) {
  21431. var Octree = (function () {
  21432. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  21433. if (maxDepth === void 0) { maxDepth = 2; }
  21434. this.maxDepth = maxDepth;
  21435. this.dynamicContent = new Array();
  21436. this._maxBlockCapacity = maxBlockCapacity || 64;
  21437. this._selectionContent = new BABYLON.SmartArray(1024);
  21438. this._creationFunc = creationFunc;
  21439. }
  21440. // Methods
  21441. Octree.prototype.update = function (worldMin, worldMax, entries) {
  21442. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  21443. };
  21444. Octree.prototype.addMesh = function (entry) {
  21445. for (var index = 0; index < this.blocks.length; index++) {
  21446. var block = this.blocks[index];
  21447. block.addEntry(entry);
  21448. }
  21449. };
  21450. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  21451. this._selectionContent.reset();
  21452. for (var index = 0; index < this.blocks.length; index++) {
  21453. var block = this.blocks[index];
  21454. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  21455. }
  21456. if (allowDuplicate) {
  21457. this._selectionContent.concat(this.dynamicContent);
  21458. }
  21459. else {
  21460. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  21461. }
  21462. return this._selectionContent;
  21463. };
  21464. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  21465. this._selectionContent.reset();
  21466. for (var index = 0; index < this.blocks.length; index++) {
  21467. var block = this.blocks[index];
  21468. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  21469. }
  21470. if (allowDuplicate) {
  21471. this._selectionContent.concat(this.dynamicContent);
  21472. }
  21473. else {
  21474. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  21475. }
  21476. return this._selectionContent;
  21477. };
  21478. Octree.prototype.intersectsRay = function (ray) {
  21479. this._selectionContent.reset();
  21480. for (var index = 0; index < this.blocks.length; index++) {
  21481. var block = this.blocks[index];
  21482. block.intersectsRay(ray, this._selectionContent);
  21483. }
  21484. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  21485. return this._selectionContent;
  21486. };
  21487. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  21488. target.blocks = new Array();
  21489. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  21490. // Segmenting space
  21491. for (var x = 0; x < 2; x++) {
  21492. for (var y = 0; y < 2; y++) {
  21493. for (var z = 0; z < 2; z++) {
  21494. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  21495. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  21496. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  21497. block.addEntries(entries);
  21498. target.blocks.push(block);
  21499. }
  21500. }
  21501. }
  21502. };
  21503. Octree.CreationFuncForMeshes = function (entry, block) {
  21504. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  21505. block.entries.push(entry);
  21506. }
  21507. };
  21508. Octree.CreationFuncForSubMeshes = function (entry, block) {
  21509. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  21510. block.entries.push(entry);
  21511. }
  21512. };
  21513. return Octree;
  21514. })();
  21515. BABYLON.Octree = Octree;
  21516. })(BABYLON || (BABYLON = {}));
  21517. //# sourceMappingURL=babylon.octree.js.map
  21518. var BABYLON;
  21519. (function (BABYLON) {
  21520. var OctreeBlock = (function () {
  21521. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  21522. this.entries = new Array();
  21523. this._boundingVectors = new Array();
  21524. this._capacity = capacity;
  21525. this._depth = depth;
  21526. this._maxDepth = maxDepth;
  21527. this._creationFunc = creationFunc;
  21528. this._minPoint = minPoint;
  21529. this._maxPoint = maxPoint;
  21530. this._boundingVectors.push(minPoint.clone());
  21531. this._boundingVectors.push(maxPoint.clone());
  21532. this._boundingVectors.push(minPoint.clone());
  21533. this._boundingVectors[2].x = maxPoint.x;
  21534. this._boundingVectors.push(minPoint.clone());
  21535. this._boundingVectors[3].y = maxPoint.y;
  21536. this._boundingVectors.push(minPoint.clone());
  21537. this._boundingVectors[4].z = maxPoint.z;
  21538. this._boundingVectors.push(maxPoint.clone());
  21539. this._boundingVectors[5].z = minPoint.z;
  21540. this._boundingVectors.push(maxPoint.clone());
  21541. this._boundingVectors[6].x = minPoint.x;
  21542. this._boundingVectors.push(maxPoint.clone());
  21543. this._boundingVectors[7].y = minPoint.y;
  21544. }
  21545. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  21546. // Property
  21547. get: function () {
  21548. return this._capacity;
  21549. },
  21550. enumerable: true,
  21551. configurable: true
  21552. });
  21553. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  21554. get: function () {
  21555. return this._minPoint;
  21556. },
  21557. enumerable: true,
  21558. configurable: true
  21559. });
  21560. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  21561. get: function () {
  21562. return this._maxPoint;
  21563. },
  21564. enumerable: true,
  21565. configurable: true
  21566. });
  21567. // Methods
  21568. OctreeBlock.prototype.addEntry = function (entry) {
  21569. if (this.blocks) {
  21570. for (var index = 0; index < this.blocks.length; index++) {
  21571. var block = this.blocks[index];
  21572. block.addEntry(entry);
  21573. }
  21574. return;
  21575. }
  21576. this._creationFunc(entry, this);
  21577. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  21578. this.createInnerBlocks();
  21579. }
  21580. };
  21581. OctreeBlock.prototype.addEntries = function (entries) {
  21582. for (var index = 0; index < entries.length; index++) {
  21583. var mesh = entries[index];
  21584. this.addEntry(mesh);
  21585. }
  21586. };
  21587. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  21588. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  21589. if (this.blocks) {
  21590. for (var index = 0; index < this.blocks.length; index++) {
  21591. var block = this.blocks[index];
  21592. block.select(frustumPlanes, selection, allowDuplicate);
  21593. }
  21594. return;
  21595. }
  21596. if (allowDuplicate) {
  21597. selection.concat(this.entries);
  21598. }
  21599. else {
  21600. selection.concatWithNoDuplicate(this.entries);
  21601. }
  21602. }
  21603. };
  21604. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  21605. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  21606. if (this.blocks) {
  21607. for (var index = 0; index < this.blocks.length; index++) {
  21608. var block = this.blocks[index];
  21609. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  21610. }
  21611. return;
  21612. }
  21613. if (allowDuplicate) {
  21614. selection.concat(this.entries);
  21615. }
  21616. else {
  21617. selection.concatWithNoDuplicate(this.entries);
  21618. }
  21619. }
  21620. };
  21621. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  21622. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  21623. if (this.blocks) {
  21624. for (var index = 0; index < this.blocks.length; index++) {
  21625. var block = this.blocks[index];
  21626. block.intersectsRay(ray, selection);
  21627. }
  21628. return;
  21629. }
  21630. selection.concatWithNoDuplicate(this.entries);
  21631. }
  21632. };
  21633. OctreeBlock.prototype.createInnerBlocks = function () {
  21634. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  21635. };
  21636. return OctreeBlock;
  21637. })();
  21638. BABYLON.OctreeBlock = OctreeBlock;
  21639. })(BABYLON || (BABYLON = {}));
  21640. //# sourceMappingURL=babylon.octreeBlock.js.map
  21641. var BABYLON;
  21642. (function (BABYLON) {
  21643. var Bone = (function () {
  21644. function Bone(name, skeleton, parentBone, matrix) {
  21645. this.name = name;
  21646. this.children = new Array();
  21647. this.animations = new Array();
  21648. this._worldTransform = new BABYLON.Matrix();
  21649. this._absoluteTransform = new BABYLON.Matrix();
  21650. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  21651. this._skeleton = skeleton;
  21652. this._matrix = matrix;
  21653. this._baseMatrix = matrix;
  21654. skeleton.bones.push(this);
  21655. if (parentBone) {
  21656. this._parent = parentBone;
  21657. parentBone.children.push(this);
  21658. }
  21659. else {
  21660. this._parent = null;
  21661. }
  21662. this._updateDifferenceMatrix();
  21663. }
  21664. // Members
  21665. Bone.prototype.getParent = function () {
  21666. return this._parent;
  21667. };
  21668. Bone.prototype.getLocalMatrix = function () {
  21669. return this._matrix;
  21670. };
  21671. Bone.prototype.getBaseMatrix = function () {
  21672. return this._baseMatrix;
  21673. };
  21674. Bone.prototype.getWorldMatrix = function () {
  21675. return this._worldTransform;
  21676. };
  21677. Bone.prototype.getInvertedAbsoluteTransform = function () {
  21678. return this._invertedAbsoluteTransform;
  21679. };
  21680. Bone.prototype.getAbsoluteMatrix = function () {
  21681. var matrix = this._matrix.clone();
  21682. var parent = this._parent;
  21683. while (parent) {
  21684. matrix = matrix.multiply(parent.getLocalMatrix());
  21685. parent = parent.getParent();
  21686. }
  21687. return matrix;
  21688. };
  21689. // Methods
  21690. Bone.prototype.updateMatrix = function (matrix) {
  21691. this._matrix = matrix;
  21692. this._skeleton._markAsDirty();
  21693. this._updateDifferenceMatrix();
  21694. };
  21695. Bone.prototype._updateDifferenceMatrix = function () {
  21696. if (this._parent) {
  21697. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  21698. }
  21699. else {
  21700. this._absoluteTransform.copyFrom(this._matrix);
  21701. }
  21702. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  21703. for (var index = 0; index < this.children.length; index++) {
  21704. this.children[index]._updateDifferenceMatrix();
  21705. }
  21706. };
  21707. Bone.prototype.markAsDirty = function () {
  21708. this._skeleton._markAsDirty();
  21709. };
  21710. return Bone;
  21711. })();
  21712. BABYLON.Bone = Bone;
  21713. })(BABYLON || (BABYLON = {}));
  21714. //# sourceMappingURL=babylon.bone.js.map
  21715. var BABYLON;
  21716. (function (BABYLON) {
  21717. var Skeleton = (function () {
  21718. function Skeleton(name, id, scene) {
  21719. this.name = name;
  21720. this.id = id;
  21721. this.bones = new Array();
  21722. this._isDirty = true;
  21723. this._identity = BABYLON.Matrix.Identity();
  21724. this.bones = [];
  21725. this._scene = scene;
  21726. scene.skeletons.push(this);
  21727. this.prepare();
  21728. //make sure it will recalculate the matrix next time prepare is called.
  21729. this._isDirty = true;
  21730. }
  21731. // Members
  21732. Skeleton.prototype.getTransformMatrices = function () {
  21733. return this._transformMatrices;
  21734. };
  21735. // Methods
  21736. Skeleton.prototype._markAsDirty = function () {
  21737. this._isDirty = true;
  21738. };
  21739. Skeleton.prototype.prepare = function () {
  21740. if (!this._isDirty) {
  21741. return;
  21742. }
  21743. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  21744. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  21745. }
  21746. for (var index = 0; index < this.bones.length; index++) {
  21747. var bone = this.bones[index];
  21748. var parentBone = bone.getParent();
  21749. if (parentBone) {
  21750. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  21751. }
  21752. else {
  21753. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  21754. }
  21755. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  21756. }
  21757. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  21758. this._isDirty = false;
  21759. this._scene._activeBones += this.bones.length;
  21760. };
  21761. Skeleton.prototype.getAnimatables = function () {
  21762. if (!this._animatables || this._animatables.length !== this.bones.length) {
  21763. this._animatables = [];
  21764. for (var index = 0; index < this.bones.length; index++) {
  21765. this._animatables.push(this.bones[index]);
  21766. }
  21767. }
  21768. return this._animatables;
  21769. };
  21770. Skeleton.prototype.clone = function (name, id) {
  21771. var result = new Skeleton(name, id || name, this._scene);
  21772. for (var index = 0; index < this.bones.length; index++) {
  21773. var source = this.bones[index];
  21774. var parentBone = null;
  21775. if (source.getParent()) {
  21776. var parentIndex = this.bones.indexOf(source.getParent());
  21777. parentBone = result.bones[parentIndex];
  21778. }
  21779. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  21780. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  21781. }
  21782. return result;
  21783. };
  21784. return Skeleton;
  21785. })();
  21786. BABYLON.Skeleton = Skeleton;
  21787. })(BABYLON || (BABYLON = {}));
  21788. //# sourceMappingURL=babylon.skeleton.js.map
  21789. var BABYLON;
  21790. (function (BABYLON) {
  21791. var PostProcess = (function () {
  21792. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  21793. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  21794. this.name = name;
  21795. this.width = -1;
  21796. this.height = -1;
  21797. this._reusable = false;
  21798. this._textures = new BABYLON.SmartArray(2);
  21799. this._currentRenderTextureInd = 0;
  21800. if (camera != null) {
  21801. this._camera = camera;
  21802. this._scene = camera.getScene();
  21803. camera.attachPostProcess(this);
  21804. this._engine = this._scene.getEngine();
  21805. }
  21806. else {
  21807. this._engine = engine;
  21808. }
  21809. this._renderRatio = ratio;
  21810. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  21811. this._reusable = reusable || false;
  21812. samplers = samplers || [];
  21813. samplers.push("textureSampler");
  21814. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  21815. }
  21816. PostProcess.prototype.isReusable = function () {
  21817. return this._reusable;
  21818. };
  21819. PostProcess.prototype.activate = function (camera, sourceTexture) {
  21820. camera = camera || this._camera;
  21821. var scene = camera.getScene();
  21822. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  21823. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  21824. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  21825. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  21826. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  21827. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  21828. if (this._textures.length > 0) {
  21829. for (var i = 0; i < this._textures.length; i++) {
  21830. this._engine._releaseTexture(this._textures.data[i]);
  21831. }
  21832. this._textures.reset();
  21833. }
  21834. this.width = desiredWidth;
  21835. this.height = desiredHeight;
  21836. 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 }));
  21837. if (this._reusable) {
  21838. 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 }));
  21839. }
  21840. if (this.onSizeChanged) {
  21841. this.onSizeChanged();
  21842. }
  21843. }
  21844. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  21845. if (this.onActivate) {
  21846. this.onActivate(camera);
  21847. }
  21848. // Clear
  21849. if (this.clearColor) {
  21850. this._engine.clear(this.clearColor, true, true);
  21851. }
  21852. else {
  21853. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  21854. }
  21855. if (this._reusable) {
  21856. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  21857. }
  21858. };
  21859. PostProcess.prototype.apply = function () {
  21860. // Check
  21861. if (!this._effect.isReady())
  21862. return null;
  21863. // States
  21864. this._engine.enableEffect(this._effect);
  21865. this._engine.setState(false);
  21866. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21867. this._engine.setDepthBuffer(false);
  21868. this._engine.setDepthWrite(false);
  21869. // Texture
  21870. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  21871. // Parameters
  21872. if (this.onApply) {
  21873. this.onApply(this._effect);
  21874. }
  21875. return this._effect;
  21876. };
  21877. PostProcess.prototype.dispose = function (camera) {
  21878. camera = camera || this._camera;
  21879. if (this._textures.length > 0) {
  21880. for (var i = 0; i < this._textures.length; i++) {
  21881. this._engine._releaseTexture(this._textures.data[i]);
  21882. }
  21883. this._textures.reset();
  21884. }
  21885. if (!camera) {
  21886. return;
  21887. }
  21888. camera.detachPostProcess(this);
  21889. var index = camera._postProcesses.indexOf(this);
  21890. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  21891. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  21892. }
  21893. };
  21894. return PostProcess;
  21895. })();
  21896. BABYLON.PostProcess = PostProcess;
  21897. })(BABYLON || (BABYLON = {}));
  21898. //# sourceMappingURL=babylon.postProcess.js.map
  21899. var BABYLON;
  21900. (function (BABYLON) {
  21901. var PostProcessManager = (function () {
  21902. function PostProcessManager(scene) {
  21903. this._vertexDeclaration = [2];
  21904. this._vertexStrideSize = 2 * 4;
  21905. this._scene = scene;
  21906. }
  21907. PostProcessManager.prototype._prepareBuffers = function () {
  21908. if (this._vertexBuffer) {
  21909. return;
  21910. }
  21911. // VBO
  21912. var vertices = [];
  21913. vertices.push(1, 1);
  21914. vertices.push(-1, 1);
  21915. vertices.push(-1, -1);
  21916. vertices.push(1, -1);
  21917. this._vertexBuffer = this._scene.getEngine().createVertexBuffer(vertices);
  21918. // Indices
  21919. var indices = [];
  21920. indices.push(0);
  21921. indices.push(1);
  21922. indices.push(2);
  21923. indices.push(0);
  21924. indices.push(2);
  21925. indices.push(3);
  21926. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  21927. };
  21928. // Methods
  21929. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  21930. var postProcesses = this._scene.activeCamera._postProcesses;
  21931. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  21932. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  21933. return false;
  21934. }
  21935. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  21936. return true;
  21937. };
  21938. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  21939. var engine = this._scene.getEngine();
  21940. for (var index = 0; index < postProcesses.length; index++) {
  21941. if (index < postProcesses.length - 1) {
  21942. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  21943. }
  21944. else {
  21945. if (targetTexture) {
  21946. engine.bindFramebuffer(targetTexture);
  21947. }
  21948. else {
  21949. engine.restoreDefaultFramebuffer();
  21950. }
  21951. }
  21952. var pp = postProcesses[index];
  21953. var effect = pp.apply();
  21954. if (effect) {
  21955. if (pp.onBeforeRender) {
  21956. pp.onBeforeRender(effect);
  21957. }
  21958. // VBOs
  21959. this._prepareBuffers();
  21960. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  21961. // Draw order
  21962. engine.draw(true, 0, 6);
  21963. }
  21964. }
  21965. // Restore depth buffer
  21966. engine.setDepthBuffer(true);
  21967. engine.setDepthWrite(true);
  21968. };
  21969. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  21970. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  21971. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  21972. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  21973. return;
  21974. }
  21975. var engine = this._scene.getEngine();
  21976. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  21977. if (index < postProcessesTakenIndices.length - 1) {
  21978. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  21979. }
  21980. else {
  21981. if (targetTexture) {
  21982. engine.bindFramebuffer(targetTexture);
  21983. }
  21984. else {
  21985. engine.restoreDefaultFramebuffer();
  21986. }
  21987. }
  21988. if (doNotPresent) {
  21989. break;
  21990. }
  21991. var pp = postProcesses[postProcessesTakenIndices[index]];
  21992. var effect = pp.apply();
  21993. if (effect) {
  21994. if (pp.onBeforeRender) {
  21995. pp.onBeforeRender(effect);
  21996. }
  21997. // VBOs
  21998. this._prepareBuffers();
  21999. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  22000. // Draw order
  22001. engine.draw(true, 0, 6);
  22002. }
  22003. }
  22004. // Restore depth buffer
  22005. engine.setDepthBuffer(true);
  22006. engine.setDepthWrite(true);
  22007. };
  22008. PostProcessManager.prototype.dispose = function () {
  22009. if (this._vertexBuffer) {
  22010. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22011. this._vertexBuffer = null;
  22012. }
  22013. if (this._indexBuffer) {
  22014. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22015. this._indexBuffer = null;
  22016. }
  22017. };
  22018. return PostProcessManager;
  22019. })();
  22020. BABYLON.PostProcessManager = PostProcessManager;
  22021. })(BABYLON || (BABYLON = {}));
  22022. //# sourceMappingURL=babylon.postProcessManager.js.map
  22023. var BABYLON;
  22024. (function (BABYLON) {
  22025. var PassPostProcess = (function (_super) {
  22026. __extends(PassPostProcess, _super);
  22027. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22028. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  22029. }
  22030. return PassPostProcess;
  22031. })(BABYLON.PostProcess);
  22032. BABYLON.PassPostProcess = PassPostProcess;
  22033. })(BABYLON || (BABYLON = {}));
  22034. //# sourceMappingURL=babylon.passPostProcess.js.map
  22035. var BABYLON;
  22036. (function (BABYLON) {
  22037. var BlurPostProcess = (function (_super) {
  22038. __extends(BlurPostProcess, _super);
  22039. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  22040. var _this = this;
  22041. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  22042. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  22043. this.direction = direction;
  22044. this.blurWidth = blurWidth;
  22045. this.onApply = function (effect) {
  22046. effect.setFloat2("screenSize", _this.width, _this.height);
  22047. effect.setVector2("direction", _this.direction);
  22048. effect.setFloat("blurWidth", _this.blurWidth);
  22049. };
  22050. }
  22051. return BlurPostProcess;
  22052. })(BABYLON.PostProcess);
  22053. BABYLON.BlurPostProcess = BlurPostProcess;
  22054. })(BABYLON || (BABYLON = {}));
  22055. //# sourceMappingURL=babylon.blurPostProcess.js.map
  22056. var BABYLON;
  22057. (function (BABYLON) {
  22058. var RefractionPostProcess = (function (_super) {
  22059. __extends(RefractionPostProcess, _super);
  22060. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  22061. var _this = this;
  22062. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  22063. this.color = color;
  22064. this.depth = depth;
  22065. this.colorLevel = colorLevel;
  22066. this.onActivate = function (cam) {
  22067. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  22068. };
  22069. this.onApply = function (effect) {
  22070. effect.setColor3("baseColor", _this.color);
  22071. effect.setFloat("depth", _this.depth);
  22072. effect.setFloat("colorLevel", _this.colorLevel);
  22073. effect.setTexture("refractionSampler", _this._refRexture);
  22074. };
  22075. }
  22076. // Methods
  22077. RefractionPostProcess.prototype.dispose = function (camera) {
  22078. if (this._refRexture) {
  22079. this._refRexture.dispose();
  22080. }
  22081. _super.prototype.dispose.call(this, camera);
  22082. };
  22083. return RefractionPostProcess;
  22084. })(BABYLON.PostProcess);
  22085. BABYLON.RefractionPostProcess = RefractionPostProcess;
  22086. })(BABYLON || (BABYLON = {}));
  22087. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  22088. var BABYLON;
  22089. (function (BABYLON) {
  22090. var BlackAndWhitePostProcess = (function (_super) {
  22091. __extends(BlackAndWhitePostProcess, _super);
  22092. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22093. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  22094. }
  22095. return BlackAndWhitePostProcess;
  22096. })(BABYLON.PostProcess);
  22097. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  22098. })(BABYLON || (BABYLON = {}));
  22099. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  22100. var BABYLON;
  22101. (function (BABYLON) {
  22102. var ConvolutionPostProcess = (function (_super) {
  22103. __extends(ConvolutionPostProcess, _super);
  22104. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  22105. var _this = this;
  22106. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  22107. this.kernel = kernel;
  22108. this.onApply = function (effect) {
  22109. effect.setFloat2("screenSize", _this.width, _this.height);
  22110. effect.setArray("kernel", _this.kernel);
  22111. };
  22112. }
  22113. // Statics
  22114. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  22115. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  22116. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  22117. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  22118. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  22119. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  22120. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  22121. return ConvolutionPostProcess;
  22122. })(BABYLON.PostProcess);
  22123. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  22124. })(BABYLON || (BABYLON = {}));
  22125. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  22126. var BABYLON;
  22127. (function (BABYLON) {
  22128. var FilterPostProcess = (function (_super) {
  22129. __extends(FilterPostProcess, _super);
  22130. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  22131. var _this = this;
  22132. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  22133. this.kernelMatrix = kernelMatrix;
  22134. this.onApply = function (effect) {
  22135. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  22136. };
  22137. }
  22138. return FilterPostProcess;
  22139. })(BABYLON.PostProcess);
  22140. BABYLON.FilterPostProcess = FilterPostProcess;
  22141. })(BABYLON || (BABYLON = {}));
  22142. //# sourceMappingURL=babylon.filterPostProcess.js.map
  22143. var BABYLON;
  22144. (function (BABYLON) {
  22145. var FxaaPostProcess = (function (_super) {
  22146. __extends(FxaaPostProcess, _super);
  22147. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22148. var _this = this;
  22149. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  22150. this.onSizeChanged = function () {
  22151. _this.texelWidth = 1.0 / _this.width;
  22152. _this.texelHeight = 1.0 / _this.height;
  22153. };
  22154. this.onApply = function (effect) {
  22155. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  22156. };
  22157. }
  22158. return FxaaPostProcess;
  22159. })(BABYLON.PostProcess);
  22160. BABYLON.FxaaPostProcess = FxaaPostProcess;
  22161. })(BABYLON || (BABYLON = {}));
  22162. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  22163. var BABYLON;
  22164. (function (BABYLON) {
  22165. var StereoscopicInterlacePostProcess = (function (_super) {
  22166. __extends(StereoscopicInterlacePostProcess, _super);
  22167. function StereoscopicInterlacePostProcess(name, camB, postProcessA, isStereoscopicHoriz, samplingMode) {
  22168. var _this = this;
  22169. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, camB, samplingMode, camB.getScene().getEngine(), false, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  22170. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  22171. this.onSizeChanged = function () {
  22172. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  22173. };
  22174. this.onApply = function (effect) {
  22175. effect.setTextureFromPostProcess("camASampler", postProcessA);
  22176. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  22177. };
  22178. }
  22179. return StereoscopicInterlacePostProcess;
  22180. })(BABYLON.PostProcess);
  22181. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  22182. })(BABYLON || (BABYLON = {}));
  22183. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  22184. var BABYLON;
  22185. (function (BABYLON) {
  22186. var LensFlare = (function () {
  22187. function LensFlare(size, position, color, imgUrl, system) {
  22188. this.size = size;
  22189. this.position = position;
  22190. this.dispose = function () {
  22191. if (this.texture) {
  22192. this.texture.dispose();
  22193. }
  22194. // Remove from scene
  22195. var index = this._system.lensFlares.indexOf(this);
  22196. this._system.lensFlares.splice(index, 1);
  22197. };
  22198. this.color = color || new BABYLON.Color3(1, 1, 1);
  22199. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  22200. this._system = system;
  22201. system.lensFlares.push(this);
  22202. }
  22203. return LensFlare;
  22204. })();
  22205. BABYLON.LensFlare = LensFlare;
  22206. })(BABYLON || (BABYLON = {}));
  22207. //# sourceMappingURL=babylon.lensFlare.js.map
  22208. var BABYLON;
  22209. (function (BABYLON) {
  22210. var LensFlareSystem = (function () {
  22211. function LensFlareSystem(name, emitter, scene) {
  22212. this.name = name;
  22213. this.lensFlares = new Array();
  22214. this.borderLimit = 300;
  22215. this._vertexDeclaration = [2];
  22216. this._vertexStrideSize = 2 * 4;
  22217. this._isEnabled = true;
  22218. this._scene = scene;
  22219. this._emitter = emitter;
  22220. scene.lensFlareSystems.push(this);
  22221. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  22222. // VBO
  22223. var vertices = [];
  22224. vertices.push(1, 1);
  22225. vertices.push(-1, 1);
  22226. vertices.push(-1, -1);
  22227. vertices.push(1, -1);
  22228. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  22229. // Indices
  22230. var indices = [];
  22231. indices.push(0);
  22232. indices.push(1);
  22233. indices.push(2);
  22234. indices.push(0);
  22235. indices.push(2);
  22236. indices.push(3);
  22237. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  22238. // Effects
  22239. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  22240. }
  22241. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  22242. get: function () {
  22243. return this._isEnabled;
  22244. },
  22245. set: function (value) {
  22246. this._isEnabled = value;
  22247. },
  22248. enumerable: true,
  22249. configurable: true
  22250. });
  22251. LensFlareSystem.prototype.getScene = function () {
  22252. return this._scene;
  22253. };
  22254. LensFlareSystem.prototype.getEmitter = function () {
  22255. return this._emitter;
  22256. };
  22257. LensFlareSystem.prototype.getEmitterPosition = function () {
  22258. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  22259. };
  22260. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  22261. var position = this.getEmitterPosition();
  22262. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  22263. this._positionX = position.x;
  22264. this._positionY = position.y;
  22265. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  22266. if (position.z > 0) {
  22267. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  22268. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  22269. return true;
  22270. }
  22271. }
  22272. return false;
  22273. };
  22274. LensFlareSystem.prototype._isVisible = function () {
  22275. if (!this._isEnabled) {
  22276. return false;
  22277. }
  22278. var emitterPosition = this.getEmitterPosition();
  22279. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  22280. var distance = direction.length();
  22281. direction.normalize();
  22282. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  22283. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  22284. return !pickInfo.hit || pickInfo.distance > distance;
  22285. };
  22286. LensFlareSystem.prototype.render = function () {
  22287. if (!this._effect.isReady())
  22288. return false;
  22289. var engine = this._scene.getEngine();
  22290. var viewport = this._scene.activeCamera.viewport;
  22291. var globalViewport = viewport.toGlobal(engine);
  22292. // Position
  22293. if (!this.computeEffectivePosition(globalViewport)) {
  22294. return false;
  22295. }
  22296. // Visibility
  22297. if (!this._isVisible()) {
  22298. return false;
  22299. }
  22300. // Intensity
  22301. var awayX;
  22302. var awayY;
  22303. if (this._positionX < this.borderLimit + globalViewport.x) {
  22304. awayX = this.borderLimit + globalViewport.x - this._positionX;
  22305. }
  22306. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  22307. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  22308. }
  22309. else {
  22310. awayX = 0;
  22311. }
  22312. if (this._positionY < this.borderLimit + globalViewport.y) {
  22313. awayY = this.borderLimit + globalViewport.y - this._positionY;
  22314. }
  22315. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  22316. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  22317. }
  22318. else {
  22319. awayY = 0;
  22320. }
  22321. var away = (awayX > awayY) ? awayX : awayY;
  22322. if (away > this.borderLimit) {
  22323. away = this.borderLimit;
  22324. }
  22325. var intensity = 1.0 - (away / this.borderLimit);
  22326. if (intensity < 0) {
  22327. return false;
  22328. }
  22329. if (intensity > 1.0) {
  22330. intensity = 1.0;
  22331. }
  22332. // Position
  22333. var centerX = globalViewport.x + globalViewport.width / 2;
  22334. var centerY = globalViewport.y + globalViewport.height / 2;
  22335. var distX = centerX - this._positionX;
  22336. var distY = centerY - this._positionY;
  22337. // Effects
  22338. engine.enableEffect(this._effect);
  22339. engine.setState(false);
  22340. engine.setDepthBuffer(false);
  22341. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  22342. // VBOs
  22343. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  22344. // Flares
  22345. for (var index = 0; index < this.lensFlares.length; index++) {
  22346. var flare = this.lensFlares[index];
  22347. var x = centerX - (distX * flare.position);
  22348. var y = centerY - (distY * flare.position);
  22349. var cw = flare.size;
  22350. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  22351. var cx = 2 * (x / globalViewport.width) - 1.0;
  22352. var cy = 1.0 - 2 * (y / globalViewport.height);
  22353. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  22354. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  22355. // Texture
  22356. this._effect.setTexture("textureSampler", flare.texture);
  22357. // Color
  22358. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  22359. // Draw order
  22360. engine.draw(true, 0, 6);
  22361. }
  22362. engine.setDepthBuffer(true);
  22363. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  22364. return true;
  22365. };
  22366. LensFlareSystem.prototype.dispose = function () {
  22367. if (this._vertexBuffer) {
  22368. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  22369. this._vertexBuffer = null;
  22370. }
  22371. if (this._indexBuffer) {
  22372. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  22373. this._indexBuffer = null;
  22374. }
  22375. while (this.lensFlares.length) {
  22376. this.lensFlares[0].dispose();
  22377. }
  22378. // Remove from scene
  22379. var index = this._scene.lensFlareSystems.indexOf(this);
  22380. this._scene.lensFlareSystems.splice(index, 1);
  22381. };
  22382. return LensFlareSystem;
  22383. })();
  22384. BABYLON.LensFlareSystem = LensFlareSystem;
  22385. })(BABYLON || (BABYLON = {}));
  22386. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  22387. var BABYLON;
  22388. (function (BABYLON) {
  22389. var CannonJSPlugin = (function () {
  22390. function CannonJSPlugin() {
  22391. this._registeredMeshes = [];
  22392. this._physicsMaterials = [];
  22393. this.updateBodyPosition = function (mesh) {
  22394. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22395. var registeredMesh = this._registeredMeshes[index];
  22396. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22397. var body = registeredMesh.body;
  22398. var center = mesh.getBoundingInfo().boundingBox.center;
  22399. body.position.set(center.x, center.z, center.y);
  22400. body.quaternion.x = mesh.rotationQuaternion.x;
  22401. body.quaternion.z = mesh.rotationQuaternion.y;
  22402. body.quaternion.y = mesh.rotationQuaternion.z;
  22403. body.quaternion.w = -mesh.rotationQuaternion.w;
  22404. return;
  22405. }
  22406. }
  22407. };
  22408. }
  22409. CannonJSPlugin.prototype.initialize = function (iterations) {
  22410. if (iterations === void 0) { iterations = 10; }
  22411. this._world = new CANNON.World();
  22412. this._world.broadphase = new CANNON.NaiveBroadphase();
  22413. this._world.solver.iterations = iterations;
  22414. };
  22415. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  22416. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  22417. };
  22418. CannonJSPlugin.prototype.runOneStep = function (delta) {
  22419. this._world.step(delta);
  22420. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22421. var registeredMesh = this._registeredMeshes[index];
  22422. if (registeredMesh.isChild) {
  22423. continue;
  22424. }
  22425. // Body position
  22426. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  22427. var deltaPos = registeredMesh.delta;
  22428. if (deltaPos) {
  22429. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  22430. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  22431. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  22432. }
  22433. else {
  22434. registeredMesh.mesh.position.x = bodyX;
  22435. registeredMesh.mesh.position.y = bodyZ;
  22436. registeredMesh.mesh.position.z = bodyY;
  22437. }
  22438. if (!registeredMesh.mesh.rotationQuaternion) {
  22439. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22440. }
  22441. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  22442. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  22443. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  22444. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  22445. }
  22446. };
  22447. CannonJSPlugin.prototype.setGravity = function (gravity) {
  22448. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  22449. };
  22450. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  22451. this.unregisterMesh(mesh);
  22452. mesh.computeWorldMatrix(true);
  22453. switch (impostor) {
  22454. case BABYLON.PhysicsEngine.SphereImpostor:
  22455. var bbox = mesh.getBoundingInfo().boundingBox;
  22456. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22457. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22458. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22459. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  22460. case BABYLON.PhysicsEngine.BoxImpostor:
  22461. bbox = mesh.getBoundingInfo().boundingBox;
  22462. var min = bbox.minimumWorld;
  22463. var max = bbox.maximumWorld;
  22464. var box = max.subtract(min).scale(0.5);
  22465. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  22466. case BABYLON.PhysicsEngine.PlaneImpostor:
  22467. return this._createPlane(mesh, options);
  22468. case BABYLON.PhysicsEngine.MeshImpostor:
  22469. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22470. var rawFaces = mesh.getIndices();
  22471. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  22472. }
  22473. return null;
  22474. };
  22475. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  22476. var shape = new CANNON.Sphere(radius);
  22477. if (!options) {
  22478. return shape;
  22479. }
  22480. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22481. };
  22482. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  22483. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  22484. if (!options) {
  22485. return shape;
  22486. }
  22487. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22488. };
  22489. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  22490. var shape = new CANNON.Plane();
  22491. if (!options) {
  22492. return shape;
  22493. }
  22494. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22495. };
  22496. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  22497. var verts = [], faces = [];
  22498. mesh.computeWorldMatrix(true);
  22499. // Get vertices
  22500. for (var i = 0; i < rawVerts.length; i += 3) {
  22501. var transformed = BABYLON.Vector3.Zero();
  22502. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  22503. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  22504. }
  22505. // Get faces
  22506. for (var j = 0; j < rawFaces.length; j += 3) {
  22507. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  22508. }
  22509. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  22510. if (!options) {
  22511. return shape;
  22512. }
  22513. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22514. };
  22515. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  22516. var index;
  22517. var mat;
  22518. for (index = 0; index < this._physicsMaterials.length; index++) {
  22519. mat = this._physicsMaterials[index];
  22520. if (mat.friction === friction && mat.restitution === restitution) {
  22521. return mat;
  22522. }
  22523. }
  22524. var currentMat = new CANNON.Material();
  22525. currentMat.friction = friction;
  22526. currentMat.restitution = restitution;
  22527. this._physicsMaterials.push(currentMat);
  22528. for (index = 0; index < this._physicsMaterials.length; index++) {
  22529. mat = this._physicsMaterials[index];
  22530. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  22531. contactMaterial.contactEquationStiffness = 1e10;
  22532. contactMaterial.contactEquationRegularizationTime = 10;
  22533. this._world.addContactMaterial(contactMaterial);
  22534. }
  22535. return currentMat;
  22536. };
  22537. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  22538. var initialRotation = null;
  22539. if (mesh.rotationQuaternion) {
  22540. initialRotation = mesh.rotationQuaternion.clone();
  22541. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22542. }
  22543. // The delta between the mesh position and the mesh bounding box center
  22544. var bbox = mesh.getBoundingInfo().boundingBox;
  22545. var deltaPosition = mesh.position.subtract(bbox.center);
  22546. var material = this._addMaterial(friction, restitution);
  22547. var body = new CANNON.RigidBody(mass, shape, material);
  22548. if (initialRotation) {
  22549. body.quaternion.x = initialRotation.x;
  22550. body.quaternion.z = initialRotation.y;
  22551. body.quaternion.y = initialRotation.z;
  22552. body.quaternion.w = -initialRotation.w;
  22553. }
  22554. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  22555. this._world.add(body);
  22556. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  22557. return body;
  22558. };
  22559. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  22560. var compoundShape = new CANNON.Compound();
  22561. for (var index = 0; index < parts.length; index++) {
  22562. var mesh = parts[index].mesh;
  22563. var shape = this.registerMesh(mesh, parts[index].impostor);
  22564. if (index == 0) {
  22565. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  22566. }
  22567. else {
  22568. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  22569. }
  22570. }
  22571. var initialMesh = parts[0].mesh;
  22572. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  22573. body.parts = parts;
  22574. return body;
  22575. };
  22576. CannonJSPlugin.prototype._unbindBody = function (body) {
  22577. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22578. var registeredMesh = this._registeredMeshes[index];
  22579. if (registeredMesh.body === body) {
  22580. registeredMesh.body = null;
  22581. registeredMesh.delta = 0;
  22582. }
  22583. }
  22584. };
  22585. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  22586. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22587. var registeredMesh = this._registeredMeshes[index];
  22588. if (registeredMesh.mesh === mesh) {
  22589. // Remove body
  22590. if (registeredMesh.body) {
  22591. this._world.remove(registeredMesh.body);
  22592. this._unbindBody(registeredMesh.body);
  22593. }
  22594. this._registeredMeshes.splice(index, 1);
  22595. return;
  22596. }
  22597. }
  22598. };
  22599. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  22600. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  22601. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  22602. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22603. var registeredMesh = this._registeredMeshes[index];
  22604. if (registeredMesh.mesh === mesh) {
  22605. registeredMesh.body.applyImpulse(impulse, worldPoint);
  22606. return;
  22607. }
  22608. }
  22609. };
  22610. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  22611. var body1 = null, body2 = null;
  22612. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22613. var registeredMesh = this._registeredMeshes[index];
  22614. if (registeredMesh.mesh === mesh1) {
  22615. body1 = registeredMesh.body;
  22616. }
  22617. else if (registeredMesh.mesh === mesh2) {
  22618. body2 = registeredMesh.body;
  22619. }
  22620. }
  22621. if (!body1 || !body2) {
  22622. return false;
  22623. }
  22624. 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));
  22625. this._world.addConstraint(constraint);
  22626. return true;
  22627. };
  22628. CannonJSPlugin.prototype.dispose = function () {
  22629. while (this._registeredMeshes.length) {
  22630. this.unregisterMesh(this._registeredMeshes[0].mesh);
  22631. }
  22632. };
  22633. CannonJSPlugin.prototype.isSupported = function () {
  22634. return window.CANNON !== undefined;
  22635. };
  22636. return CannonJSPlugin;
  22637. })();
  22638. BABYLON.CannonJSPlugin = CannonJSPlugin;
  22639. })(BABYLON || (BABYLON = {}));
  22640. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  22641. var BABYLON;
  22642. (function (BABYLON) {
  22643. var OimoJSPlugin = (function () {
  22644. function OimoJSPlugin() {
  22645. this._registeredMeshes = [];
  22646. /**
  22647. * Update the body position according to the mesh position
  22648. * @param mesh
  22649. */
  22650. this.updateBodyPosition = function (mesh) {
  22651. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22652. var registeredMesh = this._registeredMeshes[index];
  22653. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22654. var body = registeredMesh.body.body;
  22655. mesh.computeWorldMatrix(true);
  22656. var center = mesh.getBoundingInfo().boundingBox.center;
  22657. body.setPosition(new OIMO.Vec3(center.x, center.y, center.z));
  22658. body.setRotation(new OIMO.Vec3(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z));
  22659. body.sleeping = false;
  22660. return;
  22661. }
  22662. // Case where the parent has been updated
  22663. if (registeredMesh.mesh.parent === mesh) {
  22664. mesh.computeWorldMatrix(true);
  22665. registeredMesh.mesh.computeWorldMatrix(true);
  22666. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  22667. var absoluteRotation = mesh.rotation;
  22668. body = registeredMesh.body.body;
  22669. body.setPosition(new OIMO.Vec3(absolutePosition.x, absolutePosition.y, absolutePosition.z));
  22670. body.setRotation(new OIMO.Vec3(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z));
  22671. body.sleeping = false;
  22672. return;
  22673. }
  22674. }
  22675. };
  22676. }
  22677. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  22678. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  22679. };
  22680. OimoJSPlugin.prototype.initialize = function (iterations) {
  22681. this._world = new OIMO.World();
  22682. this._world.clear();
  22683. };
  22684. OimoJSPlugin.prototype.setGravity = function (gravity) {
  22685. this._world.gravity = gravity;
  22686. };
  22687. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  22688. var body = null;
  22689. this.unregisterMesh(mesh);
  22690. mesh.computeWorldMatrix(true);
  22691. var initialRotation = null;
  22692. if (mesh.rotationQuaternion) {
  22693. initialRotation = mesh.rotationQuaternion.clone();
  22694. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22695. mesh.computeWorldMatrix(true);
  22696. }
  22697. var bbox = mesh.getBoundingInfo().boundingBox;
  22698. // The delta between the mesh position and the mesh bounding box center
  22699. var deltaPosition = mesh.position.subtract(bbox.center);
  22700. // Transform delta position with the rotation
  22701. if (initialRotation) {
  22702. var m = new BABYLON.Matrix();
  22703. initialRotation.toRotationMatrix(m);
  22704. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  22705. }
  22706. // register mesh
  22707. switch (impostor) {
  22708. case BABYLON.PhysicsEngine.SphereImpostor:
  22709. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22710. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22711. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22712. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  22713. body = new OIMO.Body({
  22714. type: 'sphere',
  22715. size: [size],
  22716. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  22717. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  22718. move: options.mass != 0,
  22719. config: [options.mass, options.friction, options.restitution],
  22720. world: this._world
  22721. });
  22722. break;
  22723. case BABYLON.PhysicsEngine.PlaneImpostor:
  22724. //Oimo "fakes" a cylinder as a box, so why don't we!
  22725. case BABYLON.PhysicsEngine.CylinderImpostor:
  22726. case BABYLON.PhysicsEngine.BoxImpostor:
  22727. var min = bbox.minimumWorld;
  22728. var max = bbox.maximumWorld;
  22729. var box = max.subtract(min);
  22730. var sizeX = this._checkWithEpsilon(box.x);
  22731. var sizeY = this._checkWithEpsilon(box.y);
  22732. var sizeZ = this._checkWithEpsilon(box.z);
  22733. body = new OIMO.Body({
  22734. type: 'box',
  22735. size: [sizeX, sizeY, sizeZ],
  22736. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  22737. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  22738. move: options.mass != 0,
  22739. config: [options.mass, options.friction, options.restitution],
  22740. world: this._world
  22741. });
  22742. break;
  22743. }
  22744. //If quaternion was set as the rotation of the object
  22745. if (initialRotation) {
  22746. //We have to access the rigid body's properties to set the quaternion.
  22747. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  22748. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  22749. //update the internal rotation matrix
  22750. body.body.syncShapes();
  22751. }
  22752. this._registeredMeshes.push({
  22753. mesh: mesh,
  22754. body: body,
  22755. delta: deltaPosition
  22756. });
  22757. return body;
  22758. };
  22759. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  22760. var types = [], sizes = [], positions = [], rotations = [];
  22761. var initialMesh = parts[0].mesh;
  22762. for (var index = 0; index < parts.length; index++) {
  22763. var part = parts[index];
  22764. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  22765. types.push(bodyParameters.type);
  22766. sizes.push.apply(sizes, bodyParameters.size);
  22767. positions.push.apply(positions, bodyParameters.pos);
  22768. rotations.push.apply(rotations, bodyParameters.rot);
  22769. }
  22770. var body = new OIMO.Body({
  22771. type: types,
  22772. size: sizes,
  22773. pos: positions,
  22774. rot: rotations,
  22775. move: options.mass != 0,
  22776. config: [options.mass, options.friction, options.restitution],
  22777. world: this._world
  22778. });
  22779. this._registeredMeshes.push({
  22780. mesh: initialMesh,
  22781. body: body
  22782. });
  22783. return body;
  22784. };
  22785. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  22786. var bodyParameters = null;
  22787. var mesh = part.mesh;
  22788. // We need the bounding box/sphere info to compute the physics body
  22789. mesh.computeWorldMatrix();
  22790. switch (part.impostor) {
  22791. case BABYLON.PhysicsEngine.SphereImpostor:
  22792. var bbox = mesh.getBoundingInfo().boundingBox;
  22793. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22794. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22795. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22796. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  22797. bodyParameters = {
  22798. type: 'sphere',
  22799. /* bug with oimo : sphere needs 3 sizes in this case */
  22800. size: [size, -1, -1],
  22801. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  22802. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  22803. };
  22804. break;
  22805. case BABYLON.PhysicsEngine.PlaneImpostor:
  22806. case BABYLON.PhysicsEngine.BoxImpostor:
  22807. bbox = mesh.getBoundingInfo().boundingBox;
  22808. var min = bbox.minimumWorld;
  22809. var max = bbox.maximumWorld;
  22810. var box = max.subtract(min);
  22811. var sizeX = this._checkWithEpsilon(box.x);
  22812. var sizeY = this._checkWithEpsilon(box.y);
  22813. var sizeZ = this._checkWithEpsilon(box.z);
  22814. var relativePosition = mesh.position;
  22815. bodyParameters = {
  22816. type: 'box',
  22817. size: [sizeX, sizeY, sizeZ],
  22818. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  22819. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  22820. };
  22821. break;
  22822. }
  22823. return bodyParameters;
  22824. };
  22825. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  22826. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22827. var registeredMesh = this._registeredMeshes[index];
  22828. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22829. if (registeredMesh.body) {
  22830. this._world.removeRigidBody(registeredMesh.body.body);
  22831. this._unbindBody(registeredMesh.body);
  22832. }
  22833. this._registeredMeshes.splice(index, 1);
  22834. return;
  22835. }
  22836. }
  22837. };
  22838. OimoJSPlugin.prototype._unbindBody = function (body) {
  22839. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22840. var registeredMesh = this._registeredMeshes[index];
  22841. if (registeredMesh.body === body) {
  22842. registeredMesh.body = null;
  22843. }
  22844. }
  22845. };
  22846. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  22847. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22848. var registeredMesh = this._registeredMeshes[index];
  22849. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22850. // Get object mass to have a behaviour similar to cannon.js
  22851. var mass = registeredMesh.body.body.massInfo.mass;
  22852. // The force is scaled with the mass of object
  22853. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  22854. return;
  22855. }
  22856. }
  22857. };
  22858. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22859. var body1 = null, body2 = null;
  22860. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22861. var registeredMesh = this._registeredMeshes[index];
  22862. if (registeredMesh.mesh === mesh1) {
  22863. body1 = registeredMesh.body.body;
  22864. }
  22865. else if (registeredMesh.mesh === mesh2) {
  22866. body2 = registeredMesh.body.body;
  22867. }
  22868. }
  22869. if (!body1 || !body2) {
  22870. return false;
  22871. }
  22872. if (!options) {
  22873. options = {};
  22874. }
  22875. new OIMO.Link({
  22876. type: options.type,
  22877. body1: body1,
  22878. body2: body2,
  22879. min: options.min,
  22880. max: options.max,
  22881. axe1: options.axe1,
  22882. axe2: options.axe2,
  22883. pos1: [pivot1.x, pivot1.y, pivot1.z],
  22884. pos2: [pivot2.x, pivot2.y, pivot2.z],
  22885. collision: options.collision,
  22886. spring: options.spring,
  22887. world: this._world
  22888. });
  22889. return true;
  22890. };
  22891. OimoJSPlugin.prototype.dispose = function () {
  22892. this._world.clear();
  22893. while (this._registeredMeshes.length) {
  22894. this.unregisterMesh(this._registeredMeshes[0].mesh);
  22895. }
  22896. };
  22897. OimoJSPlugin.prototype.isSupported = function () {
  22898. return OIMO !== undefined;
  22899. };
  22900. OimoJSPlugin.prototype._getLastShape = function (body) {
  22901. var lastShape = body.shapes;
  22902. while (lastShape.next) {
  22903. lastShape = lastShape.next;
  22904. }
  22905. return lastShape;
  22906. };
  22907. OimoJSPlugin.prototype.runOneStep = function (time) {
  22908. this._world.step();
  22909. // Update the position of all registered meshes
  22910. var i = this._registeredMeshes.length;
  22911. var m;
  22912. while (i--) {
  22913. var body = this._registeredMeshes[i].body.body;
  22914. var mesh = this._registeredMeshes[i].mesh;
  22915. var delta = this._registeredMeshes[i].delta;
  22916. if (!body.sleeping) {
  22917. if (body.shapes.next) {
  22918. var parentShape = this._getLastShape(body);
  22919. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  22920. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  22921. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  22922. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  22923. if (!mesh.rotationQuaternion) {
  22924. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22925. }
  22926. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  22927. mesh.computeWorldMatrix();
  22928. }
  22929. else {
  22930. m = body.getMatrix();
  22931. mtx = BABYLON.Matrix.FromArray(m);
  22932. // Body position
  22933. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  22934. if (!delta) {
  22935. mesh.position.x = bodyX;
  22936. mesh.position.y = bodyY;
  22937. mesh.position.z = bodyZ;
  22938. }
  22939. else {
  22940. mesh.position.x = bodyX + delta.x;
  22941. mesh.position.y = bodyY + delta.y;
  22942. mesh.position.z = bodyZ + delta.z;
  22943. }
  22944. if (!mesh.rotationQuaternion) {
  22945. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22946. }
  22947. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  22948. mesh.computeWorldMatrix();
  22949. }
  22950. }
  22951. }
  22952. };
  22953. return OimoJSPlugin;
  22954. })();
  22955. BABYLON.OimoJSPlugin = OimoJSPlugin;
  22956. })(BABYLON || (BABYLON = {}));
  22957. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  22958. var BABYLON;
  22959. (function (BABYLON) {
  22960. var PhysicsEngine = (function () {
  22961. function PhysicsEngine(plugin) {
  22962. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  22963. }
  22964. PhysicsEngine.prototype._initialize = function (gravity) {
  22965. this._currentPlugin.initialize();
  22966. this._setGravity(gravity);
  22967. };
  22968. PhysicsEngine.prototype._runOneStep = function (delta) {
  22969. if (delta > 0.1) {
  22970. delta = 0.1;
  22971. }
  22972. else if (delta <= 0) {
  22973. delta = 1.0 / 60.0;
  22974. }
  22975. this._currentPlugin.runOneStep(delta);
  22976. };
  22977. PhysicsEngine.prototype._setGravity = function (gravity) {
  22978. this.gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  22979. this._currentPlugin.setGravity(this.gravity);
  22980. };
  22981. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  22982. return this._currentPlugin.registerMesh(mesh, impostor, options);
  22983. };
  22984. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  22985. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  22986. };
  22987. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  22988. this._currentPlugin.unregisterMesh(mesh);
  22989. };
  22990. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  22991. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  22992. };
  22993. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  22994. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  22995. };
  22996. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  22997. this._currentPlugin.updateBodyPosition(mesh);
  22998. };
  22999. PhysicsEngine.prototype.dispose = function () {
  23000. this._currentPlugin.dispose();
  23001. };
  23002. PhysicsEngine.prototype.isSupported = function () {
  23003. return this._currentPlugin.isSupported();
  23004. };
  23005. // Statics
  23006. PhysicsEngine.NoImpostor = 0;
  23007. PhysicsEngine.SphereImpostor = 1;
  23008. PhysicsEngine.BoxImpostor = 2;
  23009. PhysicsEngine.PlaneImpostor = 3;
  23010. PhysicsEngine.MeshImpostor = 4;
  23011. PhysicsEngine.CapsuleImpostor = 5;
  23012. PhysicsEngine.ConeImpostor = 6;
  23013. PhysicsEngine.CylinderImpostor = 7;
  23014. PhysicsEngine.ConvexHullImpostor = 8;
  23015. PhysicsEngine.Epsilon = 0.001;
  23016. return PhysicsEngine;
  23017. })();
  23018. BABYLON.PhysicsEngine = PhysicsEngine;
  23019. })(BABYLON || (BABYLON = {}));
  23020. //# sourceMappingURL=babylon.physicsEngine.js.map
  23021. var BABYLON;
  23022. (function (BABYLON) {
  23023. var serializeLight = function (light) {
  23024. var serializationObject = {};
  23025. serializationObject.name = light.name;
  23026. serializationObject.id = light.id;
  23027. serializationObject.tags = BABYLON.Tags.GetTags(light);
  23028. if (light instanceof BABYLON.PointLight) {
  23029. serializationObject.type = 0;
  23030. serializationObject.position = light.position.asArray();
  23031. }
  23032. else if (light instanceof BABYLON.DirectionalLight) {
  23033. serializationObject.type = 1;
  23034. var directionalLight = light;
  23035. serializationObject.position = directionalLight.position.asArray();
  23036. serializationObject.direction = directionalLight.direction.asArray();
  23037. }
  23038. else if (light instanceof BABYLON.SpotLight) {
  23039. serializationObject.type = 2;
  23040. var spotLight = light;
  23041. serializationObject.position = spotLight.position.asArray();
  23042. serializationObject.direction = spotLight.position.asArray();
  23043. serializationObject.angle = spotLight.angle;
  23044. serializationObject.exponent = spotLight.exponent;
  23045. }
  23046. else if (light instanceof BABYLON.HemisphericLight) {
  23047. serializationObject.type = 3;
  23048. var hemisphericLight = light;
  23049. serializationObject.direction = hemisphericLight.direction.asArray();
  23050. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  23051. }
  23052. if (light.intensity) {
  23053. serializationObject.intensity = light.intensity;
  23054. }
  23055. serializationObject.range = light.range;
  23056. serializationObject.diffuse = light.diffuse.asArray();
  23057. serializationObject.specular = light.specular.asArray();
  23058. return serializationObject;
  23059. };
  23060. var serializeFresnelParameter = function (fresnelParameter) {
  23061. var serializationObject = {};
  23062. serializationObject.isEnabled = fresnelParameter.isEnabled;
  23063. serializationObject.leftColor = fresnelParameter.leftColor;
  23064. serializationObject.rightColor = fresnelParameter.rightColor;
  23065. serializationObject.bias = fresnelParameter.bias;
  23066. serializationObject.power = fresnelParameter.power;
  23067. return serializationObject;
  23068. };
  23069. var appendAnimations = function (source, destination) {
  23070. if (source.animations) {
  23071. destination.animations = [];
  23072. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  23073. var animation = source.animations[animationIndex];
  23074. destination.animations.push(serializeAnimation(animation));
  23075. }
  23076. }
  23077. };
  23078. var serializeCamera = function (camera) {
  23079. var serializationObject = {};
  23080. serializationObject.name = camera.name;
  23081. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  23082. serializationObject.id = camera.id;
  23083. serializationObject.position = camera.position.asArray();
  23084. // Parent
  23085. if (camera.parent) {
  23086. serializationObject.parentId = camera.parent.id;
  23087. }
  23088. serializationObject.fov = camera.fov;
  23089. serializationObject.minZ = camera.minZ;
  23090. serializationObject.maxZ = camera.maxZ;
  23091. serializationObject.inertia = camera.inertia;
  23092. //setting the type
  23093. if (camera instanceof BABYLON.FreeCamera) {
  23094. serializationObject.type = "FreeCamera";
  23095. }
  23096. else if (camera instanceof BABYLON.ArcRotateCamera) {
  23097. serializationObject.type = "ArcRotateCamera";
  23098. }
  23099. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23100. serializationObject.type = "AnaglyphArcRotateCamera";
  23101. }
  23102. else if (camera instanceof BABYLON.GamepadCamera) {
  23103. serializationObject.type = "GamepadCamera";
  23104. }
  23105. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  23106. serializationObject.type = "AnaglyphFreeCamera";
  23107. }
  23108. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  23109. serializationObject.type = "DeviceOrientationCamera";
  23110. }
  23111. else if (camera instanceof BABYLON.FollowCamera) {
  23112. serializationObject.type = "FollowCamera";
  23113. }
  23114. else if (camera instanceof BABYLON.TouchCamera) {
  23115. serializationObject.type = "TouchCamera";
  23116. }
  23117. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  23118. serializationObject.type = "VirtualJoysticksCamera";
  23119. }
  23120. else if (camera instanceof BABYLON.WebVRFreeCamera) {
  23121. serializationObject.type = "WebVRFreeCamera";
  23122. }
  23123. else if (camera instanceof BABYLON.VRDeviceOrientationFreeCamera) {
  23124. serializationObject.type = "VRDeviceOrientationFreeCamera";
  23125. }
  23126. //special properties of specific cameras
  23127. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23128. var arcCamera = camera;
  23129. serializationObject.alpha = arcCamera.alpha;
  23130. serializationObject.beta = arcCamera.beta;
  23131. serializationObject.radius = arcCamera.radius;
  23132. if (arcCamera.target && arcCamera.target.id) {
  23133. serializationObject.lockedTargetId = arcCamera.target.id;
  23134. }
  23135. }
  23136. else if (camera instanceof BABYLON.FollowCamera) {
  23137. var followCam = camera;
  23138. serializationObject.radius = followCam.radius;
  23139. serializationObject.heightOffset = followCam.heightOffset;
  23140. serializationObject.rotationOffset = followCam.rotationOffset;
  23141. }
  23142. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  23143. //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.
  23144. if (camera['_interaxialDistance'] !== undefined) {
  23145. serializationObject.interaxial_distance = BABYLON.Tools.ToDegrees(camera['_interaxialDistance']);
  23146. }
  23147. }
  23148. //general properties that not all cameras have. The [] is due to typescript's type safety
  23149. if (camera['speed'] !== undefined) {
  23150. serializationObject.speed = camera['speed'];
  23151. }
  23152. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  23153. serializationObject.target = camera['target'].asArray();
  23154. }
  23155. // Target
  23156. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  23157. serializationObject.rotation = camera['rotation'].asArray();
  23158. }
  23159. // Locked target
  23160. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  23161. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  23162. }
  23163. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  23164. serializationObject.applyGravity = camera['applyGravity'] || false;
  23165. if (camera['ellipsoid']) {
  23166. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  23167. }
  23168. // Animations
  23169. appendAnimations(camera, serializationObject);
  23170. // Layer mask
  23171. serializationObject.layerMask = camera.layerMask;
  23172. return serializationObject;
  23173. };
  23174. var serializeAnimation = function (animation) {
  23175. var serializationObject = {};
  23176. serializationObject.name = animation.name;
  23177. serializationObject.property = animation.targetProperty;
  23178. serializationObject.framePerSecond = animation.framePerSecond;
  23179. serializationObject.dataType = animation.dataType;
  23180. serializationObject.loopBehavior = animation.loopMode;
  23181. var dataType = animation.dataType;
  23182. serializationObject.keys = [];
  23183. var keys = animation.getKeys();
  23184. for (var index = 0; index < keys.length; index++) {
  23185. var animationKey = keys[index];
  23186. var key = {};
  23187. key.frame = animationKey.frame;
  23188. switch (dataType) {
  23189. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  23190. key.values = [animationKey.value];
  23191. break;
  23192. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  23193. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  23194. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  23195. key.values = animationKey.value.asArray();
  23196. break;
  23197. }
  23198. serializationObject.keys.push(key);
  23199. }
  23200. return serializationObject;
  23201. };
  23202. var serializeMultiMaterial = function (material) {
  23203. var serializationObject = {};
  23204. serializationObject.name = material.name;
  23205. serializationObject.id = material.id;
  23206. serializationObject.tags = BABYLON.Tags.GetTags(material);
  23207. serializationObject.materials = [];
  23208. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  23209. var subMat = material.subMaterials[matIndex];
  23210. if (subMat) {
  23211. serializationObject.materials.push(subMat.id);
  23212. }
  23213. else {
  23214. serializationObject.materials.push(null);
  23215. }
  23216. }
  23217. return serializationObject;
  23218. };
  23219. var serializeMaterial = function (material) {
  23220. var serializationObject = {};
  23221. serializationObject.name = material.name;
  23222. serializationObject.ambient = material.ambientColor.asArray();
  23223. serializationObject.diffuse = material.diffuseColor.asArray();
  23224. serializationObject.specular = material.specularColor.asArray();
  23225. serializationObject.specularPower = material.specularPower;
  23226. serializationObject.emissive = material.emissiveColor.asArray();
  23227. serializationObject.alpha = material.alpha;
  23228. serializationObject.id = material.id;
  23229. serializationObject.tags = BABYLON.Tags.GetTags(material);
  23230. serializationObject.backFaceCulling = material.backFaceCulling;
  23231. if (material.diffuseTexture) {
  23232. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  23233. }
  23234. if (material.diffuseFresnelParameters) {
  23235. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  23236. }
  23237. if (material.ambientTexture) {
  23238. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  23239. }
  23240. if (material.opacityTexture) {
  23241. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  23242. }
  23243. if (material.opacityFresnelParameters) {
  23244. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  23245. }
  23246. if (material.reflectionTexture) {
  23247. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  23248. }
  23249. if (material.reflectionFresnelParameters) {
  23250. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  23251. }
  23252. if (material.emissiveTexture) {
  23253. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  23254. }
  23255. if (material.emissiveFresnelParameters) {
  23256. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  23257. }
  23258. if (material.specularTexture) {
  23259. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  23260. }
  23261. if (material.bumpTexture) {
  23262. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  23263. }
  23264. return serializationObject;
  23265. };
  23266. var serializeTexture = function (texture) {
  23267. var serializationObject = {};
  23268. if (!texture.name) {
  23269. return null;
  23270. }
  23271. if (texture instanceof BABYLON.CubeTexture) {
  23272. serializationObject.name = texture.name;
  23273. serializationObject.hasAlpha = texture.hasAlpha;
  23274. serializationObject.level = texture.level;
  23275. serializationObject.coordinatesMode = texture.coordinatesMode;
  23276. return serializationObject;
  23277. }
  23278. if (texture instanceof BABYLON.MirrorTexture) {
  23279. var mirrorTexture = texture;
  23280. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  23281. serializationObject.renderList = [];
  23282. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  23283. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  23284. }
  23285. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  23286. }
  23287. else if (texture instanceof BABYLON.RenderTargetTexture) {
  23288. var renderTargetTexture = texture;
  23289. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  23290. serializationObject.renderList = [];
  23291. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  23292. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  23293. }
  23294. }
  23295. var regularTexture = texture;
  23296. serializationObject.name = texture.name;
  23297. serializationObject.hasAlpha = texture.hasAlpha;
  23298. serializationObject.level = texture.level;
  23299. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  23300. serializationObject.coordinatesMode = texture.coordinatesMode;
  23301. serializationObject.uOffset = regularTexture.uOffset;
  23302. serializationObject.vOffset = regularTexture.vOffset;
  23303. serializationObject.uScale = regularTexture.uScale;
  23304. serializationObject.vScale = regularTexture.vScale;
  23305. serializationObject.uAng = regularTexture.uAng;
  23306. serializationObject.vAng = regularTexture.vAng;
  23307. serializationObject.wAng = regularTexture.wAng;
  23308. serializationObject.wrapU = texture.wrapU;
  23309. serializationObject.wrapV = texture.wrapV;
  23310. // Animations
  23311. appendAnimations(texture, serializationObject);
  23312. return serializationObject;
  23313. };
  23314. var serializeSkeleton = function (skeleton) {
  23315. var serializationObject = {};
  23316. serializationObject.name = skeleton.name;
  23317. serializationObject.id = skeleton.id;
  23318. serializationObject.bones = [];
  23319. for (var index = 0; index < skeleton.bones.length; index++) {
  23320. var bone = skeleton.bones[index];
  23321. var serializedBone = {
  23322. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  23323. name: bone.name,
  23324. matrix: bone.getLocalMatrix().toArray()
  23325. };
  23326. serializationObject.bones.push(serializedBone);
  23327. if (bone.animations && bone.animations.length > 0) {
  23328. serializedBone.animation = serializeAnimation(bone.animations[0]);
  23329. }
  23330. }
  23331. return serializationObject;
  23332. };
  23333. var serializeParticleSystem = function (particleSystem) {
  23334. var serializationObject = {};
  23335. serializationObject.emitterId = particleSystem.emitter.id;
  23336. serializationObject.capacity = particleSystem.getCapacity();
  23337. if (particleSystem.particleTexture) {
  23338. serializationObject.textureName = particleSystem.particleTexture.name;
  23339. }
  23340. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  23341. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  23342. serializationObject.minSize = particleSystem.minSize;
  23343. serializationObject.maxSize = particleSystem.maxSize;
  23344. serializationObject.minLifeTime = particleSystem.minLifeTime;
  23345. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  23346. serializationObject.emitRate = particleSystem.emitRate;
  23347. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  23348. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  23349. serializationObject.gravity = particleSystem.gravity.asArray();
  23350. serializationObject.direction1 = particleSystem.direction1.asArray();
  23351. serializationObject.direction2 = particleSystem.direction2.asArray();
  23352. serializationObject.color1 = particleSystem.color1.asArray();
  23353. serializationObject.color2 = particleSystem.color2.asArray();
  23354. serializationObject.colorDead = particleSystem.colorDead.asArray();
  23355. serializationObject.updateSpeed = particleSystem.updateSpeed;
  23356. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  23357. serializationObject.textureMask = particleSystem.textureMask.asArray();
  23358. serializationObject.blendMode = particleSystem.blendMode;
  23359. return serializationObject;
  23360. };
  23361. var serializeLensFlareSystem = function (lensFlareSystem) {
  23362. var serializationObject = {};
  23363. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  23364. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  23365. serializationObject.flares = [];
  23366. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  23367. var flare = lensFlareSystem.lensFlares[index];
  23368. serializationObject.flares.push({
  23369. size: flare.size,
  23370. position: flare.position,
  23371. color: flare.color.asArray(),
  23372. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  23373. });
  23374. }
  23375. return serializationObject;
  23376. };
  23377. var serializeShadowGenerator = function (light) {
  23378. var serializationObject = {};
  23379. var shadowGenerator = light.getShadowGenerator();
  23380. serializationObject.lightId = light.id;
  23381. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  23382. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  23383. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  23384. serializationObject.renderList = [];
  23385. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  23386. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  23387. serializationObject.renderList.push(mesh.id);
  23388. }
  23389. return serializationObject;
  23390. };
  23391. var serializedGeometries = [];
  23392. var serializeGeometry = function (geometry, serializationGeometries) {
  23393. if (serializedGeometries[geometry.id]) {
  23394. return;
  23395. }
  23396. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  23397. serializationGeometries.boxes.push(serializeBox(geometry));
  23398. }
  23399. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  23400. serializationGeometries.spheres.push(serializeSphere(geometry));
  23401. }
  23402. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  23403. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  23404. }
  23405. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  23406. serializationGeometries.toruses.push(serializeTorus(geometry));
  23407. }
  23408. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  23409. serializationGeometries.grounds.push(serializeGround(geometry));
  23410. }
  23411. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  23412. serializationGeometries.planes.push(serializePlane(geometry));
  23413. }
  23414. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  23415. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  23416. }
  23417. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  23418. throw new Error("Unknow primitive type");
  23419. }
  23420. else {
  23421. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  23422. }
  23423. serializedGeometries[geometry.id] = true;
  23424. };
  23425. var serializeGeometryBase = function (geometry) {
  23426. var serializationObject = {};
  23427. serializationObject.id = geometry.id;
  23428. if (BABYLON.Tags.HasTags(geometry)) {
  23429. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  23430. }
  23431. return serializationObject;
  23432. };
  23433. var serializeVertexData = function (vertexData) {
  23434. var serializationObject = serializeGeometryBase(vertexData);
  23435. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23436. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23437. }
  23438. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23439. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23440. }
  23441. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23442. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  23443. }
  23444. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23445. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  23446. }
  23447. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  23448. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  23449. }
  23450. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23451. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23452. serializationObject.matricesIndices._isExpanded = true;
  23453. }
  23454. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23455. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23456. }
  23457. serializationObject.indices = vertexData.getIndices();
  23458. return serializationObject;
  23459. };
  23460. var serializePrimitive = function (primitive) {
  23461. var serializationObject = serializeGeometryBase(primitive);
  23462. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  23463. return serializationObject;
  23464. };
  23465. var serializeBox = function (box) {
  23466. var serializationObject = serializePrimitive(box);
  23467. serializationObject.size = box.size;
  23468. return serializationObject;
  23469. };
  23470. var serializeSphere = function (sphere) {
  23471. var serializationObject = serializePrimitive(sphere);
  23472. serializationObject.segments = sphere.segments;
  23473. serializationObject.diameter = sphere.diameter;
  23474. return serializationObject;
  23475. };
  23476. var serializeCylinder = function (cylinder) {
  23477. var serializationObject = serializePrimitive(cylinder);
  23478. serializationObject.height = cylinder.height;
  23479. serializationObject.diameterTop = cylinder.diameterTop;
  23480. serializationObject.diameterBottom = cylinder.diameterBottom;
  23481. serializationObject.tessellation = cylinder.tessellation;
  23482. return serializationObject;
  23483. };
  23484. var serializeTorus = function (torus) {
  23485. var serializationObject = serializePrimitive(torus);
  23486. serializationObject.diameter = torus.diameter;
  23487. serializationObject.thickness = torus.thickness;
  23488. serializationObject.tessellation = torus.tessellation;
  23489. return serializationObject;
  23490. };
  23491. var serializeGround = function (ground) {
  23492. var serializationObject = serializePrimitive(ground);
  23493. serializationObject.width = ground.width;
  23494. serializationObject.height = ground.height;
  23495. serializationObject.subdivisions = ground.subdivisions;
  23496. return serializationObject;
  23497. };
  23498. var serializePlane = function (plane) {
  23499. var serializationObject = serializePrimitive(plane);
  23500. serializationObject.size = plane.size;
  23501. return serializationObject;
  23502. };
  23503. var serializeTorusKnot = function (torusKnot) {
  23504. var serializationObject = serializePrimitive(torusKnot);
  23505. serializationObject.radius = torusKnot.radius;
  23506. serializationObject.tube = torusKnot.tube;
  23507. serializationObject.radialSegments = torusKnot.radialSegments;
  23508. serializationObject.tubularSegments = torusKnot.tubularSegments;
  23509. serializationObject.p = torusKnot.p;
  23510. serializationObject.q = torusKnot.q;
  23511. return serializationObject;
  23512. };
  23513. var serializeMesh = function (mesh, serializationScene) {
  23514. var serializationObject = {};
  23515. serializationObject.name = mesh.name;
  23516. serializationObject.id = mesh.id;
  23517. if (BABYLON.Tags.HasTags(mesh)) {
  23518. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  23519. }
  23520. serializationObject.position = mesh.position.asArray();
  23521. if (mesh.rotationQuaternion) {
  23522. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  23523. }
  23524. else if (mesh.rotation) {
  23525. serializationObject.rotation = mesh.rotation.asArray();
  23526. }
  23527. serializationObject.scaling = mesh.scaling.asArray();
  23528. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  23529. serializationObject.isEnabled = mesh.isEnabled();
  23530. serializationObject.isVisible = mesh.isVisible;
  23531. serializationObject.infiniteDistance = mesh.infiniteDistance;
  23532. serializationObject.pickable = mesh.isPickable;
  23533. serializationObject.receiveShadows = mesh.receiveShadows;
  23534. serializationObject.billboardMode = mesh.billboardMode;
  23535. serializationObject.visibility = mesh.visibility;
  23536. serializationObject.checkCollisions = mesh.checkCollisions;
  23537. // Parent
  23538. if (mesh.parent) {
  23539. serializationObject.parentId = mesh.parent.id;
  23540. }
  23541. // Geometry
  23542. var geometry = mesh._geometry;
  23543. if (geometry) {
  23544. var geometryId = geometry.id;
  23545. serializationObject.geometryId = geometryId;
  23546. if (!mesh.getScene().getGeometryByID(geometryId)) {
  23547. // 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
  23548. serializeGeometry(geometry, serializationScene.geometries);
  23549. }
  23550. // SubMeshes
  23551. serializationObject.subMeshes = [];
  23552. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  23553. var subMesh = mesh.subMeshes[subIndex];
  23554. serializationObject.subMeshes.push({
  23555. materialIndex: subMesh.materialIndex,
  23556. verticesStart: subMesh.verticesStart,
  23557. verticesCount: subMesh.verticesCount,
  23558. indexStart: subMesh.indexStart,
  23559. indexCount: subMesh.indexCount
  23560. });
  23561. }
  23562. }
  23563. // Material
  23564. if (mesh.material) {
  23565. serializationObject.materialId = mesh.material.id;
  23566. }
  23567. else {
  23568. mesh.material = null;
  23569. }
  23570. // Skeleton
  23571. if (mesh.skeleton) {
  23572. serializationObject.skeletonId = mesh.skeleton.id;
  23573. }
  23574. // Physics
  23575. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  23576. serializationObject.physicsMass = mesh.getPhysicsMass();
  23577. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  23578. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  23579. switch (mesh.getPhysicsImpostor()) {
  23580. case BABYLON.PhysicsEngine.BoxImpostor:
  23581. serializationObject.physicsImpostor = 1;
  23582. break;
  23583. case BABYLON.PhysicsEngine.SphereImpostor:
  23584. serializationObject.physicsImpostor = 2;
  23585. break;
  23586. }
  23587. }
  23588. // Instances
  23589. serializationObject.instances = [];
  23590. for (var index = 0; index < mesh.instances.length; index++) {
  23591. var instance = mesh.instances[index];
  23592. var serializationInstance = {
  23593. name: instance.name,
  23594. position: instance.position,
  23595. rotation: instance.rotation,
  23596. rotationQuaternion: instance.rotationQuaternion,
  23597. scaling: instance.scaling
  23598. };
  23599. serializationObject.instances.push(serializationInstance);
  23600. // Animations
  23601. appendAnimations(instance, serializationInstance);
  23602. }
  23603. // Animations
  23604. appendAnimations(mesh, serializationObject);
  23605. // Layer mask
  23606. serializationObject.layerMask = mesh.layerMask;
  23607. return serializationObject;
  23608. };
  23609. var SceneSerializer = (function () {
  23610. function SceneSerializer() {
  23611. }
  23612. SceneSerializer.Serialize = function (scene) {
  23613. var serializationObject = {};
  23614. // Scene
  23615. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  23616. serializationObject.autoClear = scene.autoClear;
  23617. serializationObject.clearColor = scene.clearColor.asArray();
  23618. serializationObject.ambientColor = scene.ambientColor.asArray();
  23619. serializationObject.gravity = scene.gravity.asArray();
  23620. // Fog
  23621. if (scene.fogMode && scene.fogMode !== 0) {
  23622. serializationObject.fogMode = scene.fogMode;
  23623. serializationObject.fogColor = scene.fogColor.asArray();
  23624. serializationObject.fogStart = scene.fogStart;
  23625. serializationObject.fogEnd = scene.fogEnd;
  23626. serializationObject.fogDensity = scene.fogDensity;
  23627. }
  23628. // Lights
  23629. serializationObject.lights = [];
  23630. for (var index = 0; index < scene.lights.length; index++) {
  23631. var light = scene.lights[index];
  23632. serializationObject.lights.push(serializeLight(light));
  23633. }
  23634. // Cameras
  23635. serializationObject.cameras = [];
  23636. for (index = 0; index < scene.cameras.length; index++) {
  23637. var camera = scene.cameras[index];
  23638. serializationObject.cameras.push(serializeCamera(camera));
  23639. }
  23640. if (scene.activeCamera) {
  23641. serializationObject.activeCameraID = scene.activeCamera.id;
  23642. }
  23643. // Materials
  23644. serializationObject.materials = [];
  23645. serializationObject.multiMaterials = [];
  23646. for (index = 0; index < scene.materials.length; index++) {
  23647. var material = scene.materials[index];
  23648. if (material instanceof BABYLON.StandardMaterial) {
  23649. serializationObject.materials.push(serializeMaterial(material));
  23650. }
  23651. else if (material instanceof BABYLON.MultiMaterial) {
  23652. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  23653. }
  23654. }
  23655. // Skeletons
  23656. serializationObject.skeletons = [];
  23657. for (index = 0; index < scene.skeletons.length; index++) {
  23658. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  23659. }
  23660. // Geometries
  23661. serializationObject.geometries = {};
  23662. serializationObject.geometries.boxes = [];
  23663. serializationObject.geometries.spheres = [];
  23664. serializationObject.geometries.cylinders = [];
  23665. serializationObject.geometries.toruses = [];
  23666. serializationObject.geometries.grounds = [];
  23667. serializationObject.geometries.planes = [];
  23668. serializationObject.geometries.torusKnots = [];
  23669. serializationObject.geometries.vertexData = [];
  23670. serializedGeometries = [];
  23671. var geometries = scene.getGeometries();
  23672. for (index = 0; index < geometries.length; index++) {
  23673. var geometry = geometries[index];
  23674. if (geometry.isReady()) {
  23675. serializeGeometry(geometry, serializationObject.geometries);
  23676. }
  23677. }
  23678. // Meshes
  23679. serializationObject.meshes = [];
  23680. for (index = 0; index < scene.meshes.length; index++) {
  23681. var abstractMesh = scene.meshes[index];
  23682. if (abstractMesh instanceof BABYLON.Mesh) {
  23683. var mesh = abstractMesh;
  23684. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  23685. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  23686. }
  23687. }
  23688. }
  23689. // Particles Systems
  23690. serializationObject.particleSystems = [];
  23691. for (index = 0; index < scene.particleSystems.length; index++) {
  23692. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  23693. }
  23694. // Lens flares
  23695. serializationObject.lensFlareSystems = [];
  23696. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  23697. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  23698. }
  23699. // Shadows
  23700. serializationObject.shadowGenerators = [];
  23701. for (index = 0; index < scene.lights.length; index++) {
  23702. light = scene.lights[index];
  23703. if (light.getShadowGenerator()) {
  23704. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  23705. }
  23706. }
  23707. return serializationObject;
  23708. };
  23709. return SceneSerializer;
  23710. })();
  23711. BABYLON.SceneSerializer = SceneSerializer;
  23712. })(BABYLON || (BABYLON = {}));
  23713. //# sourceMappingURL=babylon.sceneSerializer.js.map
  23714. var BABYLON;
  23715. (function (BABYLON) {
  23716. // Unique ID when we import meshes from Babylon to CSG
  23717. var currentCSGMeshId = 0;
  23718. // # class Vertex
  23719. // Represents a vertex of a polygon. Use your own vertex class instead of this
  23720. // one to provide additional features like texture coordinates and vertex
  23721. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  23722. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  23723. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  23724. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  23725. // is not used anywhere else.
  23726. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  23727. var Vertex = (function () {
  23728. function Vertex(pos, normal, uv) {
  23729. this.pos = pos;
  23730. this.normal = normal;
  23731. this.uv = uv;
  23732. }
  23733. Vertex.prototype.clone = function () {
  23734. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  23735. };
  23736. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  23737. // orientation of a polygon is flipped.
  23738. Vertex.prototype.flip = function () {
  23739. this.normal = this.normal.scale(-1);
  23740. };
  23741. // Create a new vertex between this vertex and `other` by linearly
  23742. // interpolating all properties using a parameter of `t`. Subclasses should
  23743. // override this to interpolate additional properties.
  23744. Vertex.prototype.interpolate = function (other, t) {
  23745. 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));
  23746. };
  23747. return Vertex;
  23748. })();
  23749. // # class Plane
  23750. // Represents a plane in 3D space.
  23751. var Plane = (function () {
  23752. function Plane(normal, w) {
  23753. this.normal = normal;
  23754. this.w = w;
  23755. }
  23756. Plane.FromPoints = function (a, b, c) {
  23757. var v0 = c.subtract(a);
  23758. var v1 = b.subtract(a);
  23759. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  23760. return null;
  23761. }
  23762. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  23763. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  23764. };
  23765. Plane.prototype.clone = function () {
  23766. return new Plane(this.normal.clone(), this.w);
  23767. };
  23768. Plane.prototype.flip = function () {
  23769. this.normal.scaleInPlace(-1);
  23770. this.w = -this.w;
  23771. };
  23772. // Split `polygon` by this plane if needed, then put the polygon or polygon
  23773. // fragments in the appropriate lists. Coplanar polygons go into either
  23774. // `coplanarFront` or `coplanarBack` depending on their orientation with
  23775. // respect to this plane. Polygons in front or in back of this plane go into
  23776. // either `front` or `back`.
  23777. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  23778. var COPLANAR = 0;
  23779. var FRONT = 1;
  23780. var BACK = 2;
  23781. var SPANNING = 3;
  23782. // Classify each point as well as the entire polygon into one of the above
  23783. // four classes.
  23784. var polygonType = 0;
  23785. var types = [];
  23786. for (var i = 0; i < polygon.vertices.length; i++) {
  23787. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  23788. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  23789. polygonType |= type;
  23790. types.push(type);
  23791. }
  23792. // Put the polygon in the correct list, splitting it when necessary.
  23793. switch (polygonType) {
  23794. case COPLANAR:
  23795. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  23796. break;
  23797. case FRONT:
  23798. front.push(polygon);
  23799. break;
  23800. case BACK:
  23801. back.push(polygon);
  23802. break;
  23803. case SPANNING:
  23804. var f = [], b = [];
  23805. for (i = 0; i < polygon.vertices.length; i++) {
  23806. var j = (i + 1) % polygon.vertices.length;
  23807. var ti = types[i], tj = types[j];
  23808. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  23809. if (ti != BACK)
  23810. f.push(vi);
  23811. if (ti != FRONT)
  23812. b.push(ti != BACK ? vi.clone() : vi);
  23813. if ((ti | tj) == SPANNING) {
  23814. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  23815. var v = vi.interpolate(vj, t);
  23816. f.push(v);
  23817. b.push(v.clone());
  23818. }
  23819. }
  23820. if (f.length >= 3) {
  23821. var poly = new Polygon(f, polygon.shared);
  23822. if (poly.plane)
  23823. front.push(poly);
  23824. }
  23825. if (b.length >= 3) {
  23826. poly = new Polygon(b, polygon.shared);
  23827. if (poly.plane)
  23828. back.push(poly);
  23829. }
  23830. break;
  23831. }
  23832. };
  23833. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  23834. // point is on the plane.
  23835. Plane.EPSILON = 1e-5;
  23836. return Plane;
  23837. })();
  23838. // # class Polygon
  23839. // Represents a convex polygon. The vertices used to initialize a polygon must
  23840. // be coplanar and form a convex loop.
  23841. //
  23842. // Each convex polygon has a `shared` property, which is shared between all
  23843. // polygons that are clones of each other or were split from the same polygon.
  23844. // This can be used to define per-polygon properties (such as surface color).
  23845. var Polygon = (function () {
  23846. function Polygon(vertices, shared) {
  23847. this.vertices = vertices;
  23848. this.shared = shared;
  23849. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  23850. }
  23851. Polygon.prototype.clone = function () {
  23852. var vertices = this.vertices.map(function (v) { return v.clone(); });
  23853. return new Polygon(vertices, this.shared);
  23854. };
  23855. Polygon.prototype.flip = function () {
  23856. this.vertices.reverse().map(function (v) { v.flip(); });
  23857. this.plane.flip();
  23858. };
  23859. return Polygon;
  23860. })();
  23861. // # class Node
  23862. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  23863. // by picking a polygon to split along. That polygon (and all other coplanar
  23864. // polygons) are added directly to that node and the other polygons are added to
  23865. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  23866. // no distinction between internal and leaf nodes.
  23867. var Node = (function () {
  23868. function Node(polygons) {
  23869. this.plane = null;
  23870. this.front = null;
  23871. this.back = null;
  23872. this.polygons = [];
  23873. if (polygons) {
  23874. this.build(polygons);
  23875. }
  23876. }
  23877. Node.prototype.clone = function () {
  23878. var node = new Node();
  23879. node.plane = this.plane && this.plane.clone();
  23880. node.front = this.front && this.front.clone();
  23881. node.back = this.back && this.back.clone();
  23882. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  23883. return node;
  23884. };
  23885. // Convert solid space to empty space and empty space to solid space.
  23886. Node.prototype.invert = function () {
  23887. for (var i = 0; i < this.polygons.length; i++) {
  23888. this.polygons[i].flip();
  23889. }
  23890. if (this.plane) {
  23891. this.plane.flip();
  23892. }
  23893. if (this.front) {
  23894. this.front.invert();
  23895. }
  23896. if (this.back) {
  23897. this.back.invert();
  23898. }
  23899. var temp = this.front;
  23900. this.front = this.back;
  23901. this.back = temp;
  23902. };
  23903. // Recursively remove all polygons in `polygons` that are inside this BSP
  23904. // tree.
  23905. Node.prototype.clipPolygons = function (polygons) {
  23906. if (!this.plane)
  23907. return polygons.slice();
  23908. var front = [], back = [];
  23909. for (var i = 0; i < polygons.length; i++) {
  23910. this.plane.splitPolygon(polygons[i], front, back, front, back);
  23911. }
  23912. if (this.front) {
  23913. front = this.front.clipPolygons(front);
  23914. }
  23915. if (this.back) {
  23916. back = this.back.clipPolygons(back);
  23917. }
  23918. else {
  23919. back = [];
  23920. }
  23921. return front.concat(back);
  23922. };
  23923. // Remove all polygons in this BSP tree that are inside the other BSP tree
  23924. // `bsp`.
  23925. Node.prototype.clipTo = function (bsp) {
  23926. this.polygons = bsp.clipPolygons(this.polygons);
  23927. if (this.front)
  23928. this.front.clipTo(bsp);
  23929. if (this.back)
  23930. this.back.clipTo(bsp);
  23931. };
  23932. // Return a list of all polygons in this BSP tree.
  23933. Node.prototype.allPolygons = function () {
  23934. var polygons = this.polygons.slice();
  23935. if (this.front)
  23936. polygons = polygons.concat(this.front.allPolygons());
  23937. if (this.back)
  23938. polygons = polygons.concat(this.back.allPolygons());
  23939. return polygons;
  23940. };
  23941. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  23942. // new polygons are filtered down to the bottom of the tree and become new
  23943. // nodes there. Each set of polygons is partitioned using the first polygon
  23944. // (no heuristic is used to pick a good split).
  23945. Node.prototype.build = function (polygons) {
  23946. if (!polygons.length)
  23947. return;
  23948. if (!this.plane)
  23949. this.plane = polygons[0].plane.clone();
  23950. var front = [], back = [];
  23951. for (var i = 0; i < polygons.length; i++) {
  23952. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  23953. }
  23954. if (front.length) {
  23955. if (!this.front)
  23956. this.front = new Node();
  23957. this.front.build(front);
  23958. }
  23959. if (back.length) {
  23960. if (!this.back)
  23961. this.back = new Node();
  23962. this.back.build(back);
  23963. }
  23964. };
  23965. return Node;
  23966. })();
  23967. var CSG = (function () {
  23968. function CSG() {
  23969. this.polygons = new Array();
  23970. }
  23971. // Convert BABYLON.Mesh to BABYLON.CSG
  23972. CSG.FromMesh = function (mesh) {
  23973. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  23974. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  23975. if (mesh instanceof BABYLON.Mesh) {
  23976. mesh.computeWorldMatrix(true);
  23977. matrix = mesh.getWorldMatrix();
  23978. meshPosition = mesh.position.clone();
  23979. meshRotation = mesh.rotation.clone();
  23980. if (mesh.rotationQuaternion) {
  23981. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  23982. }
  23983. meshScaling = mesh.scaling.clone();
  23984. }
  23985. else {
  23986. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  23987. }
  23988. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  23989. var subMeshes = mesh.subMeshes;
  23990. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  23991. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  23992. vertices = [];
  23993. for (var j = 0; j < 3; j++) {
  23994. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  23995. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  23996. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  23997. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  23998. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  23999. vertex = new Vertex(position, normal, uv);
  24000. vertices.push(vertex);
  24001. }
  24002. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  24003. // To handle the case of degenerated triangle
  24004. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  24005. if (polygon.plane)
  24006. polygons.push(polygon);
  24007. }
  24008. }
  24009. var csg = CSG.FromPolygons(polygons);
  24010. csg.matrix = matrix;
  24011. csg.position = meshPosition;
  24012. csg.rotation = meshRotation;
  24013. csg.scaling = meshScaling;
  24014. csg.rotationQuaternion = meshRotationQuaternion;
  24015. currentCSGMeshId++;
  24016. return csg;
  24017. };
  24018. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  24019. CSG.FromPolygons = function (polygons) {
  24020. var csg = new CSG();
  24021. csg.polygons = polygons;
  24022. return csg;
  24023. };
  24024. CSG.prototype.clone = function () {
  24025. var csg = new CSG();
  24026. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  24027. csg.copyTransformAttributes(this);
  24028. return csg;
  24029. };
  24030. CSG.prototype.toPolygons = function () {
  24031. return this.polygons;
  24032. };
  24033. CSG.prototype.union = function (csg) {
  24034. var a = new Node(this.clone().polygons);
  24035. var b = new Node(csg.clone().polygons);
  24036. a.clipTo(b);
  24037. b.clipTo(a);
  24038. b.invert();
  24039. b.clipTo(a);
  24040. b.invert();
  24041. a.build(b.allPolygons());
  24042. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  24043. };
  24044. CSG.prototype.unionInPlace = function (csg) {
  24045. var a = new Node(this.polygons);
  24046. var b = new Node(csg.polygons);
  24047. a.clipTo(b);
  24048. b.clipTo(a);
  24049. b.invert();
  24050. b.clipTo(a);
  24051. b.invert();
  24052. a.build(b.allPolygons());
  24053. this.polygons = a.allPolygons();
  24054. };
  24055. CSG.prototype.subtract = function (csg) {
  24056. var a = new Node(this.clone().polygons);
  24057. var b = new Node(csg.clone().polygons);
  24058. a.invert();
  24059. a.clipTo(b);
  24060. b.clipTo(a);
  24061. b.invert();
  24062. b.clipTo(a);
  24063. b.invert();
  24064. a.build(b.allPolygons());
  24065. a.invert();
  24066. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  24067. };
  24068. CSG.prototype.subtractInPlace = function (csg) {
  24069. var a = new Node(this.polygons);
  24070. var b = new Node(csg.polygons);
  24071. a.invert();
  24072. a.clipTo(b);
  24073. b.clipTo(a);
  24074. b.invert();
  24075. b.clipTo(a);
  24076. b.invert();
  24077. a.build(b.allPolygons());
  24078. a.invert();
  24079. this.polygons = a.allPolygons();
  24080. };
  24081. CSG.prototype.intersect = function (csg) {
  24082. var a = new Node(this.clone().polygons);
  24083. var b = new Node(csg.clone().polygons);
  24084. a.invert();
  24085. b.clipTo(a);
  24086. b.invert();
  24087. a.clipTo(b);
  24088. b.clipTo(a);
  24089. a.build(b.allPolygons());
  24090. a.invert();
  24091. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  24092. };
  24093. CSG.prototype.intersectInPlace = function (csg) {
  24094. var a = new Node(this.polygons);
  24095. var b = new Node(csg.polygons);
  24096. a.invert();
  24097. b.clipTo(a);
  24098. b.invert();
  24099. a.clipTo(b);
  24100. b.clipTo(a);
  24101. a.build(b.allPolygons());
  24102. a.invert();
  24103. this.polygons = a.allPolygons();
  24104. };
  24105. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  24106. // not modified.
  24107. CSG.prototype.inverse = function () {
  24108. var csg = this.clone();
  24109. csg.inverseInPlace();
  24110. return csg;
  24111. };
  24112. CSG.prototype.inverseInPlace = function () {
  24113. this.polygons.map(function (p) { p.flip(); });
  24114. };
  24115. // This is used to keep meshes transformations so they can be restored
  24116. // when we build back a Babylon Mesh
  24117. // NB : All CSG operations are performed in world coordinates
  24118. CSG.prototype.copyTransformAttributes = function (csg) {
  24119. this.matrix = csg.matrix;
  24120. this.position = csg.position;
  24121. this.rotation = csg.rotation;
  24122. this.scaling = csg.scaling;
  24123. this.rotationQuaternion = csg.rotationQuaternion;
  24124. return this;
  24125. };
  24126. // Build Raw mesh from CSG
  24127. // Coordinates here are in world space
  24128. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  24129. var matrix = this.matrix.clone();
  24130. matrix.invert();
  24131. 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;
  24132. if (keepSubMeshes) {
  24133. // Sort Polygons, since subMeshes are indices range
  24134. polygons.sort(function (a, b) {
  24135. if (a.shared.meshId === b.shared.meshId) {
  24136. return a.shared.subMeshId - b.shared.subMeshId;
  24137. }
  24138. else {
  24139. return a.shared.meshId - b.shared.meshId;
  24140. }
  24141. });
  24142. }
  24143. for (var i = 0, il = polygons.length; i < il; i++) {
  24144. polygon = polygons[i];
  24145. // Building SubMeshes
  24146. if (!subMesh_dict[polygon.shared.meshId]) {
  24147. subMesh_dict[polygon.shared.meshId] = {};
  24148. }
  24149. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  24150. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  24151. indexStart: +Infinity,
  24152. indexEnd: -Infinity,
  24153. materialIndex: polygon.shared.materialIndex
  24154. };
  24155. }
  24156. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  24157. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  24158. polygonIndices[0] = 0;
  24159. polygonIndices[1] = j - 1;
  24160. polygonIndices[2] = j;
  24161. for (var k = 0; k < 3; k++) {
  24162. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  24163. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  24164. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  24165. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  24166. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  24167. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  24168. // Check if 2 points can be merged
  24169. if (!(typeof vertex_idx !== 'undefined' &&
  24170. normals[vertex_idx * 3] === localNormal.x &&
  24171. normals[vertex_idx * 3 + 1] === localNormal.y &&
  24172. normals[vertex_idx * 3 + 2] === localNormal.z &&
  24173. uvs[vertex_idx * 2] === uv.x &&
  24174. uvs[vertex_idx * 2 + 1] === uv.y)) {
  24175. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  24176. uvs.push(uv.x, uv.y);
  24177. normals.push(normal.x, normal.y, normal.z);
  24178. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  24179. }
  24180. indices.push(vertex_idx);
  24181. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  24182. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  24183. currentIndex++;
  24184. }
  24185. }
  24186. }
  24187. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  24188. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  24189. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  24190. mesh.setIndices(indices);
  24191. if (keepSubMeshes) {
  24192. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  24193. var materialIndexOffset = 0, materialMaxIndex;
  24194. mesh.subMeshes.length = 0;
  24195. for (var m in subMesh_dict) {
  24196. materialMaxIndex = -1;
  24197. for (var sm in subMesh_dict[m]) {
  24198. subMesh_obj = subMesh_dict[m][sm];
  24199. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  24200. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  24201. }
  24202. materialIndexOffset += ++materialMaxIndex;
  24203. }
  24204. }
  24205. return mesh;
  24206. };
  24207. // Build Mesh from CSG taking material and transforms into account
  24208. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  24209. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  24210. mesh.material = material;
  24211. mesh.position.copyFrom(this.position);
  24212. mesh.rotation.copyFrom(this.rotation);
  24213. if (this.rotationQuaternion) {
  24214. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  24215. }
  24216. mesh.scaling.copyFrom(this.scaling);
  24217. mesh.computeWorldMatrix(true);
  24218. return mesh;
  24219. };
  24220. return CSG;
  24221. })();
  24222. BABYLON.CSG = CSG;
  24223. })(BABYLON || (BABYLON = {}));
  24224. //# sourceMappingURL=babylon.csg.js.map
  24225. var BABYLON;
  24226. (function (BABYLON) {
  24227. var VRDistortionCorrectionPostProcess = (function (_super) {
  24228. __extends(VRDistortionCorrectionPostProcess, _super);
  24229. //ANY
  24230. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  24231. var _this = this;
  24232. _super.call(this, name, "vrDistortionCorrection", [
  24233. 'LensCenter',
  24234. 'Scale',
  24235. 'ScaleIn',
  24236. 'HmdWarpParam'
  24237. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  24238. this._isRightEye = isRightEye;
  24239. this._distortionFactors = vrMetrics.distortionK;
  24240. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  24241. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  24242. this.onSizeChanged = function () {
  24243. _this.aspectRatio = _this.width * .5 / _this.height;
  24244. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  24245. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  24246. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  24247. };
  24248. this.onApply = function (effect) {
  24249. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  24250. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  24251. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  24252. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  24253. };
  24254. }
  24255. return VRDistortionCorrectionPostProcess;
  24256. })(BABYLON.PostProcess);
  24257. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  24258. })(BABYLON || (BABYLON = {}));
  24259. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  24260. // Mainly based on these 2 articles :
  24261. // 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
  24262. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  24263. var BABYLON;
  24264. (function (BABYLON) {
  24265. (function (JoystickAxis) {
  24266. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  24267. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  24268. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  24269. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  24270. var JoystickAxis = BABYLON.JoystickAxis;
  24271. var VirtualJoystick = (function () {
  24272. function VirtualJoystick(leftJoystick) {
  24273. var _this = this;
  24274. if (leftJoystick) {
  24275. this._leftJoystick = true;
  24276. }
  24277. else {
  24278. this._leftJoystick = false;
  24279. }
  24280. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  24281. VirtualJoystick._globalJoystickIndex++;
  24282. // By default left & right arrow keys are moving the X
  24283. // and up & down keys are moving the Y
  24284. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  24285. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  24286. this.reverseLeftRight = false;
  24287. this.reverseUpDown = false;
  24288. // collections of pointers
  24289. this._touches = new BABYLON.SmartCollection();
  24290. this.deltaPosition = BABYLON.Vector3.Zero();
  24291. this._joystickSensibility = 25;
  24292. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  24293. this._rotationSpeed = 25;
  24294. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  24295. this._rotateOnAxisRelativeToMesh = false;
  24296. // injecting a canvas element on top of the canvas 3D game
  24297. if (!VirtualJoystick.vjCanvas) {
  24298. window.addEventListener("resize", function () {
  24299. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  24300. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  24301. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  24302. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  24303. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  24304. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  24305. }, false);
  24306. VirtualJoystick.vjCanvas = document.createElement("canvas");
  24307. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  24308. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  24309. VirtualJoystick.vjCanvas.width = window.innerWidth;
  24310. VirtualJoystick.vjCanvas.height = window.innerHeight;
  24311. VirtualJoystick.vjCanvas.style.width = "100%";
  24312. VirtualJoystick.vjCanvas.style.height = "100%";
  24313. VirtualJoystick.vjCanvas.style.position = "absolute";
  24314. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  24315. VirtualJoystick.vjCanvas.style.top = "0px";
  24316. VirtualJoystick.vjCanvas.style.left = "0px";
  24317. VirtualJoystick.vjCanvas.style.zIndex = "5";
  24318. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  24319. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  24320. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  24321. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  24322. document.body.appendChild(VirtualJoystick.vjCanvas);
  24323. }
  24324. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  24325. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  24326. this.pressed = false;
  24327. // default joystick color
  24328. this._joystickColor = "cyan";
  24329. this._joystickPointerID = -1;
  24330. // current joystick position
  24331. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  24332. // origin joystick position
  24333. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  24334. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  24335. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  24336. _this._onPointerDown(evt);
  24337. }, false);
  24338. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  24339. _this._onPointerMove(evt);
  24340. }, false);
  24341. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  24342. _this._onPointerUp(evt);
  24343. }, false);
  24344. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  24345. _this._onPointerUp(evt);
  24346. }, false);
  24347. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  24348. evt.preventDefault(); // Disables system menu
  24349. }, false);
  24350. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  24351. }
  24352. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  24353. this._joystickSensibility = newJoystickSensibility;
  24354. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  24355. };
  24356. VirtualJoystick.prototype._onPointerDown = function (e) {
  24357. var positionOnScreenCondition;
  24358. e.preventDefault();
  24359. if (this._leftJoystick === true) {
  24360. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  24361. }
  24362. else {
  24363. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  24364. }
  24365. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  24366. // First contact will be dedicated to the virtual joystick
  24367. this._joystickPointerID = e.pointerId;
  24368. this._joystickPointerStartPos.x = e.clientX;
  24369. this._joystickPointerStartPos.y = e.clientY;
  24370. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  24371. this._deltaJoystickVector.x = 0;
  24372. this._deltaJoystickVector.y = 0;
  24373. this.pressed = true;
  24374. this._touches.add(e.pointerId.toString(), e);
  24375. }
  24376. else {
  24377. // You can only trigger the action buttons with a joystick declared
  24378. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  24379. this._action();
  24380. this._touches.add(e.pointerId.toString(), e);
  24381. }
  24382. }
  24383. };
  24384. VirtualJoystick.prototype._onPointerMove = function (e) {
  24385. // If the current pointer is the one associated to the joystick (first touch contact)
  24386. if (this._joystickPointerID == e.pointerId) {
  24387. this._joystickPointerPos.x = e.clientX;
  24388. this._joystickPointerPos.y = e.clientY;
  24389. this._deltaJoystickVector = this._joystickPointerPos.clone();
  24390. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  24391. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  24392. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  24393. switch (this._axisTargetedByLeftAndRight) {
  24394. case JoystickAxis.X:
  24395. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  24396. break;
  24397. case JoystickAxis.Y:
  24398. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  24399. break;
  24400. case JoystickAxis.Z:
  24401. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  24402. break;
  24403. }
  24404. var directionUpDown = this.reverseUpDown ? 1 : -1;
  24405. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  24406. switch (this._axisTargetedByUpAndDown) {
  24407. case JoystickAxis.X:
  24408. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  24409. break;
  24410. case JoystickAxis.Y:
  24411. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  24412. break;
  24413. case JoystickAxis.Z:
  24414. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  24415. break;
  24416. }
  24417. }
  24418. else {
  24419. if (this._touches.item(e.pointerId.toString())) {
  24420. this._touches.item(e.pointerId.toString()).x = e.clientX;
  24421. this._touches.item(e.pointerId.toString()).y = e.clientY;
  24422. }
  24423. }
  24424. };
  24425. VirtualJoystick.prototype._onPointerUp = function (e) {
  24426. this._clearCanvas();
  24427. if (this._joystickPointerID == e.pointerId) {
  24428. this._joystickPointerID = -1;
  24429. this.pressed = false;
  24430. }
  24431. this._deltaJoystickVector.x = 0;
  24432. this._deltaJoystickVector.y = 0;
  24433. this._touches.remove(e.pointerId.toString());
  24434. };
  24435. /**
  24436. * Change the color of the virtual joystick
  24437. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  24438. */
  24439. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  24440. this._joystickColor = newColor;
  24441. };
  24442. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  24443. this._action = action;
  24444. };
  24445. // Define which axis you'd like to control for left & right
  24446. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  24447. switch (axis) {
  24448. case JoystickAxis.X:
  24449. case JoystickAxis.Y:
  24450. case JoystickAxis.Z:
  24451. this._axisTargetedByLeftAndRight = axis;
  24452. break;
  24453. default:
  24454. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  24455. break;
  24456. }
  24457. };
  24458. // Define which axis you'd like to control for up & down
  24459. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  24460. switch (axis) {
  24461. case JoystickAxis.X:
  24462. case JoystickAxis.Y:
  24463. case JoystickAxis.Z:
  24464. this._axisTargetedByUpAndDown = axis;
  24465. break;
  24466. default:
  24467. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  24468. break;
  24469. }
  24470. };
  24471. VirtualJoystick.prototype._clearCanvas = function () {
  24472. if (this._leftJoystick) {
  24473. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  24474. }
  24475. else {
  24476. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  24477. }
  24478. };
  24479. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  24480. var _this = this;
  24481. if (this.pressed) {
  24482. this._clearCanvas();
  24483. this._touches.forEach(function (touch) {
  24484. if (touch.pointerId === _this._joystickPointerID) {
  24485. VirtualJoystick.vjCanvasContext.beginPath();
  24486. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  24487. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  24488. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  24489. VirtualJoystick.vjCanvasContext.stroke();
  24490. VirtualJoystick.vjCanvasContext.beginPath();
  24491. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  24492. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  24493. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  24494. VirtualJoystick.vjCanvasContext.stroke();
  24495. VirtualJoystick.vjCanvasContext.beginPath();
  24496. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  24497. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  24498. VirtualJoystick.vjCanvasContext.stroke();
  24499. }
  24500. else {
  24501. VirtualJoystick.vjCanvasContext.beginPath();
  24502. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  24503. VirtualJoystick.vjCanvasContext.beginPath();
  24504. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  24505. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  24506. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  24507. VirtualJoystick.vjCanvasContext.stroke();
  24508. }
  24509. ;
  24510. });
  24511. }
  24512. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  24513. };
  24514. VirtualJoystick.prototype.releaseCanvas = function () {
  24515. if (VirtualJoystick.vjCanvas) {
  24516. document.body.removeChild(VirtualJoystick.vjCanvas);
  24517. VirtualJoystick.vjCanvas = null;
  24518. }
  24519. };
  24520. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  24521. VirtualJoystick._globalJoystickIndex = 0;
  24522. return VirtualJoystick;
  24523. })();
  24524. BABYLON.VirtualJoystick = VirtualJoystick;
  24525. })(BABYLON || (BABYLON = {}));
  24526. //# sourceMappingURL=babylon.virtualJoystick.js.map
  24527. var BABYLON;
  24528. (function (BABYLON) {
  24529. // We're mainly based on the logic defined into the FreeCamera code
  24530. var VirtualJoysticksCamera = (function (_super) {
  24531. __extends(VirtualJoysticksCamera, _super);
  24532. function VirtualJoysticksCamera(name, position, scene) {
  24533. _super.call(this, name, position, scene);
  24534. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  24535. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  24536. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  24537. this._leftjoystick.setJoystickSensibility(0.15);
  24538. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  24539. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  24540. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  24541. this._rightjoystick.reverseUpDown = true;
  24542. this._rightjoystick.setJoystickSensibility(0.05);
  24543. this._rightjoystick.setJoystickColor("yellow");
  24544. }
  24545. VirtualJoysticksCamera.prototype._checkInputs = function () {
  24546. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  24547. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  24548. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  24549. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  24550. if (!this._leftjoystick.pressed) {
  24551. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  24552. }
  24553. if (!this._rightjoystick.pressed) {
  24554. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  24555. }
  24556. _super.prototype._checkInputs.call(this);
  24557. };
  24558. VirtualJoysticksCamera.prototype.dispose = function () {
  24559. this._leftjoystick.releaseCanvas();
  24560. _super.prototype.dispose.call(this);
  24561. };
  24562. return VirtualJoysticksCamera;
  24563. })(BABYLON.FreeCamera);
  24564. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  24565. })(BABYLON || (BABYLON = {}));
  24566. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  24567. var BABYLON;
  24568. (function (BABYLON) {
  24569. var ShaderMaterial = (function (_super) {
  24570. __extends(ShaderMaterial, _super);
  24571. function ShaderMaterial(name, scene, shaderPath, options) {
  24572. _super.call(this, name, scene);
  24573. this._textures = new Array();
  24574. this._floats = new Array();
  24575. this._floatsArrays = {};
  24576. this._colors3 = new Array();
  24577. this._colors4 = new Array();
  24578. this._vectors2 = new Array();
  24579. this._vectors3 = new Array();
  24580. this._matrices = new Array();
  24581. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  24582. this._shaderPath = shaderPath;
  24583. options.needAlphaBlending = options.needAlphaBlending || false;
  24584. options.needAlphaTesting = options.needAlphaTesting || false;
  24585. options.attributes = options.attributes || ["position", "normal", "uv"];
  24586. options.uniforms = options.uniforms || ["worldViewProjection"];
  24587. options.samplers = options.samplers || [];
  24588. this._options = options;
  24589. }
  24590. ShaderMaterial.prototype.needAlphaBlending = function () {
  24591. return this._options.needAlphaBlending;
  24592. };
  24593. ShaderMaterial.prototype.needAlphaTesting = function () {
  24594. return this._options.needAlphaTesting;
  24595. };
  24596. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  24597. if (this._options.uniforms.indexOf(uniformName) === -1) {
  24598. this._options.uniforms.push(uniformName);
  24599. }
  24600. };
  24601. ShaderMaterial.prototype.setTexture = function (name, texture) {
  24602. if (this._options.samplers.indexOf(name) === -1) {
  24603. this._options.samplers.push(name);
  24604. }
  24605. this._textures[name] = texture;
  24606. return this;
  24607. };
  24608. ShaderMaterial.prototype.setFloat = function (name, value) {
  24609. this._checkUniform(name);
  24610. this._floats[name] = value;
  24611. return this;
  24612. };
  24613. ShaderMaterial.prototype.setFloats = function (name, value) {
  24614. this._checkUniform(name);
  24615. this._floatsArrays[name] = value;
  24616. return this;
  24617. };
  24618. ShaderMaterial.prototype.setColor3 = function (name, value) {
  24619. this._checkUniform(name);
  24620. this._colors3[name] = value;
  24621. return this;
  24622. };
  24623. ShaderMaterial.prototype.setColor4 = function (name, value) {
  24624. this._checkUniform(name);
  24625. this._colors4[name] = value;
  24626. return this;
  24627. };
  24628. ShaderMaterial.prototype.setVector2 = function (name, value) {
  24629. this._checkUniform(name);
  24630. this._vectors2[name] = value;
  24631. return this;
  24632. };
  24633. ShaderMaterial.prototype.setVector3 = function (name, value) {
  24634. this._checkUniform(name);
  24635. this._vectors3[name] = value;
  24636. return this;
  24637. };
  24638. ShaderMaterial.prototype.setMatrix = function (name, value) {
  24639. this._checkUniform(name);
  24640. this._matrices[name] = value;
  24641. return this;
  24642. };
  24643. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  24644. var scene = this.getScene();
  24645. var engine = scene.getEngine();
  24646. if (!this.checkReadyOnEveryCall) {
  24647. if (this._renderId === scene.getRenderId()) {
  24648. return true;
  24649. }
  24650. }
  24651. // Instances
  24652. var defines = [];
  24653. var fallbacks = new BABYLON.EffectFallbacks();
  24654. if (useInstances) {
  24655. defines.push("#define INSTANCES");
  24656. }
  24657. // Bones
  24658. if (mesh && mesh.useBones) {
  24659. defines.push("#define BONES");
  24660. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  24661. defines.push("#define BONES4");
  24662. fallbacks.addFallback(0, "BONES4");
  24663. }
  24664. // Alpha test
  24665. if (engine.getAlphaTesting()) {
  24666. defines.push("#define ALPHATEST");
  24667. }
  24668. var previousEffect = this._effect;
  24669. var join = defines.join("\n");
  24670. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  24671. if (!this._effect.isReady()) {
  24672. return false;
  24673. }
  24674. if (previousEffect !== this._effect) {
  24675. scene.resetCachedMaterial();
  24676. }
  24677. this._renderId = scene.getRenderId();
  24678. return true;
  24679. };
  24680. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  24681. var scene = this.getScene();
  24682. if (this._options.uniforms.indexOf("world") !== -1) {
  24683. this._effect.setMatrix("world", world);
  24684. }
  24685. if (this._options.uniforms.indexOf("worldView") !== -1) {
  24686. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  24687. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  24688. }
  24689. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  24690. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  24691. }
  24692. };
  24693. ShaderMaterial.prototype.bind = function (world, mesh) {
  24694. // Std values
  24695. this.bindOnlyWorldMatrix(world);
  24696. if (this.getScene().getCachedMaterial() !== this) {
  24697. if (this._options.uniforms.indexOf("view") !== -1) {
  24698. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  24699. }
  24700. if (this._options.uniforms.indexOf("projection") !== -1) {
  24701. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  24702. }
  24703. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  24704. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  24705. }
  24706. // Bones
  24707. if (mesh && mesh.useBones) {
  24708. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  24709. }
  24710. // Texture
  24711. for (var name in this._textures) {
  24712. this._effect.setTexture(name, this._textures[name]);
  24713. }
  24714. // Float
  24715. for (name in this._floats) {
  24716. this._effect.setFloat(name, this._floats[name]);
  24717. }
  24718. // Float s
  24719. for (name in this._floatsArrays) {
  24720. this._effect.setArray(name, this._floatsArrays[name]);
  24721. }
  24722. // Color3
  24723. for (name in this._colors3) {
  24724. this._effect.setColor3(name, this._colors3[name]);
  24725. }
  24726. // Color4
  24727. for (name in this._colors4) {
  24728. var color = this._colors4[name];
  24729. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  24730. }
  24731. // Vector2
  24732. for (name in this._vectors2) {
  24733. this._effect.setVector2(name, this._vectors2[name]);
  24734. }
  24735. // Vector3
  24736. for (name in this._vectors3) {
  24737. this._effect.setVector3(name, this._vectors3[name]);
  24738. }
  24739. // Matrix
  24740. for (name in this._matrices) {
  24741. this._effect.setMatrix(name, this._matrices[name]);
  24742. }
  24743. }
  24744. _super.prototype.bind.call(this, world, mesh);
  24745. };
  24746. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  24747. for (var name in this._textures) {
  24748. this._textures[name].dispose();
  24749. }
  24750. this._textures = [];
  24751. _super.prototype.dispose.call(this, forceDisposeEffect);
  24752. };
  24753. return ShaderMaterial;
  24754. })(BABYLON.Material);
  24755. BABYLON.ShaderMaterial = ShaderMaterial;
  24756. })(BABYLON || (BABYLON = {}));
  24757. //# sourceMappingURL=babylon.shaderMaterial.js.map
  24758. var BABYLON;
  24759. (function (BABYLON) {
  24760. var VertexData = (function () {
  24761. function VertexData() {
  24762. }
  24763. VertexData.prototype.set = function (data, kind) {
  24764. switch (kind) {
  24765. case BABYLON.VertexBuffer.PositionKind:
  24766. this.positions = data;
  24767. break;
  24768. case BABYLON.VertexBuffer.NormalKind:
  24769. this.normals = data;
  24770. break;
  24771. case BABYLON.VertexBuffer.UVKind:
  24772. this.uvs = data;
  24773. break;
  24774. case BABYLON.VertexBuffer.UV2Kind:
  24775. this.uv2s = data;
  24776. break;
  24777. case BABYLON.VertexBuffer.ColorKind:
  24778. this.colors = data;
  24779. break;
  24780. case BABYLON.VertexBuffer.MatricesIndicesKind:
  24781. this.matricesIndices = data;
  24782. break;
  24783. case BABYLON.VertexBuffer.MatricesWeightsKind:
  24784. this.matricesWeights = data;
  24785. break;
  24786. }
  24787. };
  24788. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  24789. this._applyTo(mesh, updatable);
  24790. };
  24791. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  24792. this._applyTo(geometry, updatable);
  24793. };
  24794. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  24795. this._update(mesh);
  24796. };
  24797. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  24798. this._update(geometry);
  24799. };
  24800. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  24801. if (this.positions) {
  24802. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  24803. }
  24804. if (this.normals) {
  24805. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  24806. }
  24807. if (this.uvs) {
  24808. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  24809. }
  24810. if (this.uv2s) {
  24811. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  24812. }
  24813. if (this.colors) {
  24814. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  24815. }
  24816. if (this.matricesIndices) {
  24817. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  24818. }
  24819. if (this.matricesWeights) {
  24820. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  24821. }
  24822. if (this.indices) {
  24823. meshOrGeometry.setIndices(this.indices);
  24824. }
  24825. };
  24826. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  24827. if (this.positions) {
  24828. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  24829. }
  24830. if (this.normals) {
  24831. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  24832. }
  24833. if (this.uvs) {
  24834. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  24835. }
  24836. if (this.uv2s) {
  24837. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  24838. }
  24839. if (this.colors) {
  24840. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  24841. }
  24842. if (this.matricesIndices) {
  24843. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  24844. }
  24845. if (this.matricesWeights) {
  24846. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  24847. }
  24848. if (this.indices) {
  24849. meshOrGeometry.setIndices(this.indices);
  24850. }
  24851. };
  24852. VertexData.prototype.transform = function (matrix) {
  24853. var transformed = BABYLON.Vector3.Zero();
  24854. if (this.positions) {
  24855. var position = BABYLON.Vector3.Zero();
  24856. for (var index = 0; index < this.positions.length; index += 3) {
  24857. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  24858. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  24859. this.positions[index] = transformed.x;
  24860. this.positions[index + 1] = transformed.y;
  24861. this.positions[index + 2] = transformed.z;
  24862. }
  24863. }
  24864. if (this.normals) {
  24865. var normal = BABYLON.Vector3.Zero();
  24866. for (index = 0; index < this.normals.length; index += 3) {
  24867. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  24868. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  24869. this.normals[index] = transformed.x;
  24870. this.normals[index + 1] = transformed.y;
  24871. this.normals[index + 2] = transformed.z;
  24872. }
  24873. }
  24874. };
  24875. VertexData.prototype.merge = function (other) {
  24876. if (other.indices) {
  24877. if (!this.indices) {
  24878. this.indices = [];
  24879. }
  24880. var offset = this.positions ? this.positions.length / 3 : 0;
  24881. for (var index = 0; index < other.indices.length; index++) {
  24882. this.indices.push(other.indices[index] + offset);
  24883. }
  24884. }
  24885. if (other.positions) {
  24886. if (!this.positions) {
  24887. this.positions = [];
  24888. }
  24889. for (index = 0; index < other.positions.length; index++) {
  24890. this.positions.push(other.positions[index]);
  24891. }
  24892. }
  24893. if (other.normals) {
  24894. if (!this.normals) {
  24895. this.normals = [];
  24896. }
  24897. for (index = 0; index < other.normals.length; index++) {
  24898. this.normals.push(other.normals[index]);
  24899. }
  24900. }
  24901. if (other.uvs) {
  24902. if (!this.uvs) {
  24903. this.uvs = [];
  24904. }
  24905. for (index = 0; index < other.uvs.length; index++) {
  24906. this.uvs.push(other.uvs[index]);
  24907. }
  24908. }
  24909. if (other.uv2s) {
  24910. if (!this.uv2s) {
  24911. this.uv2s = [];
  24912. }
  24913. for (index = 0; index < other.uv2s.length; index++) {
  24914. this.uv2s.push(other.uv2s[index]);
  24915. }
  24916. }
  24917. if (other.matricesIndices) {
  24918. if (!this.matricesIndices) {
  24919. this.matricesIndices = [];
  24920. }
  24921. for (index = 0; index < other.matricesIndices.length; index++) {
  24922. this.matricesIndices.push(other.matricesIndices[index]);
  24923. }
  24924. }
  24925. if (other.matricesWeights) {
  24926. if (!this.matricesWeights) {
  24927. this.matricesWeights = [];
  24928. }
  24929. for (index = 0; index < other.matricesWeights.length; index++) {
  24930. this.matricesWeights.push(other.matricesWeights[index]);
  24931. }
  24932. }
  24933. if (other.colors) {
  24934. if (!this.colors) {
  24935. this.colors = [];
  24936. }
  24937. for (index = 0; index < other.colors.length; index++) {
  24938. this.colors.push(other.colors[index]);
  24939. }
  24940. }
  24941. };
  24942. // Statics
  24943. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  24944. return VertexData._ExtractFrom(mesh, copyWhenShared);
  24945. };
  24946. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  24947. return VertexData._ExtractFrom(geometry, copyWhenShared);
  24948. };
  24949. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  24950. var result = new VertexData();
  24951. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  24952. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  24953. }
  24954. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  24955. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  24956. }
  24957. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24958. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  24959. }
  24960. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24961. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  24962. }
  24963. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  24964. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  24965. }
  24966. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  24967. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  24968. }
  24969. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24970. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  24971. }
  24972. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  24973. return result;
  24974. };
  24975. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  24976. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  24977. closeArray = closeArray || false;
  24978. closePath = closePath || false;
  24979. var defaultOffset = Math.floor(pathArray[0].length / 2);
  24980. offset = offset || defaultOffset;
  24981. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  24982. var positions = [];
  24983. var indices = [];
  24984. var normals = [];
  24985. var uvs = [];
  24986. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  24987. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  24988. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  24989. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  24990. var minlg; // minimal length among all paths from pathArray
  24991. var lg = []; // array of path lengths : nb of vertex per path
  24992. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  24993. var p; // path iterator
  24994. var i; // point iterator
  24995. var j; // point iterator
  24996. // if single path in pathArray
  24997. if (pathArray.length < 2) {
  24998. var ar1 = [];
  24999. var ar2 = [];
  25000. for (i = 0; i < pathArray[0].length - offset; i++) {
  25001. ar1.push(pathArray[0][i]);
  25002. ar2.push(pathArray[0][i + offset]);
  25003. }
  25004. pathArray = [ar1, ar2];
  25005. }
  25006. // positions and horizontal distances (u)
  25007. var idc = 0;
  25008. minlg = pathArray[0].length;
  25009. for (p = 0; p < pathArray.length; p++) {
  25010. uTotalDistance[p] = 0;
  25011. us[p] = [0];
  25012. var path = pathArray[p];
  25013. var l = path.length;
  25014. minlg = (minlg < l) ? minlg : l;
  25015. lg[p] = l;
  25016. idx[p] = idc;
  25017. j = 0;
  25018. while (j < l) {
  25019. positions.push(path[j].x, path[j].y, path[j].z);
  25020. if (j > 0) {
  25021. var vectlg = path[j].subtract(path[j - 1]).length();
  25022. var dist = vectlg + uTotalDistance[p];
  25023. us[p].push(dist);
  25024. uTotalDistance[p] = dist;
  25025. }
  25026. j++;
  25027. }
  25028. if (closePath) {
  25029. vectlg = path[0].subtract(path[j - 1]).length();
  25030. dist = vectlg + uTotalDistance[p];
  25031. uTotalDistance[p] = dist;
  25032. }
  25033. idc += l;
  25034. }
  25035. // vertical distances (v)
  25036. for (i = 0; i < minlg; i++) {
  25037. vTotalDistance[i] = 0;
  25038. vs[i] = [0];
  25039. var path1;
  25040. var path2;
  25041. for (p = 0; p < pathArray.length - 1; p++) {
  25042. path1 = pathArray[p];
  25043. path2 = pathArray[p + 1];
  25044. vectlg = path2[i].subtract(path1[i]).length();
  25045. dist = vectlg + vTotalDistance[i];
  25046. vs[i].push(dist);
  25047. vTotalDistance[i] = dist;
  25048. }
  25049. if (closeArray) {
  25050. path1 = pathArray[p];
  25051. path2 = pathArray[0];
  25052. vectlg = path2[i].subtract(path1[i]).length();
  25053. dist = vectlg + vTotalDistance[i];
  25054. vTotalDistance[i] = dist;
  25055. }
  25056. }
  25057. // uvs
  25058. var u;
  25059. var v;
  25060. for (p = 0; p < pathArray.length; p++) {
  25061. for (i = 0; i < minlg; i++) {
  25062. u = us[p][i] / uTotalDistance[p];
  25063. v = vs[i][p] / vTotalDistance[i];
  25064. uvs.push(u, v);
  25065. }
  25066. }
  25067. // indices
  25068. p = 0; // path index
  25069. var pi = 0; // positions array index
  25070. var l1 = lg[p] - 1; // path1 length
  25071. var l2 = lg[p + 1] - 1; // path2 length
  25072. var min = (l1 < l2) ? l1 : l2; // current path stop index
  25073. var shft = idx[1] - idx[0]; // shift
  25074. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  25075. var t1; // two consecutive triangles, so 4 points : point1
  25076. var t2; // point2
  25077. var t3; // point3
  25078. var t4; // point4
  25079. while (pi <= min && p < path1nb) {
  25080. // 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
  25081. t1 = pi;
  25082. t2 = pi + shft;
  25083. t3 = pi + 1;
  25084. t4 = pi + shft + 1;
  25085. indices.push(pi, pi + shft, pi + 1);
  25086. indices.push(pi + shft + 1, pi + 1, pi + shft);
  25087. pi += 1;
  25088. if (pi === min) {
  25089. if (closePath) {
  25090. indices.push(pi, pi + shft, idx[p]);
  25091. indices.push(idx[p] + shft, idx[p], pi + shft);
  25092. t3 = idx[p];
  25093. t4 = idx[p] + shft;
  25094. }
  25095. p++;
  25096. if (p === lg.length - 1) {
  25097. shft = idx[0] - idx[p];
  25098. l1 = lg[p] - 1;
  25099. l2 = lg[0] - 1;
  25100. }
  25101. else {
  25102. shft = idx[p + 1] - idx[p];
  25103. l1 = lg[p] - 1;
  25104. l2 = lg[p + 1] - 1;
  25105. }
  25106. pi = idx[p];
  25107. min = (l1 < l2) ? l1 + pi : l2 + pi;
  25108. }
  25109. }
  25110. // normals
  25111. VertexData.ComputeNormals(positions, indices, normals);
  25112. // sides
  25113. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25114. // Result
  25115. var vertexData = new VertexData();
  25116. vertexData.indices = indices;
  25117. vertexData.positions = positions;
  25118. vertexData.normals = normals;
  25119. vertexData.uvs = uvs;
  25120. return vertexData;
  25121. };
  25122. VertexData.CreateBox = function (size, sideOrientation) {
  25123. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25124. var normalsSource = [
  25125. new BABYLON.Vector3(0, 0, 1),
  25126. new BABYLON.Vector3(0, 0, -1),
  25127. new BABYLON.Vector3(1, 0, 0),
  25128. new BABYLON.Vector3(-1, 0, 0),
  25129. new BABYLON.Vector3(0, 1, 0),
  25130. new BABYLON.Vector3(0, -1, 0)
  25131. ];
  25132. var indices = [];
  25133. var positions = [];
  25134. var normals = [];
  25135. var uvs = [];
  25136. size = size || 1;
  25137. // Create each face in turn.
  25138. for (var index = 0; index < normalsSource.length; index++) {
  25139. var normal = normalsSource[index];
  25140. // Get two vectors perpendicular to the face normal and to each other.
  25141. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  25142. var side2 = BABYLON.Vector3.Cross(normal, side1);
  25143. // Six indices (two triangles) per face.
  25144. var verticesLength = positions.length / 3;
  25145. indices.push(verticesLength);
  25146. indices.push(verticesLength + 1);
  25147. indices.push(verticesLength + 2);
  25148. indices.push(verticesLength);
  25149. indices.push(verticesLength + 2);
  25150. indices.push(verticesLength + 3);
  25151. // Four vertices per face.
  25152. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  25153. positions.push(vertex.x, vertex.y, vertex.z);
  25154. normals.push(normal.x, normal.y, normal.z);
  25155. uvs.push(1.0, 1.0);
  25156. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  25157. positions.push(vertex.x, vertex.y, vertex.z);
  25158. normals.push(normal.x, normal.y, normal.z);
  25159. uvs.push(0.0, 1.0);
  25160. vertex = normal.add(side1).add(side2).scale(size / 2);
  25161. positions.push(vertex.x, vertex.y, vertex.z);
  25162. normals.push(normal.x, normal.y, normal.z);
  25163. uvs.push(0.0, 0.0);
  25164. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  25165. positions.push(vertex.x, vertex.y, vertex.z);
  25166. normals.push(normal.x, normal.y, normal.z);
  25167. uvs.push(1.0, 0.0);
  25168. }
  25169. // sides
  25170. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25171. // Result
  25172. var vertexData = new VertexData();
  25173. vertexData.indices = indices;
  25174. vertexData.positions = positions;
  25175. vertexData.normals = normals;
  25176. vertexData.uvs = uvs;
  25177. return vertexData;
  25178. };
  25179. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  25180. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25181. segments = segments || 32;
  25182. diameter = diameter || 1;
  25183. var radius = diameter / 2;
  25184. var totalZRotationSteps = 2 + segments;
  25185. var totalYRotationSteps = 2 * totalZRotationSteps;
  25186. var indices = [];
  25187. var positions = [];
  25188. var normals = [];
  25189. var uvs = [];
  25190. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  25191. var normalizedZ = zRotationStep / totalZRotationSteps;
  25192. var angleZ = (normalizedZ * Math.PI);
  25193. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  25194. var normalizedY = yRotationStep / totalYRotationSteps;
  25195. var angleY = normalizedY * Math.PI * 2;
  25196. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  25197. var rotationY = BABYLON.Matrix.RotationY(angleY);
  25198. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  25199. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  25200. var vertex = complete.scale(radius);
  25201. var normal = BABYLON.Vector3.Normalize(vertex);
  25202. positions.push(vertex.x, vertex.y, vertex.z);
  25203. normals.push(normal.x, normal.y, normal.z);
  25204. uvs.push(normalizedZ, normalizedY);
  25205. }
  25206. if (zRotationStep > 0) {
  25207. var verticesCount = positions.length / 3;
  25208. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  25209. indices.push((firstIndex));
  25210. indices.push((firstIndex + 1));
  25211. indices.push(firstIndex + totalYRotationSteps + 1);
  25212. indices.push((firstIndex + totalYRotationSteps + 1));
  25213. indices.push((firstIndex + 1));
  25214. indices.push((firstIndex + totalYRotationSteps + 2));
  25215. }
  25216. }
  25217. }
  25218. // Sides
  25219. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25220. // Result
  25221. var vertexData = new VertexData();
  25222. vertexData.indices = indices;
  25223. vertexData.positions = positions;
  25224. vertexData.normals = normals;
  25225. vertexData.uvs = uvs;
  25226. return vertexData;
  25227. };
  25228. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  25229. if (subdivisions === void 0) { subdivisions = 1; }
  25230. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25231. var radiusTop = diameterTop / 2;
  25232. var radiusBottom = diameterBottom / 2;
  25233. var indices = [];
  25234. var positions = [];
  25235. var normals = [];
  25236. var uvs = [];
  25237. height = height || 1;
  25238. diameterTop = diameterTop || 0.5;
  25239. diameterBottom = diameterBottom || 1;
  25240. tessellation = tessellation || 16;
  25241. subdivisions = subdivisions || 1;
  25242. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  25243. var getCircleVector = function (i) {
  25244. var angle = (i * 2.0 * Math.PI / tessellation);
  25245. var dx = Math.cos(angle);
  25246. var dz = Math.sin(angle);
  25247. return new BABYLON.Vector3(dx, 0, dz);
  25248. };
  25249. var createCylinderCap = function (isTop) {
  25250. var radius = isTop ? radiusTop : radiusBottom;
  25251. if (radius === 0) {
  25252. return;
  25253. }
  25254. var vbase = positions.length / 3;
  25255. var offset = new BABYLON.Vector3(0, height / 2, 0);
  25256. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  25257. if (!isTop) {
  25258. offset.scaleInPlace(-1);
  25259. textureScale.x = -textureScale.x;
  25260. }
  25261. // Positions, normals & uvs
  25262. for (var i = 0; i < tessellation; i++) {
  25263. var circleVector = getCircleVector(i);
  25264. var position = circleVector.scale(radius).add(offset);
  25265. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  25266. positions.push(position.x, position.y, position.z);
  25267. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25268. }
  25269. // Indices
  25270. for (i = 0; i < tessellation - 2; i++) {
  25271. if (!isTop) {
  25272. indices.push(vbase);
  25273. indices.push(vbase + (i + 2) % tessellation);
  25274. indices.push(vbase + (i + 1) % tessellation);
  25275. }
  25276. else {
  25277. indices.push(vbase);
  25278. indices.push(vbase + (i + 1) % tessellation);
  25279. indices.push(vbase + (i + 2) % tessellation);
  25280. }
  25281. }
  25282. };
  25283. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  25284. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  25285. var stride = tessellation + 1;
  25286. // Positions, normals & uvs
  25287. for (var i = 0; i <= tessellation; i++) {
  25288. var circleVector = getCircleVector(i);
  25289. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  25290. var position, radius = radiusBottom;
  25291. for (var s = 0; s <= subdivisions; s++) {
  25292. // Update variables
  25293. position = circleVector.scale(radius);
  25294. position.addInPlace(base.add(offset.scale(s)));
  25295. textureCoordinate.y += 1 / subdivisions;
  25296. radius += (radiusTop - radiusBottom) / subdivisions;
  25297. // Push in arrays
  25298. positions.push(position.x, position.y, position.z);
  25299. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25300. }
  25301. }
  25302. subdivisions += 1;
  25303. // Indices
  25304. for (s = 0; s < subdivisions - 1; s++) {
  25305. for (i = 0; i <= tessellation; i++) {
  25306. indices.push(i * subdivisions + s);
  25307. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  25308. indices.push(i * subdivisions + (s + 1));
  25309. indices.push(i * subdivisions + (s + 1));
  25310. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  25311. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  25312. }
  25313. }
  25314. // Create flat triangle fan caps to seal the top and bottom.
  25315. createCylinderCap(true);
  25316. createCylinderCap(false);
  25317. // Normals
  25318. VertexData.ComputeNormals(positions, indices, normals);
  25319. // Sides
  25320. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25321. // Result
  25322. var vertexData = new VertexData();
  25323. vertexData.indices = indices;
  25324. vertexData.positions = positions;
  25325. vertexData.normals = normals;
  25326. vertexData.uvs = uvs;
  25327. return vertexData;
  25328. };
  25329. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  25330. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25331. var indices = [];
  25332. var positions = [];
  25333. var normals = [];
  25334. var uvs = [];
  25335. diameter = diameter || 1;
  25336. thickness = thickness || 0.5;
  25337. tessellation = tessellation || 16;
  25338. var stride = tessellation + 1;
  25339. for (var i = 0; i <= tessellation; i++) {
  25340. var u = i / tessellation;
  25341. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  25342. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  25343. for (var j = 0; j <= tessellation; j++) {
  25344. var v = 1 - j / tessellation;
  25345. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  25346. var dx = Math.cos(innerAngle);
  25347. var dy = Math.sin(innerAngle);
  25348. // Create a vertex.
  25349. var normal = new BABYLON.Vector3(dx, dy, 0);
  25350. var position = normal.scale(thickness / 2);
  25351. var textureCoordinate = new BABYLON.Vector2(u, v);
  25352. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  25353. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  25354. positions.push(position.x, position.y, position.z);
  25355. normals.push(normal.x, normal.y, normal.z);
  25356. uvs.push(textureCoordinate.x, textureCoordinate.y);
  25357. // And create indices for two triangles.
  25358. var nextI = (i + 1) % stride;
  25359. var nextJ = (j + 1) % stride;
  25360. indices.push(i * stride + j);
  25361. indices.push(i * stride + nextJ);
  25362. indices.push(nextI * stride + j);
  25363. indices.push(i * stride + nextJ);
  25364. indices.push(nextI * stride + nextJ);
  25365. indices.push(nextI * stride + j);
  25366. }
  25367. }
  25368. // Sides
  25369. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25370. // Result
  25371. var vertexData = new VertexData();
  25372. vertexData.indices = indices;
  25373. vertexData.positions = positions;
  25374. vertexData.normals = normals;
  25375. vertexData.uvs = uvs;
  25376. return vertexData;
  25377. };
  25378. VertexData.CreateLines = function (points) {
  25379. var indices = [];
  25380. var positions = [];
  25381. for (var index = 0; index < points.length; index++) {
  25382. positions.push(points[index].x, points[index].y, points[index].z);
  25383. if (index > 0) {
  25384. indices.push(index - 1);
  25385. indices.push(index);
  25386. }
  25387. }
  25388. // Result
  25389. var vertexData = new VertexData();
  25390. vertexData.indices = indices;
  25391. vertexData.positions = positions;
  25392. return vertexData;
  25393. };
  25394. VertexData.CreateDashedLines = function (points, dashSize, gapSize, dashNb) {
  25395. dashSize = dashSize || 3;
  25396. gapSize = gapSize || 1;
  25397. dashNb = dashNb || 200;
  25398. var positions = new Array();
  25399. var indices = new Array();
  25400. var curvect = BABYLON.Vector3.Zero();
  25401. var lg = 0;
  25402. var nb = 0;
  25403. var shft = 0;
  25404. var dashshft = 0;
  25405. var curshft = 0;
  25406. var idx = 0;
  25407. var i = 0;
  25408. for (i = 0; i < points.length - 1; i++) {
  25409. points[i + 1].subtractToRef(points[i], curvect);
  25410. lg += curvect.length();
  25411. }
  25412. shft = lg / dashNb;
  25413. dashshft = dashSize * shft / (dashSize + gapSize);
  25414. for (i = 0; i < points.length - 1; i++) {
  25415. points[i + 1].subtractToRef(points[i], curvect);
  25416. nb = Math.floor(curvect.length() / shft);
  25417. curvect.normalize();
  25418. for (var j = 0; j < nb; j++) {
  25419. curshft = shft * j;
  25420. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  25421. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  25422. indices.push(idx, idx + 1);
  25423. idx += 2;
  25424. }
  25425. }
  25426. // Result
  25427. var vertexData = new VertexData();
  25428. vertexData.positions = positions;
  25429. vertexData.indices = indices;
  25430. return vertexData;
  25431. };
  25432. VertexData.CreateGround = function (width, height, subdivisions) {
  25433. var indices = [];
  25434. var positions = [];
  25435. var normals = [];
  25436. var uvs = [];
  25437. var row, col;
  25438. width = width || 1;
  25439. height = height || 1;
  25440. subdivisions = subdivisions || 1;
  25441. for (row = 0; row <= subdivisions; row++) {
  25442. for (col = 0; col <= subdivisions; col++) {
  25443. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  25444. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25445. positions.push(position.x, position.y, position.z);
  25446. normals.push(normal.x, normal.y, normal.z);
  25447. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  25448. }
  25449. }
  25450. for (row = 0; row < subdivisions; row++) {
  25451. for (col = 0; col < subdivisions; col++) {
  25452. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25453. indices.push(col + 1 + row * (subdivisions + 1));
  25454. indices.push(col + row * (subdivisions + 1));
  25455. indices.push(col + (row + 1) * (subdivisions + 1));
  25456. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25457. indices.push(col + row * (subdivisions + 1));
  25458. }
  25459. }
  25460. // Result
  25461. var vertexData = new VertexData();
  25462. vertexData.indices = indices;
  25463. vertexData.positions = positions;
  25464. vertexData.normals = normals;
  25465. vertexData.uvs = uvs;
  25466. return vertexData;
  25467. };
  25468. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  25469. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  25470. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  25471. var indices = [];
  25472. var positions = [];
  25473. var normals = [];
  25474. var uvs = [];
  25475. var row, col, tileRow, tileCol;
  25476. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  25477. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  25478. precision.w = (precision.w < 1) ? 1 : precision.w;
  25479. precision.h = (precision.h < 1) ? 1 : precision.h;
  25480. var tileSize = {
  25481. 'w': (xmax - xmin) / subdivisions.w,
  25482. 'h': (zmax - zmin) / subdivisions.h
  25483. };
  25484. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  25485. // Indices
  25486. var base = positions.length / 3;
  25487. var rowLength = precision.w + 1;
  25488. for (row = 0; row < precision.h; row++) {
  25489. for (col = 0; col < precision.w; col++) {
  25490. var square = [
  25491. base + col + row * rowLength,
  25492. base + (col + 1) + row * rowLength,
  25493. base + (col + 1) + (row + 1) * rowLength,
  25494. base + col + (row + 1) * rowLength
  25495. ];
  25496. indices.push(square[1]);
  25497. indices.push(square[2]);
  25498. indices.push(square[3]);
  25499. indices.push(square[0]);
  25500. indices.push(square[1]);
  25501. indices.push(square[3]);
  25502. }
  25503. }
  25504. // Position, normals and uvs
  25505. var position = BABYLON.Vector3.Zero();
  25506. var normal = new BABYLON.Vector3(0, 1.0, 0);
  25507. for (row = 0; row <= precision.h; row++) {
  25508. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  25509. for (col = 0; col <= precision.w; col++) {
  25510. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  25511. position.y = 0;
  25512. positions.push(position.x, position.y, position.z);
  25513. normals.push(normal.x, normal.y, normal.z);
  25514. uvs.push(col / precision.w, row / precision.h);
  25515. }
  25516. }
  25517. }
  25518. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  25519. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  25520. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  25521. }
  25522. }
  25523. // Result
  25524. var vertexData = new VertexData();
  25525. vertexData.indices = indices;
  25526. vertexData.positions = positions;
  25527. vertexData.normals = normals;
  25528. vertexData.uvs = uvs;
  25529. return vertexData;
  25530. };
  25531. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  25532. var indices = [];
  25533. var positions = [];
  25534. var normals = [];
  25535. var uvs = [];
  25536. var row, col;
  25537. // Vertices
  25538. for (row = 0; row <= subdivisions; row++) {
  25539. for (col = 0; col <= subdivisions; col++) {
  25540. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  25541. // Compute height
  25542. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  25543. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  25544. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  25545. var r = buffer[pos] / 255.0;
  25546. var g = buffer[pos + 1] / 255.0;
  25547. var b = buffer[pos + 2] / 255.0;
  25548. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  25549. position.y = minHeight + (maxHeight - minHeight) * gradient;
  25550. // Add vertex
  25551. positions.push(position.x, position.y, position.z);
  25552. normals.push(0, 0, 0);
  25553. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  25554. }
  25555. }
  25556. // Indices
  25557. for (row = 0; row < subdivisions; row++) {
  25558. for (col = 0; col < subdivisions; col++) {
  25559. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25560. indices.push(col + 1 + row * (subdivisions + 1));
  25561. indices.push(col + row * (subdivisions + 1));
  25562. indices.push(col + (row + 1) * (subdivisions + 1));
  25563. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  25564. indices.push(col + row * (subdivisions + 1));
  25565. }
  25566. }
  25567. // Normals
  25568. VertexData.ComputeNormals(positions, indices, normals);
  25569. // Result
  25570. var vertexData = new VertexData();
  25571. vertexData.indices = indices;
  25572. vertexData.positions = positions;
  25573. vertexData.normals = normals;
  25574. vertexData.uvs = uvs;
  25575. return vertexData;
  25576. };
  25577. VertexData.CreatePlane = function (size, sideOrientation) {
  25578. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25579. var indices = [];
  25580. var positions = [];
  25581. var normals = [];
  25582. var uvs = [];
  25583. size = size || 1;
  25584. // Vertices
  25585. var halfSize = size / 2.0;
  25586. positions.push(-halfSize, -halfSize, 0);
  25587. normals.push(0, 0, -1.0);
  25588. uvs.push(0.0, 0.0);
  25589. positions.push(halfSize, -halfSize, 0);
  25590. normals.push(0, 0, -1.0);
  25591. uvs.push(1.0, 0.0);
  25592. positions.push(halfSize, halfSize, 0);
  25593. normals.push(0, 0, -1.0);
  25594. uvs.push(1.0, 1.0);
  25595. positions.push(-halfSize, halfSize, 0);
  25596. normals.push(0, 0, -1.0);
  25597. uvs.push(0.0, 1.0);
  25598. // Indices
  25599. indices.push(0);
  25600. indices.push(1);
  25601. indices.push(2);
  25602. indices.push(0);
  25603. indices.push(2);
  25604. indices.push(3);
  25605. // Sides
  25606. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25607. // Result
  25608. var vertexData = new VertexData();
  25609. vertexData.indices = indices;
  25610. vertexData.positions = positions;
  25611. vertexData.normals = normals;
  25612. vertexData.uvs = uvs;
  25613. return vertexData;
  25614. };
  25615. VertexData.CreateDisc = function (radius, tessellation, sideOrientation) {
  25616. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25617. var positions = [];
  25618. var indices = [];
  25619. var normals = [];
  25620. var uvs = [];
  25621. // positions and uvs
  25622. positions.push(0, 0, 0); // disc center first
  25623. uvs.push(0.5, 0.5);
  25624. var step = Math.PI * 2 / tessellation;
  25625. for (var a = 0; a < Math.PI * 2; a += step) {
  25626. var x = Math.cos(a);
  25627. var y = Math.sin(a);
  25628. var u = (x + 1) / 2;
  25629. var v = (1 - y) / 2;
  25630. positions.push(radius * x, radius * y, 0);
  25631. uvs.push(u, v);
  25632. }
  25633. positions.push(positions[3], positions[4], positions[5]); // close the circle
  25634. uvs.push(uvs[2], uvs[3]);
  25635. //indices
  25636. var vertexNb = positions.length / 3;
  25637. for (var i = 1; i < vertexNb - 1; i++) {
  25638. indices.push(i + 1, 0, i);
  25639. }
  25640. // result
  25641. VertexData.ComputeNormals(positions, indices, normals);
  25642. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25643. var vertexData = new VertexData();
  25644. vertexData.indices = indices;
  25645. vertexData.positions = positions;
  25646. vertexData.normals = normals;
  25647. vertexData.uvs = uvs;
  25648. return vertexData;
  25649. };
  25650. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  25651. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  25652. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  25653. var indices = [];
  25654. var positions = [];
  25655. var normals = [];
  25656. var uvs = [];
  25657. radius = radius || 2;
  25658. tube = tube || 0.5;
  25659. radialSegments = radialSegments || 32;
  25660. tubularSegments = tubularSegments || 32;
  25661. p = p || 2;
  25662. q = q || 3;
  25663. // Helper
  25664. var getPos = function (angle) {
  25665. var cu = Math.cos(angle);
  25666. var su = Math.sin(angle);
  25667. var quOverP = q / p * angle;
  25668. var cs = Math.cos(quOverP);
  25669. var tx = radius * (2 + cs) * 0.5 * cu;
  25670. var ty = radius * (2 + cs) * su * 0.5;
  25671. var tz = radius * Math.sin(quOverP) * 0.5;
  25672. return new BABYLON.Vector3(tx, ty, tz);
  25673. };
  25674. // Vertices
  25675. for (var i = 0; i <= radialSegments; i++) {
  25676. var modI = i % radialSegments;
  25677. var u = modI / radialSegments * 2 * p * Math.PI;
  25678. var p1 = getPos(u);
  25679. var p2 = getPos(u + 0.01);
  25680. var tang = p2.subtract(p1);
  25681. var n = p2.add(p1);
  25682. var bitan = BABYLON.Vector3.Cross(tang, n);
  25683. n = BABYLON.Vector3.Cross(bitan, tang);
  25684. bitan.normalize();
  25685. n.normalize();
  25686. for (var j = 0; j < tubularSegments; j++) {
  25687. var modJ = j % tubularSegments;
  25688. var v = modJ / tubularSegments * 2 * Math.PI;
  25689. var cx = -tube * Math.cos(v);
  25690. var cy = tube * Math.sin(v);
  25691. positions.push(p1.x + cx * n.x + cy * bitan.x);
  25692. positions.push(p1.y + cx * n.y + cy * bitan.y);
  25693. positions.push(p1.z + cx * n.z + cy * bitan.z);
  25694. uvs.push(i / radialSegments);
  25695. uvs.push(j / tubularSegments);
  25696. }
  25697. }
  25698. for (i = 0; i < radialSegments; i++) {
  25699. for (j = 0; j < tubularSegments; j++) {
  25700. var jNext = (j + 1) % tubularSegments;
  25701. var a = i * tubularSegments + j;
  25702. var b = (i + 1) * tubularSegments + j;
  25703. var c = (i + 1) * tubularSegments + jNext;
  25704. var d = i * tubularSegments + jNext;
  25705. indices.push(d);
  25706. indices.push(b);
  25707. indices.push(a);
  25708. indices.push(d);
  25709. indices.push(c);
  25710. indices.push(b);
  25711. }
  25712. }
  25713. // Normals
  25714. VertexData.ComputeNormals(positions, indices, normals);
  25715. // Sides
  25716. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  25717. // Result
  25718. var vertexData = new VertexData();
  25719. vertexData.indices = indices;
  25720. vertexData.positions = positions;
  25721. vertexData.normals = normals;
  25722. vertexData.uvs = uvs;
  25723. return vertexData;
  25724. };
  25725. // Tools
  25726. /**
  25727. * @param {any} - positions (number[] or Float32Array)
  25728. * @param {any} - indices (number[] or Uint16Array)
  25729. * @param {any} - normals (number[] or Float32Array)
  25730. */
  25731. VertexData.ComputeNormals = function (positions, indices, normals) {
  25732. var index = 0;
  25733. // temp Vector3
  25734. var p1 = BABYLON.Vector3.Zero();
  25735. var p2 = BABYLON.Vector3.Zero();
  25736. var p3 = BABYLON.Vector3.Zero();
  25737. var p1p2 = BABYLON.Vector3.Zero();
  25738. var p3p2 = BABYLON.Vector3.Zero();
  25739. var faceNormal = BABYLON.Vector3.Zero();
  25740. var vertexNormali1 = BABYLON.Vector3.Zero();
  25741. var vertexNormali2 = BABYLON.Vector3.Zero();
  25742. var vertexNormali3 = BABYLON.Vector3.Zero();
  25743. // indice triplet = 1 face
  25744. var nbFaces = indices.length / 3;
  25745. for (index = 0; index < nbFaces; index++) {
  25746. var i1 = indices[index * 3];
  25747. var i2 = indices[index * 3 + 1];
  25748. var i3 = indices[index * 3 + 2];
  25749. // setting the temp V3
  25750. BABYLON.Vector3.FromFloatsToRef(positions[i1 * 3], positions[i1 * 3 + 1], positions[i1 * 3 + 2], p1);
  25751. BABYLON.Vector3.FromFloatsToRef(positions[i2 * 3], positions[i2 * 3 + 1], positions[i2 * 3 + 2], p2);
  25752. BABYLON.Vector3.FromFloatsToRef(positions[i3 * 3], positions[i3 * 3 + 1], positions[i3 * 3 + 2], p3);
  25753. p1.subtractToRef(p2, p1p2);
  25754. p3.subtractToRef(p2, p3p2);
  25755. BABYLON.Vector3.CrossToRef(p1p2, p3p2, faceNormal);
  25756. faceNormal.normalize();
  25757. // All intermediate results are stored in the normals array :
  25758. // get the normals at i1, i2 and i3 indexes
  25759. normals[i1 * 3] = normals[i1 * 3] || 0.0;
  25760. normals[i1 * 3 + 1] = normals[i1 * 3 + 1] || 0.0;
  25761. normals[i1 * 3 + 2] = normals[i1 * 3 + 2] || 0.0;
  25762. normals[i2 * 3] = normals[i2 * 3] || 0.0;
  25763. normals[i2 * 3 + 1] = normals[i2 * 3 + 1] || 0.0;
  25764. normals[i2 * 3 + 2] = normals[i2 * 3 + 2] || 0.0;
  25765. normals[i3 * 3] = normals[i3 * 3] || 0.0;
  25766. normals[i3 * 3 + 1] = normals[i3 * 3 + 1] || 0.0;
  25767. normals[i3 * 3 + 2] = normals[i3 * 3 + 2] || 0.0;
  25768. // make intermediate vectors3 from normals values
  25769. BABYLON.Vector3.FromFloatsToRef(normals[i1 * 3], normals[i1 * 3 + 1], normals[i1 * 3 + 2], vertexNormali1);
  25770. BABYLON.Vector3.FromFloatsToRef(normals[i2 * 3], normals[i2 * 3 + 1], normals[i2 * 3 + 2], vertexNormali2);
  25771. BABYLON.Vector3.FromFloatsToRef(normals[i3 * 3], normals[i3 * 3 + 1], normals[i3 * 3 + 2], vertexNormali3);
  25772. // add the current face normals to these intermediate vectors3
  25773. vertexNormali1 = vertexNormali1.addInPlace(faceNormal);
  25774. vertexNormali2 = vertexNormali2.addInPlace(faceNormal);
  25775. vertexNormali3 = vertexNormali3.addInPlace(faceNormal);
  25776. // store back intermediate vectors3 into the normals array
  25777. normals[i1 * 3] = vertexNormali1.x;
  25778. normals[i1 * 3 + 1] = vertexNormali1.y;
  25779. normals[i1 * 3 + 2] = vertexNormali1.z;
  25780. normals[i2 * 3] = vertexNormali2.x;
  25781. normals[i2 * 3 + 1] = vertexNormali2.y;
  25782. normals[i2 * 3 + 2] = vertexNormali2.z;
  25783. normals[i3 * 3] = vertexNormali3.x;
  25784. normals[i3 * 3 + 1] = vertexNormali3.y;
  25785. normals[i3 * 3 + 2] = vertexNormali3.z;
  25786. }
  25787. // last normalization
  25788. for (index = 0; index < normals.length / 3; index++) {
  25789. BABYLON.Vector3.FromFloatsToRef(normals[index * 3], normals[index * 3 + 1], normals[index * 3 + 2], vertexNormali1);
  25790. vertexNormali1.normalize();
  25791. normals[index * 3] = vertexNormali1.x;
  25792. normals[index * 3 + 1] = vertexNormali1.y;
  25793. normals[index * 3 + 2] = vertexNormali1.z;
  25794. }
  25795. };
  25796. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  25797. var li = indices.length;
  25798. var ln = normals.length;
  25799. var i;
  25800. var n;
  25801. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  25802. switch (sideOrientation) {
  25803. case BABYLON.Mesh.FRONTSIDE:
  25804. // nothing changed
  25805. break;
  25806. case BABYLON.Mesh.BACKSIDE:
  25807. var tmp;
  25808. // indices
  25809. for (i = 0; i < li; i += 3) {
  25810. tmp = indices[i];
  25811. indices[i] = indices[i + 2];
  25812. indices[i + 2] = tmp;
  25813. }
  25814. // normals
  25815. for (n = 0; n < ln; n++) {
  25816. normals[n] = -normals[n];
  25817. }
  25818. break;
  25819. case BABYLON.Mesh.DOUBLESIDE:
  25820. // positions
  25821. var lp = positions.length;
  25822. var l = lp / 3;
  25823. for (var p = 0; p < lp; p++) {
  25824. positions[lp + p] = positions[p];
  25825. }
  25826. // indices
  25827. for (i = 0; i < li; i += 3) {
  25828. indices[i + li] = indices[i + 2] + l;
  25829. indices[i + 1 + li] = indices[i + 1] + l;
  25830. indices[i + 2 + li] = indices[i] + l;
  25831. }
  25832. // normals
  25833. for (n = 0; n < ln; n++) {
  25834. normals[ln + n] = -normals[n];
  25835. }
  25836. // uvs
  25837. var lu = uvs.length;
  25838. for (var u = 0; u < lu; u++) {
  25839. uvs[u + lu] = uvs[u];
  25840. }
  25841. break;
  25842. }
  25843. };
  25844. return VertexData;
  25845. })();
  25846. BABYLON.VertexData = VertexData;
  25847. })(BABYLON || (BABYLON = {}));
  25848. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  25849. var BABYLON;
  25850. (function (BABYLON) {
  25851. var AnaglyphPostProcess = (function (_super) {
  25852. __extends(AnaglyphPostProcess, _super);
  25853. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  25854. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  25855. }
  25856. return AnaglyphPostProcess;
  25857. })(BABYLON.PostProcess);
  25858. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  25859. })(BABYLON || (BABYLON = {}));
  25860. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  25861. var BABYLON;
  25862. (function (BABYLON) {
  25863. var Tags = (function () {
  25864. function Tags() {
  25865. }
  25866. Tags.EnableFor = function (obj) {
  25867. obj._tags = obj._tags || {};
  25868. obj.hasTags = function () {
  25869. return Tags.HasTags(obj);
  25870. };
  25871. obj.addTags = function (tagsString) {
  25872. return Tags.AddTagsTo(obj, tagsString);
  25873. };
  25874. obj.removeTags = function (tagsString) {
  25875. return Tags.RemoveTagsFrom(obj, tagsString);
  25876. };
  25877. obj.matchesTagsQuery = function (tagsQuery) {
  25878. return Tags.MatchesQuery(obj, tagsQuery);
  25879. };
  25880. };
  25881. Tags.DisableFor = function (obj) {
  25882. delete obj._tags;
  25883. delete obj.hasTags;
  25884. delete obj.addTags;
  25885. delete obj.removeTags;
  25886. delete obj.matchesTagsQuery;
  25887. };
  25888. Tags.HasTags = function (obj) {
  25889. if (!obj._tags) {
  25890. return false;
  25891. }
  25892. return !BABYLON.Tools.IsEmpty(obj._tags);
  25893. };
  25894. Tags.GetTags = function (obj) {
  25895. if (!obj._tags) {
  25896. return null;
  25897. }
  25898. return obj._tags;
  25899. };
  25900. // the tags 'true' and 'false' are reserved and cannot be used as tags
  25901. // a tag cannot start with '||', '&&', and '!'
  25902. // it cannot contain whitespaces
  25903. Tags.AddTagsTo = function (obj, tagsString) {
  25904. if (!tagsString) {
  25905. return;
  25906. }
  25907. var tags = tagsString.split(" ");
  25908. for (var t in tags) {
  25909. Tags._AddTagTo(obj, tags[t]);
  25910. }
  25911. };
  25912. Tags._AddTagTo = function (obj, tag) {
  25913. tag = tag.trim();
  25914. if (tag === "" || tag === "true" || tag === "false") {
  25915. return;
  25916. }
  25917. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  25918. return;
  25919. }
  25920. Tags.EnableFor(obj);
  25921. obj._tags[tag] = true;
  25922. };
  25923. Tags.RemoveTagsFrom = function (obj, tagsString) {
  25924. if (!Tags.HasTags(obj)) {
  25925. return;
  25926. }
  25927. var tags = tagsString.split(" ");
  25928. for (var t in tags) {
  25929. Tags._RemoveTagFrom(obj, tags[t]);
  25930. }
  25931. };
  25932. Tags._RemoveTagFrom = function (obj, tag) {
  25933. delete obj._tags[tag];
  25934. };
  25935. Tags.MatchesQuery = function (obj, tagsQuery) {
  25936. if (tagsQuery === undefined) {
  25937. return true;
  25938. }
  25939. if (tagsQuery === "") {
  25940. return Tags.HasTags(obj);
  25941. }
  25942. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  25943. };
  25944. return Tags;
  25945. })();
  25946. BABYLON.Tags = Tags;
  25947. })(BABYLON || (BABYLON = {}));
  25948. //# sourceMappingURL=babylon.tags.js.map
  25949. var BABYLON;
  25950. (function (BABYLON) {
  25951. var Internals;
  25952. (function (Internals) {
  25953. var AndOrNotEvaluator = (function () {
  25954. function AndOrNotEvaluator() {
  25955. }
  25956. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  25957. if (!query.match(/\([^\(\)]*\)/g)) {
  25958. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  25959. }
  25960. else {
  25961. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  25962. // remove parenthesis
  25963. r = r.slice(1, r.length - 1);
  25964. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  25965. });
  25966. }
  25967. if (query === "true") {
  25968. return true;
  25969. }
  25970. if (query === "false") {
  25971. return false;
  25972. }
  25973. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  25974. };
  25975. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  25976. evaluateCallback = evaluateCallback || (function (r) {
  25977. return r === "true" ? true : false;
  25978. });
  25979. var result;
  25980. var or = parenthesisContent.split("||");
  25981. for (var i in or) {
  25982. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  25983. var and = ori.split("&&");
  25984. if (and.length > 1) {
  25985. for (var j = 0; j < and.length; ++j) {
  25986. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  25987. if (andj !== "true" && andj !== "false") {
  25988. if (andj[0] === "!") {
  25989. result = !evaluateCallback(andj.substring(1));
  25990. }
  25991. else {
  25992. result = evaluateCallback(andj);
  25993. }
  25994. }
  25995. else {
  25996. result = andj === "true" ? true : false;
  25997. }
  25998. if (!result) {
  25999. ori = "false";
  26000. break;
  26001. }
  26002. }
  26003. }
  26004. if (result || ori === "true") {
  26005. result = true;
  26006. break;
  26007. }
  26008. // result equals false (or undefined)
  26009. if (ori !== "true" && ori !== "false") {
  26010. if (ori[0] === "!") {
  26011. result = !evaluateCallback(ori.substring(1));
  26012. }
  26013. else {
  26014. result = evaluateCallback(ori);
  26015. }
  26016. }
  26017. else {
  26018. result = ori === "true" ? true : false;
  26019. }
  26020. }
  26021. // the whole parenthesis scope is replaced by 'true' or 'false'
  26022. return result ? "true" : "false";
  26023. };
  26024. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  26025. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  26026. // remove whitespaces
  26027. r = r.replace(/[\s]/g, function () { return ""; });
  26028. return r.length % 2 ? "!" : "";
  26029. });
  26030. booleanString = booleanString.trim();
  26031. if (booleanString === "!true") {
  26032. booleanString = "false";
  26033. }
  26034. else if (booleanString === "!false") {
  26035. booleanString = "true";
  26036. }
  26037. return booleanString;
  26038. };
  26039. return AndOrNotEvaluator;
  26040. })();
  26041. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  26042. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26043. })(BABYLON || (BABYLON = {}));
  26044. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  26045. var BABYLON;
  26046. (function (BABYLON) {
  26047. var PostProcessRenderPass = (function () {
  26048. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  26049. this._enabled = true;
  26050. this._refCount = 0;
  26051. this._name = name;
  26052. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  26053. this.setRenderList(renderList);
  26054. this._renderTexture.onBeforeRender = beforeRender;
  26055. this._renderTexture.onAfterRender = afterRender;
  26056. this._scene = scene;
  26057. this._renderList = renderList;
  26058. }
  26059. // private
  26060. PostProcessRenderPass.prototype._incRefCount = function () {
  26061. if (this._refCount === 0) {
  26062. this._scene.customRenderTargets.push(this._renderTexture);
  26063. }
  26064. return ++this._refCount;
  26065. };
  26066. PostProcessRenderPass.prototype._decRefCount = function () {
  26067. this._refCount--;
  26068. if (this._refCount <= 0) {
  26069. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  26070. }
  26071. return this._refCount;
  26072. };
  26073. PostProcessRenderPass.prototype._update = function () {
  26074. this.setRenderList(this._renderList);
  26075. };
  26076. // public
  26077. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  26078. this._renderTexture.renderList = renderList;
  26079. };
  26080. PostProcessRenderPass.prototype.getRenderTexture = function () {
  26081. return this._renderTexture;
  26082. };
  26083. return PostProcessRenderPass;
  26084. })();
  26085. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  26086. })(BABYLON || (BABYLON = {}));
  26087. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  26088. var BABYLON;
  26089. (function (BABYLON) {
  26090. var PostProcessRenderEffect = (function () {
  26091. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  26092. this._engine = engine;
  26093. this._name = name;
  26094. this._singleInstance = singleInstance || true;
  26095. this._getPostProcess = getPostProcess;
  26096. this._cameras = [];
  26097. this._indicesForCamera = [];
  26098. this._postProcesses = {};
  26099. this._renderPasses = {};
  26100. this._renderEffectAsPasses = {};
  26101. }
  26102. PostProcessRenderEffect.prototype._update = function () {
  26103. for (var renderPassName in this._renderPasses) {
  26104. this._renderPasses[renderPassName]._update();
  26105. }
  26106. };
  26107. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  26108. this._renderPasses[renderPass._name] = renderPass;
  26109. this._linkParameters();
  26110. };
  26111. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  26112. delete this._renderPasses[renderPass._name];
  26113. this._linkParameters();
  26114. };
  26115. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  26116. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  26117. this._linkParameters();
  26118. };
  26119. PostProcessRenderEffect.prototype.getPass = function (passName) {
  26120. for (var renderPassName in this._renderPasses) {
  26121. if (renderPassName === passName) {
  26122. return this._renderPasses[passName];
  26123. }
  26124. }
  26125. };
  26126. PostProcessRenderEffect.prototype.emptyPasses = function () {
  26127. this._renderPasses = {};
  26128. this._linkParameters();
  26129. };
  26130. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  26131. var cameraKey;
  26132. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26133. for (var i = 0; i < _cam.length; i++) {
  26134. var camera = _cam[i];
  26135. var cameraName = camera.name;
  26136. if (this._singleInstance) {
  26137. cameraKey = 0;
  26138. }
  26139. else {
  26140. cameraKey = cameraName;
  26141. }
  26142. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  26143. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  26144. if (!this._indicesForCamera[cameraName]) {
  26145. this._indicesForCamera[cameraName] = [];
  26146. }
  26147. this._indicesForCamera[cameraName].push(index);
  26148. if (this._cameras.indexOf(camera) === -1) {
  26149. this._cameras[cameraName] = camera;
  26150. }
  26151. for (var passName in this._renderPasses) {
  26152. this._renderPasses[passName]._incRefCount();
  26153. }
  26154. }
  26155. this._linkParameters();
  26156. };
  26157. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  26158. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26159. for (var i = 0; i < _cam.length; i++) {
  26160. var camera = _cam[i];
  26161. var cameraName = camera.name;
  26162. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26163. var index = this._cameras.indexOf(cameraName);
  26164. this._indicesForCamera.splice(index, 1);
  26165. this._cameras.splice(index, 1);
  26166. for (var passName in this._renderPasses) {
  26167. this._renderPasses[passName]._decRefCount();
  26168. }
  26169. }
  26170. };
  26171. PostProcessRenderEffect.prototype._enable = function (cameras) {
  26172. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26173. for (var i = 0; i < _cam.length; i++) {
  26174. var camera = _cam[i];
  26175. var cameraName = camera.name;
  26176. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  26177. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  26178. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  26179. }
  26180. }
  26181. for (var passName in this._renderPasses) {
  26182. this._renderPasses[passName]._incRefCount();
  26183. }
  26184. }
  26185. };
  26186. PostProcessRenderEffect.prototype._disable = function (cameras) {
  26187. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26188. for (var i = 0; i < _cam.length; i++) {
  26189. var camera = _cam[i];
  26190. var cameraName = camera.Name;
  26191. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  26192. for (var passName in this._renderPasses) {
  26193. this._renderPasses[passName]._decRefCount();
  26194. }
  26195. }
  26196. };
  26197. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  26198. if (this._singleInstance) {
  26199. return this._postProcesses[0];
  26200. }
  26201. else {
  26202. return this._postProcesses[camera.name];
  26203. }
  26204. };
  26205. PostProcessRenderEffect.prototype._linkParameters = function () {
  26206. var _this = this;
  26207. for (var index in this._postProcesses) {
  26208. if (this.applyParameters) {
  26209. this.applyParameters(this._postProcesses[index]);
  26210. }
  26211. this._postProcesses[index].onBeforeRender = function (effect) {
  26212. _this._linkTextures(effect);
  26213. };
  26214. }
  26215. };
  26216. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  26217. for (var renderPassName in this._renderPasses) {
  26218. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  26219. }
  26220. for (var renderEffectName in this._renderEffectAsPasses) {
  26221. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  26222. }
  26223. };
  26224. return PostProcessRenderEffect;
  26225. })();
  26226. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  26227. })(BABYLON || (BABYLON = {}));
  26228. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  26229. var BABYLON;
  26230. (function (BABYLON) {
  26231. var PostProcessRenderPipeline = (function () {
  26232. function PostProcessRenderPipeline(engine, name) {
  26233. this._engine = engine;
  26234. this._name = name;
  26235. this._renderEffects = {};
  26236. this._renderEffectsForIsolatedPass = {};
  26237. this._cameras = [];
  26238. }
  26239. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  26240. this._renderEffects[renderEffect._name] = renderEffect;
  26241. };
  26242. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  26243. var renderEffects = this._renderEffects[renderEffectName];
  26244. if (!renderEffects) {
  26245. return;
  26246. }
  26247. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26248. };
  26249. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  26250. var renderEffects = this._renderEffects[renderEffectName];
  26251. if (!renderEffects) {
  26252. return;
  26253. }
  26254. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  26255. };
  26256. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  26257. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26258. var indicesToDelete = [];
  26259. for (var i = 0; i < _cam.length; i++) {
  26260. var camera = _cam[i];
  26261. var cameraName = camera.name;
  26262. if (this._cameras.indexOf(camera) === -1) {
  26263. this._cameras[cameraName] = camera;
  26264. }
  26265. else if (unique) {
  26266. indicesToDelete.push(i);
  26267. }
  26268. }
  26269. for (var i = 0; i < indicesToDelete.length; i++) {
  26270. cameras.splice(indicesToDelete[i], 1);
  26271. }
  26272. for (var renderEffectName in this._renderEffects) {
  26273. this._renderEffects[renderEffectName]._attachCameras(_cam);
  26274. }
  26275. };
  26276. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  26277. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26278. for (var renderEffectName in this._renderEffects) {
  26279. this._renderEffects[renderEffectName]._detachCameras(_cam);
  26280. }
  26281. for (var i = 0; i < _cam.length; i++) {
  26282. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  26283. }
  26284. };
  26285. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  26286. var _this = this;
  26287. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26288. var pass = null;
  26289. for (var renderEffectName in this._renderEffects) {
  26290. pass = this._renderEffects[renderEffectName].getPass(passName);
  26291. if (pass != null) {
  26292. break;
  26293. }
  26294. }
  26295. if (pass === null) {
  26296. return;
  26297. }
  26298. for (var renderEffectName in this._renderEffects) {
  26299. this._renderEffects[renderEffectName]._disable(_cam);
  26300. }
  26301. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  26302. for (var i = 0; i < _cam.length; i++) {
  26303. var camera = _cam[i];
  26304. var cameraName = camera.name;
  26305. 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); });
  26306. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  26307. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  26308. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  26309. }
  26310. };
  26311. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  26312. var _this = this;
  26313. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  26314. for (var i = 0; i < _cam.length; i++) {
  26315. var camera = _cam[i];
  26316. var cameraName = camera.name;
  26317. 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); });
  26318. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  26319. }
  26320. for (var renderEffectName in this._renderEffects) {
  26321. this._renderEffects[renderEffectName]._enable(_cam);
  26322. }
  26323. };
  26324. PostProcessRenderPipeline.prototype._update = function () {
  26325. for (var renderEffectName in this._renderEffects) {
  26326. this._renderEffects[renderEffectName]._update();
  26327. }
  26328. for (var i = 0; i < this._cameras.length; i++) {
  26329. var cameraName = this._cameras[i].name;
  26330. if (this._renderEffectsForIsolatedPass[cameraName]) {
  26331. this._renderEffectsForIsolatedPass[cameraName]._update();
  26332. }
  26333. }
  26334. };
  26335. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  26336. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  26337. return PostProcessRenderPipeline;
  26338. })();
  26339. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  26340. })(BABYLON || (BABYLON = {}));
  26341. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  26342. var BABYLON;
  26343. (function (BABYLON) {
  26344. var PostProcessRenderPipelineManager = (function () {
  26345. function PostProcessRenderPipelineManager() {
  26346. this._renderPipelines = {};
  26347. }
  26348. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  26349. this._renderPipelines[renderPipeline._name] = renderPipeline;
  26350. };
  26351. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  26352. var renderPipeline = this._renderPipelines[renderPipelineName];
  26353. if (!renderPipeline) {
  26354. return;
  26355. }
  26356. renderPipeline._attachCameras(cameras, unique);
  26357. };
  26358. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  26359. var renderPipeline = this._renderPipelines[renderPipelineName];
  26360. if (!renderPipeline) {
  26361. return;
  26362. }
  26363. renderPipeline._detachCameras(cameras);
  26364. };
  26365. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26366. var renderPipeline = this._renderPipelines[renderPipelineName];
  26367. if (!renderPipeline) {
  26368. return;
  26369. }
  26370. renderPipeline._enableEffect(renderEffectName, cameras);
  26371. };
  26372. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  26373. var renderPipeline = this._renderPipelines[renderPipelineName];
  26374. if (!renderPipeline) {
  26375. return;
  26376. }
  26377. renderPipeline._disableEffect(renderEffectName, cameras);
  26378. };
  26379. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  26380. var renderPipeline = this._renderPipelines[renderPipelineName];
  26381. if (!renderPipeline) {
  26382. return;
  26383. }
  26384. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  26385. };
  26386. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  26387. var renderPipeline = this._renderPipelines[renderPipelineName];
  26388. if (!renderPipeline) {
  26389. return;
  26390. }
  26391. renderPipeline._disableDisplayOnlyPass(cameras);
  26392. };
  26393. PostProcessRenderPipelineManager.prototype.update = function () {
  26394. for (var renderPipelineName in this._renderPipelines) {
  26395. this._renderPipelines[renderPipelineName]._update();
  26396. }
  26397. };
  26398. return PostProcessRenderPipelineManager;
  26399. })();
  26400. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  26401. })(BABYLON || (BABYLON = {}));
  26402. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  26403. var BABYLON;
  26404. (function (BABYLON) {
  26405. var DisplayPassPostProcess = (function (_super) {
  26406. __extends(DisplayPassPostProcess, _super);
  26407. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  26408. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  26409. }
  26410. return DisplayPassPostProcess;
  26411. })(BABYLON.PostProcess);
  26412. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  26413. })(BABYLON || (BABYLON = {}));
  26414. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  26415. var BABYLON;
  26416. (function (BABYLON) {
  26417. var BoundingBoxRenderer = (function () {
  26418. function BoundingBoxRenderer(scene) {
  26419. this.frontColor = new BABYLON.Color3(1, 1, 1);
  26420. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  26421. this.showBackLines = true;
  26422. this.renderList = new BABYLON.SmartArray(32);
  26423. this._scene = scene;
  26424. }
  26425. BoundingBoxRenderer.prototype._prepareRessources = function () {
  26426. if (this._colorShader) {
  26427. return;
  26428. }
  26429. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  26430. attributes: ["position"],
  26431. uniforms: ["worldViewProjection", "color"]
  26432. });
  26433. var engine = this._scene.getEngine();
  26434. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  26435. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  26436. 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]);
  26437. };
  26438. BoundingBoxRenderer.prototype.reset = function () {
  26439. this.renderList.reset();
  26440. };
  26441. BoundingBoxRenderer.prototype.render = function () {
  26442. if (this.renderList.length === 0) {
  26443. return;
  26444. }
  26445. this._prepareRessources();
  26446. if (!this._colorShader.isReady()) {
  26447. return;
  26448. }
  26449. var engine = this._scene.getEngine();
  26450. engine.setDepthWrite(false);
  26451. this._colorShader._preBind();
  26452. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  26453. var boundingBox = this.renderList.data[boundingBoxIndex];
  26454. var min = boundingBox.minimum;
  26455. var max = boundingBox.maximum;
  26456. var diff = max.subtract(min);
  26457. var median = min.add(diff.scale(0.5));
  26458. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  26459. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  26460. .multiply(boundingBox.getWorldMatrix());
  26461. // VBOs
  26462. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  26463. if (this.showBackLines) {
  26464. // Back
  26465. engine.setDepthFunctionToGreaterOrEqual();
  26466. this._scene.resetCachedMaterial();
  26467. this._colorShader.setColor4("color", this.backColor.toColor4());
  26468. this._colorShader.bind(worldMatrix);
  26469. // Draw order
  26470. engine.draw(false, 0, 24);
  26471. }
  26472. // Front
  26473. engine.setDepthFunctionToLess();
  26474. this._scene.resetCachedMaterial();
  26475. this._colorShader.setColor4("color", this.frontColor.toColor4());
  26476. this._colorShader.bind(worldMatrix);
  26477. // Draw order
  26478. engine.draw(false, 0, 24);
  26479. }
  26480. this._colorShader.unbind();
  26481. engine.setDepthFunctionToLessOrEqual();
  26482. engine.setDepthWrite(true);
  26483. };
  26484. BoundingBoxRenderer.prototype.dispose = function () {
  26485. if (!this._colorShader) {
  26486. return;
  26487. }
  26488. this._colorShader.dispose();
  26489. this._vb.dispose();
  26490. this._scene.getEngine()._releaseBuffer(this._ib);
  26491. };
  26492. return BoundingBoxRenderer;
  26493. })();
  26494. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  26495. })(BABYLON || (BABYLON = {}));
  26496. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  26497. var BABYLON;
  26498. (function (BABYLON) {
  26499. var Condition = (function () {
  26500. function Condition(actionManager) {
  26501. this._actionManager = actionManager;
  26502. }
  26503. Condition.prototype.isValid = function () {
  26504. return true;
  26505. };
  26506. Condition.prototype._getProperty = function (propertyPath) {
  26507. return this._actionManager._getProperty(propertyPath);
  26508. };
  26509. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  26510. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26511. };
  26512. return Condition;
  26513. })();
  26514. BABYLON.Condition = Condition;
  26515. var ValueCondition = (function (_super) {
  26516. __extends(ValueCondition, _super);
  26517. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  26518. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  26519. _super.call(this, actionManager);
  26520. this.propertyPath = propertyPath;
  26521. this.value = value;
  26522. this.operator = operator;
  26523. this._target = this._getEffectiveTarget(target, this.propertyPath);
  26524. this._property = this._getProperty(this.propertyPath);
  26525. }
  26526. Object.defineProperty(ValueCondition, "IsEqual", {
  26527. get: function () {
  26528. return ValueCondition._IsEqual;
  26529. },
  26530. enumerable: true,
  26531. configurable: true
  26532. });
  26533. Object.defineProperty(ValueCondition, "IsDifferent", {
  26534. get: function () {
  26535. return ValueCondition._IsDifferent;
  26536. },
  26537. enumerable: true,
  26538. configurable: true
  26539. });
  26540. Object.defineProperty(ValueCondition, "IsGreater", {
  26541. get: function () {
  26542. return ValueCondition._IsGreater;
  26543. },
  26544. enumerable: true,
  26545. configurable: true
  26546. });
  26547. Object.defineProperty(ValueCondition, "IsLesser", {
  26548. get: function () {
  26549. return ValueCondition._IsLesser;
  26550. },
  26551. enumerable: true,
  26552. configurable: true
  26553. });
  26554. // Methods
  26555. ValueCondition.prototype.isValid = function () {
  26556. switch (this.operator) {
  26557. case ValueCondition.IsGreater:
  26558. return this._target[this._property] > this.value;
  26559. case ValueCondition.IsLesser:
  26560. return this._target[this._property] < this.value;
  26561. case ValueCondition.IsEqual:
  26562. case ValueCondition.IsDifferent:
  26563. var check;
  26564. if (this.value.equals) {
  26565. check = this.value.equals(this._target[this._property]);
  26566. }
  26567. else {
  26568. check = this.value === this._target[this._property];
  26569. }
  26570. return this.operator === ValueCondition.IsEqual ? check : !check;
  26571. }
  26572. return false;
  26573. };
  26574. // Statics
  26575. ValueCondition._IsEqual = 0;
  26576. ValueCondition._IsDifferent = 1;
  26577. ValueCondition._IsGreater = 2;
  26578. ValueCondition._IsLesser = 3;
  26579. return ValueCondition;
  26580. })(Condition);
  26581. BABYLON.ValueCondition = ValueCondition;
  26582. var PredicateCondition = (function (_super) {
  26583. __extends(PredicateCondition, _super);
  26584. function PredicateCondition(actionManager, predicate) {
  26585. _super.call(this, actionManager);
  26586. this.predicate = predicate;
  26587. }
  26588. PredicateCondition.prototype.isValid = function () {
  26589. return this.predicate();
  26590. };
  26591. return PredicateCondition;
  26592. })(Condition);
  26593. BABYLON.PredicateCondition = PredicateCondition;
  26594. var StateCondition = (function (_super) {
  26595. __extends(StateCondition, _super);
  26596. function StateCondition(actionManager, target, value) {
  26597. _super.call(this, actionManager);
  26598. this.value = value;
  26599. this._target = target;
  26600. }
  26601. // Methods
  26602. StateCondition.prototype.isValid = function () {
  26603. return this._target.state === this.value;
  26604. };
  26605. return StateCondition;
  26606. })(Condition);
  26607. BABYLON.StateCondition = StateCondition;
  26608. })(BABYLON || (BABYLON = {}));
  26609. //# sourceMappingURL=babylon.condition.js.map
  26610. var BABYLON;
  26611. (function (BABYLON) {
  26612. var Action = (function () {
  26613. function Action(triggerOptions, condition) {
  26614. this.triggerOptions = triggerOptions;
  26615. if (triggerOptions.parameter) {
  26616. this.trigger = triggerOptions.trigger;
  26617. this._triggerParameter = triggerOptions.parameter;
  26618. }
  26619. else {
  26620. this.trigger = triggerOptions;
  26621. }
  26622. this._nextActiveAction = this;
  26623. this._condition = condition;
  26624. }
  26625. // Methods
  26626. Action.prototype._prepare = function () {
  26627. };
  26628. Action.prototype.getTriggerParameter = function () {
  26629. return this._triggerParameter;
  26630. };
  26631. Action.prototype._executeCurrent = function (evt) {
  26632. if (this._nextActiveAction._condition) {
  26633. var condition = this._nextActiveAction._condition;
  26634. var currentRenderId = this._actionManager.getScene().getRenderId();
  26635. // We cache the current evaluation for the current frame
  26636. if (condition._evaluationId === currentRenderId) {
  26637. if (!condition._currentResult) {
  26638. return;
  26639. }
  26640. }
  26641. else {
  26642. condition._evaluationId = currentRenderId;
  26643. if (!condition.isValid()) {
  26644. condition._currentResult = false;
  26645. return;
  26646. }
  26647. condition._currentResult = true;
  26648. }
  26649. }
  26650. this._nextActiveAction.execute(evt);
  26651. if (this._nextActiveAction._child) {
  26652. if (!this._nextActiveAction._child._actionManager) {
  26653. this._nextActiveAction._child._actionManager = this._actionManager;
  26654. }
  26655. this._nextActiveAction = this._nextActiveAction._child;
  26656. }
  26657. else {
  26658. this._nextActiveAction = this;
  26659. }
  26660. };
  26661. Action.prototype.execute = function (evt) {
  26662. };
  26663. Action.prototype.then = function (action) {
  26664. this._child = action;
  26665. action._actionManager = this._actionManager;
  26666. action._prepare();
  26667. return action;
  26668. };
  26669. Action.prototype._getProperty = function (propertyPath) {
  26670. return this._actionManager._getProperty(propertyPath);
  26671. };
  26672. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  26673. return this._actionManager._getEffectiveTarget(target, propertyPath);
  26674. };
  26675. return Action;
  26676. })();
  26677. BABYLON.Action = Action;
  26678. })(BABYLON || (BABYLON = {}));
  26679. //# sourceMappingURL=babylon.action.js.map
  26680. var BABYLON;
  26681. (function (BABYLON) {
  26682. /**
  26683. * ActionEvent is the event beint sent when an action is triggered.
  26684. */
  26685. var ActionEvent = (function () {
  26686. /**
  26687. * @constructor
  26688. * @param source The mesh that triggered the action.
  26689. * @param pointerX the X mouse cursor position at the time of the event
  26690. * @param pointerY the Y mouse cursor position at the time of the event
  26691. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  26692. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  26693. */
  26694. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  26695. this.source = source;
  26696. this.pointerX = pointerX;
  26697. this.pointerY = pointerY;
  26698. this.meshUnderPointer = meshUnderPointer;
  26699. this.sourceEvent = sourceEvent;
  26700. }
  26701. /**
  26702. * Helper function to auto-create an ActionEvent from a source mesh.
  26703. * @param source the source mesh that triggered the event
  26704. * @param evt {Event} The original (browser) event
  26705. */
  26706. ActionEvent.CreateNew = function (source, evt) {
  26707. var scene = source.getScene();
  26708. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  26709. };
  26710. /**
  26711. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  26712. * @param scene the scene where the event occurred
  26713. * @param evt {Event} The original (browser) event
  26714. */
  26715. ActionEvent.CreateNewFromScene = function (scene, evt) {
  26716. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  26717. };
  26718. return ActionEvent;
  26719. })();
  26720. BABYLON.ActionEvent = ActionEvent;
  26721. /**
  26722. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  26723. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  26724. */
  26725. var ActionManager = (function () {
  26726. function ActionManager(scene) {
  26727. // Members
  26728. this.actions = new Array();
  26729. this._scene = scene;
  26730. scene._actionManagers.push(this);
  26731. }
  26732. Object.defineProperty(ActionManager, "NothingTrigger", {
  26733. get: function () {
  26734. return ActionManager._NothingTrigger;
  26735. },
  26736. enumerable: true,
  26737. configurable: true
  26738. });
  26739. Object.defineProperty(ActionManager, "OnPickTrigger", {
  26740. get: function () {
  26741. return ActionManager._OnPickTrigger;
  26742. },
  26743. enumerable: true,
  26744. configurable: true
  26745. });
  26746. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  26747. get: function () {
  26748. return ActionManager._OnLeftPickTrigger;
  26749. },
  26750. enumerable: true,
  26751. configurable: true
  26752. });
  26753. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  26754. get: function () {
  26755. return ActionManager._OnRightPickTrigger;
  26756. },
  26757. enumerable: true,
  26758. configurable: true
  26759. });
  26760. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  26761. get: function () {
  26762. return ActionManager._OnCenterPickTrigger;
  26763. },
  26764. enumerable: true,
  26765. configurable: true
  26766. });
  26767. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  26768. get: function () {
  26769. return ActionManager._OnPointerOverTrigger;
  26770. },
  26771. enumerable: true,
  26772. configurable: true
  26773. });
  26774. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  26775. get: function () {
  26776. return ActionManager._OnPointerOutTrigger;
  26777. },
  26778. enumerable: true,
  26779. configurable: true
  26780. });
  26781. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  26782. get: function () {
  26783. return ActionManager._OnEveryFrameTrigger;
  26784. },
  26785. enumerable: true,
  26786. configurable: true
  26787. });
  26788. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  26789. get: function () {
  26790. return ActionManager._OnIntersectionEnterTrigger;
  26791. },
  26792. enumerable: true,
  26793. configurable: true
  26794. });
  26795. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  26796. get: function () {
  26797. return ActionManager._OnIntersectionExitTrigger;
  26798. },
  26799. enumerable: true,
  26800. configurable: true
  26801. });
  26802. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  26803. get: function () {
  26804. return ActionManager._OnKeyDownTrigger;
  26805. },
  26806. enumerable: true,
  26807. configurable: true
  26808. });
  26809. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  26810. get: function () {
  26811. return ActionManager._OnKeyUpTrigger;
  26812. },
  26813. enumerable: true,
  26814. configurable: true
  26815. });
  26816. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  26817. get: function () {
  26818. return ActionManager._OnPickUpTrigger;
  26819. },
  26820. enumerable: true,
  26821. configurable: true
  26822. });
  26823. // Methods
  26824. ActionManager.prototype.dispose = function () {
  26825. var index = this._scene._actionManagers.indexOf(this);
  26826. if (index > -1) {
  26827. this._scene._actionManagers.splice(index, 1);
  26828. }
  26829. };
  26830. ActionManager.prototype.getScene = function () {
  26831. return this._scene;
  26832. };
  26833. /**
  26834. * Does this action manager handles actions of any of the given triggers
  26835. * @param {number[]} triggers - the triggers to be tested
  26836. * @return {boolean} whether one (or more) of the triggers is handeled
  26837. */
  26838. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  26839. for (var index = 0; index < this.actions.length; index++) {
  26840. var action = this.actions[index];
  26841. if (triggers.indexOf(action.trigger) > -1) {
  26842. return true;
  26843. }
  26844. }
  26845. return false;
  26846. };
  26847. /**
  26848. * Does this action manager handles actions of a given trigger
  26849. * @param {number} trigger - the trigger to be tested
  26850. * @return {boolean} whether the trigger is handeled
  26851. */
  26852. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  26853. for (var index = 0; index < this.actions.length; index++) {
  26854. var action = this.actions[index];
  26855. if (action.trigger === trigger) {
  26856. return true;
  26857. }
  26858. }
  26859. return false;
  26860. };
  26861. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  26862. /**
  26863. * Does this action manager has pointer triggers
  26864. * @return {boolean} whether or not it has pointer triggers
  26865. */
  26866. get: function () {
  26867. for (var index = 0; index < this.actions.length; index++) {
  26868. var action = this.actions[index];
  26869. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  26870. return true;
  26871. }
  26872. if (action.trigger == ActionManager._OnPickUpTrigger) {
  26873. return true;
  26874. }
  26875. }
  26876. return false;
  26877. },
  26878. enumerable: true,
  26879. configurable: true
  26880. });
  26881. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  26882. /**
  26883. * Does this action manager has pick triggers
  26884. * @return {boolean} whether or not it has pick triggers
  26885. */
  26886. get: function () {
  26887. for (var index = 0; index < this.actions.length; index++) {
  26888. var action = this.actions[index];
  26889. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  26890. return true;
  26891. }
  26892. }
  26893. return false;
  26894. },
  26895. enumerable: true,
  26896. configurable: true
  26897. });
  26898. /**
  26899. * Registers an action to this action manager
  26900. * @param {BABYLON.Action} action - the action to be registered
  26901. * @return {BABYLON.Action} the action amended (prepared) after registration
  26902. */
  26903. ActionManager.prototype.registerAction = function (action) {
  26904. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  26905. if (this.getScene().actionManager !== this) {
  26906. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  26907. return null;
  26908. }
  26909. }
  26910. this.actions.push(action);
  26911. action._actionManager = this;
  26912. action._prepare();
  26913. return action;
  26914. };
  26915. /**
  26916. * Process a specific trigger
  26917. * @param {number} trigger - the trigger to process
  26918. * @param evt {BABYLON.ActionEvent} the event details to be processed
  26919. */
  26920. ActionManager.prototype.processTrigger = function (trigger, evt) {
  26921. for (var index = 0; index < this.actions.length; index++) {
  26922. var action = this.actions[index];
  26923. if (action.trigger === trigger) {
  26924. if (trigger === ActionManager.OnKeyUpTrigger
  26925. || trigger === ActionManager.OnKeyDownTrigger) {
  26926. var parameter = action.getTriggerParameter();
  26927. if (parameter) {
  26928. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  26929. var actualkey = String.fromCharCode(unicode).toLowerCase();
  26930. if (actualkey !== parameter.toLowerCase()) {
  26931. continue;
  26932. }
  26933. }
  26934. }
  26935. action._executeCurrent(evt);
  26936. }
  26937. }
  26938. };
  26939. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  26940. var properties = propertyPath.split(".");
  26941. for (var index = 0; index < properties.length - 1; index++) {
  26942. target = target[properties[index]];
  26943. }
  26944. return target;
  26945. };
  26946. ActionManager.prototype._getProperty = function (propertyPath) {
  26947. var properties = propertyPath.split(".");
  26948. return properties[properties.length - 1];
  26949. };
  26950. // Statics
  26951. ActionManager._NothingTrigger = 0;
  26952. ActionManager._OnPickTrigger = 1;
  26953. ActionManager._OnLeftPickTrigger = 2;
  26954. ActionManager._OnRightPickTrigger = 3;
  26955. ActionManager._OnCenterPickTrigger = 4;
  26956. ActionManager._OnPointerOverTrigger = 5;
  26957. ActionManager._OnPointerOutTrigger = 6;
  26958. ActionManager._OnEveryFrameTrigger = 7;
  26959. ActionManager._OnIntersectionEnterTrigger = 8;
  26960. ActionManager._OnIntersectionExitTrigger = 9;
  26961. ActionManager._OnKeyDownTrigger = 10;
  26962. ActionManager._OnKeyUpTrigger = 11;
  26963. ActionManager._OnPickUpTrigger = 12;
  26964. return ActionManager;
  26965. })();
  26966. BABYLON.ActionManager = ActionManager;
  26967. })(BABYLON || (BABYLON = {}));
  26968. //# sourceMappingURL=babylon.actionManager.js.map
  26969. var BABYLON;
  26970. (function (BABYLON) {
  26971. var InterpolateValueAction = (function (_super) {
  26972. __extends(InterpolateValueAction, _super);
  26973. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  26974. if (duration === void 0) { duration = 1000; }
  26975. _super.call(this, triggerOptions, condition);
  26976. this.propertyPath = propertyPath;
  26977. this.value = value;
  26978. this.duration = duration;
  26979. this.stopOtherAnimations = stopOtherAnimations;
  26980. this._target = target;
  26981. }
  26982. InterpolateValueAction.prototype._prepare = function () {
  26983. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  26984. this._property = this._getProperty(this.propertyPath);
  26985. };
  26986. InterpolateValueAction.prototype.execute = function () {
  26987. var scene = this._actionManager.getScene();
  26988. var keys = [
  26989. {
  26990. frame: 0,
  26991. value: this._target[this._property]
  26992. }, {
  26993. frame: 100,
  26994. value: this.value
  26995. }
  26996. ];
  26997. var dataType;
  26998. if (typeof this.value === "number") {
  26999. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  27000. }
  27001. else if (this.value instanceof BABYLON.Color3) {
  27002. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  27003. }
  27004. else if (this.value instanceof BABYLON.Vector3) {
  27005. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  27006. }
  27007. else if (this.value instanceof BABYLON.Matrix) {
  27008. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  27009. }
  27010. else if (this.value instanceof BABYLON.Quaternion) {
  27011. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  27012. }
  27013. else {
  27014. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  27015. return;
  27016. }
  27017. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  27018. animation.setKeys(keys);
  27019. if (this.stopOtherAnimations) {
  27020. scene.stopAnimation(this._target);
  27021. }
  27022. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  27023. };
  27024. return InterpolateValueAction;
  27025. })(BABYLON.Action);
  27026. BABYLON.InterpolateValueAction = InterpolateValueAction;
  27027. })(BABYLON || (BABYLON = {}));
  27028. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  27029. var BABYLON;
  27030. (function (BABYLON) {
  27031. var SwitchBooleanAction = (function (_super) {
  27032. __extends(SwitchBooleanAction, _super);
  27033. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  27034. _super.call(this, triggerOptions, condition);
  27035. this.propertyPath = propertyPath;
  27036. this._target = target;
  27037. }
  27038. SwitchBooleanAction.prototype._prepare = function () {
  27039. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27040. this._property = this._getProperty(this.propertyPath);
  27041. };
  27042. SwitchBooleanAction.prototype.execute = function () {
  27043. this._target[this._property] = !this._target[this._property];
  27044. };
  27045. return SwitchBooleanAction;
  27046. })(BABYLON.Action);
  27047. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  27048. var SetStateAction = (function (_super) {
  27049. __extends(SetStateAction, _super);
  27050. function SetStateAction(triggerOptions, target, value, condition) {
  27051. _super.call(this, triggerOptions, condition);
  27052. this.value = value;
  27053. this._target = target;
  27054. }
  27055. SetStateAction.prototype.execute = function () {
  27056. this._target.state = this.value;
  27057. };
  27058. return SetStateAction;
  27059. })(BABYLON.Action);
  27060. BABYLON.SetStateAction = SetStateAction;
  27061. var SetValueAction = (function (_super) {
  27062. __extends(SetValueAction, _super);
  27063. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  27064. _super.call(this, triggerOptions, condition);
  27065. this.propertyPath = propertyPath;
  27066. this.value = value;
  27067. this._target = target;
  27068. }
  27069. SetValueAction.prototype._prepare = function () {
  27070. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27071. this._property = this._getProperty(this.propertyPath);
  27072. };
  27073. SetValueAction.prototype.execute = function () {
  27074. this._target[this._property] = this.value;
  27075. };
  27076. return SetValueAction;
  27077. })(BABYLON.Action);
  27078. BABYLON.SetValueAction = SetValueAction;
  27079. var IncrementValueAction = (function (_super) {
  27080. __extends(IncrementValueAction, _super);
  27081. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  27082. _super.call(this, triggerOptions, condition);
  27083. this.propertyPath = propertyPath;
  27084. this.value = value;
  27085. this._target = target;
  27086. }
  27087. IncrementValueAction.prototype._prepare = function () {
  27088. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  27089. this._property = this._getProperty(this.propertyPath);
  27090. if (typeof this._target[this._property] !== "number") {
  27091. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  27092. }
  27093. };
  27094. IncrementValueAction.prototype.execute = function () {
  27095. this._target[this._property] += this.value;
  27096. };
  27097. return IncrementValueAction;
  27098. })(BABYLON.Action);
  27099. BABYLON.IncrementValueAction = IncrementValueAction;
  27100. var PlayAnimationAction = (function (_super) {
  27101. __extends(PlayAnimationAction, _super);
  27102. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  27103. _super.call(this, triggerOptions, condition);
  27104. this.from = from;
  27105. this.to = to;
  27106. this.loop = loop;
  27107. this._target = target;
  27108. }
  27109. PlayAnimationAction.prototype._prepare = function () {
  27110. };
  27111. PlayAnimationAction.prototype.execute = function () {
  27112. var scene = this._actionManager.getScene();
  27113. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  27114. };
  27115. return PlayAnimationAction;
  27116. })(BABYLON.Action);
  27117. BABYLON.PlayAnimationAction = PlayAnimationAction;
  27118. var StopAnimationAction = (function (_super) {
  27119. __extends(StopAnimationAction, _super);
  27120. function StopAnimationAction(triggerOptions, target, condition) {
  27121. _super.call(this, triggerOptions, condition);
  27122. this._target = target;
  27123. }
  27124. StopAnimationAction.prototype._prepare = function () {
  27125. };
  27126. StopAnimationAction.prototype.execute = function () {
  27127. var scene = this._actionManager.getScene();
  27128. scene.stopAnimation(this._target);
  27129. };
  27130. return StopAnimationAction;
  27131. })(BABYLON.Action);
  27132. BABYLON.StopAnimationAction = StopAnimationAction;
  27133. var DoNothingAction = (function (_super) {
  27134. __extends(DoNothingAction, _super);
  27135. function DoNothingAction(triggerOptions, condition) {
  27136. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  27137. _super.call(this, triggerOptions, condition);
  27138. }
  27139. DoNothingAction.prototype.execute = function () {
  27140. };
  27141. return DoNothingAction;
  27142. })(BABYLON.Action);
  27143. BABYLON.DoNothingAction = DoNothingAction;
  27144. var CombineAction = (function (_super) {
  27145. __extends(CombineAction, _super);
  27146. function CombineAction(triggerOptions, children, condition) {
  27147. _super.call(this, triggerOptions, condition);
  27148. this.children = children;
  27149. }
  27150. CombineAction.prototype._prepare = function () {
  27151. for (var index = 0; index < this.children.length; index++) {
  27152. this.children[index]._actionManager = this._actionManager;
  27153. this.children[index]._prepare();
  27154. }
  27155. };
  27156. CombineAction.prototype.execute = function (evt) {
  27157. for (var index = 0; index < this.children.length; index++) {
  27158. this.children[index].execute(evt);
  27159. }
  27160. };
  27161. return CombineAction;
  27162. })(BABYLON.Action);
  27163. BABYLON.CombineAction = CombineAction;
  27164. var ExecuteCodeAction = (function (_super) {
  27165. __extends(ExecuteCodeAction, _super);
  27166. function ExecuteCodeAction(triggerOptions, func, condition) {
  27167. _super.call(this, triggerOptions, condition);
  27168. this.func = func;
  27169. }
  27170. ExecuteCodeAction.prototype.execute = function (evt) {
  27171. this.func(evt);
  27172. };
  27173. return ExecuteCodeAction;
  27174. })(BABYLON.Action);
  27175. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  27176. var SetParentAction = (function (_super) {
  27177. __extends(SetParentAction, _super);
  27178. function SetParentAction(triggerOptions, target, parent, condition) {
  27179. _super.call(this, triggerOptions, condition);
  27180. this._target = target;
  27181. this._parent = parent;
  27182. }
  27183. SetParentAction.prototype._prepare = function () {
  27184. };
  27185. SetParentAction.prototype.execute = function () {
  27186. if (this._target.parent === this._parent) {
  27187. return;
  27188. }
  27189. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  27190. invertParentWorldMatrix.invert();
  27191. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  27192. this._target.parent = this._parent;
  27193. };
  27194. return SetParentAction;
  27195. })(BABYLON.Action);
  27196. BABYLON.SetParentAction = SetParentAction;
  27197. var PlaySoundAction = (function (_super) {
  27198. __extends(PlaySoundAction, _super);
  27199. function PlaySoundAction(triggerOptions, sound, condition) {
  27200. _super.call(this, triggerOptions, condition);
  27201. this._sound = sound;
  27202. }
  27203. PlaySoundAction.prototype._prepare = function () {
  27204. };
  27205. PlaySoundAction.prototype.execute = function () {
  27206. if (this._sound !== undefined)
  27207. this._sound.play();
  27208. };
  27209. return PlaySoundAction;
  27210. })(BABYLON.Action);
  27211. BABYLON.PlaySoundAction = PlaySoundAction;
  27212. var StopSoundAction = (function (_super) {
  27213. __extends(StopSoundAction, _super);
  27214. function StopSoundAction(triggerOptions, sound, condition) {
  27215. _super.call(this, triggerOptions, condition);
  27216. this._sound = sound;
  27217. }
  27218. StopSoundAction.prototype._prepare = function () {
  27219. };
  27220. StopSoundAction.prototype.execute = function () {
  27221. if (this._sound !== undefined)
  27222. this._sound.stop();
  27223. };
  27224. return StopSoundAction;
  27225. })(BABYLON.Action);
  27226. BABYLON.StopSoundAction = StopSoundAction;
  27227. })(BABYLON || (BABYLON = {}));
  27228. //# sourceMappingURL=babylon.directActions.js.map
  27229. var BABYLON;
  27230. (function (BABYLON) {
  27231. var Geometry = (function () {
  27232. function Geometry(id, scene, vertexData, updatable, mesh) {
  27233. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27234. this._totalVertices = 0;
  27235. this._indices = [];
  27236. this._isDisposed = false;
  27237. this.id = id;
  27238. this._engine = scene.getEngine();
  27239. this._meshes = [];
  27240. this._scene = scene;
  27241. // vertexData
  27242. if (vertexData) {
  27243. this.setAllVerticesData(vertexData, updatable);
  27244. }
  27245. else {
  27246. this._totalVertices = 0;
  27247. this._indices = [];
  27248. }
  27249. // applyToMesh
  27250. if (mesh) {
  27251. this.applyToMesh(mesh);
  27252. mesh.computeWorldMatrix(true);
  27253. }
  27254. }
  27255. Geometry.prototype.getScene = function () {
  27256. return this._scene;
  27257. };
  27258. Geometry.prototype.getEngine = function () {
  27259. return this._engine;
  27260. };
  27261. Geometry.prototype.isReady = function () {
  27262. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  27263. };
  27264. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  27265. vertexData.applyToGeometry(this, updatable);
  27266. this.notifyUpdate();
  27267. };
  27268. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  27269. this._vertexBuffers = this._vertexBuffers || {};
  27270. if (this._vertexBuffers[kind]) {
  27271. this._vertexBuffers[kind].dispose();
  27272. }
  27273. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  27274. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27275. stride = this._vertexBuffers[kind].getStrideSize();
  27276. this._totalVertices = data.length / stride;
  27277. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27278. var meshes = this._meshes;
  27279. var numOfMeshes = meshes.length;
  27280. for (var index = 0; index < numOfMeshes; index++) {
  27281. var mesh = meshes[index];
  27282. mesh._resetPointsArrayCache();
  27283. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27284. mesh._createGlobalSubMesh();
  27285. mesh.computeWorldMatrix(true);
  27286. }
  27287. }
  27288. this.notifyUpdate(kind);
  27289. };
  27290. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  27291. var vertexBuffer = this.getVertexBuffer(kind);
  27292. if (!vertexBuffer) {
  27293. return;
  27294. }
  27295. vertexBuffer.updateDirectly(data, offset);
  27296. this.notifyUpdate(kind);
  27297. };
  27298. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  27299. var vertexBuffer = this.getVertexBuffer(kind);
  27300. if (!vertexBuffer) {
  27301. return;
  27302. }
  27303. vertexBuffer.update(data);
  27304. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27305. var extend;
  27306. var stride = vertexBuffer.getStrideSize();
  27307. this._totalVertices = data.length / stride;
  27308. if (updateExtends) {
  27309. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  27310. }
  27311. var meshes = this._meshes;
  27312. var numOfMeshes = meshes.length;
  27313. for (var index = 0; index < numOfMeshes; index++) {
  27314. var mesh = meshes[index];
  27315. mesh._resetPointsArrayCache();
  27316. if (updateExtends) {
  27317. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27318. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  27319. var subMesh = mesh.subMeshes[subIndex];
  27320. subMesh.refreshBoundingInfo();
  27321. }
  27322. }
  27323. }
  27324. }
  27325. this.notifyUpdate(kind);
  27326. };
  27327. Geometry.prototype.getTotalVertices = function () {
  27328. if (!this.isReady()) {
  27329. return 0;
  27330. }
  27331. return this._totalVertices;
  27332. };
  27333. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  27334. var vertexBuffer = this.getVertexBuffer(kind);
  27335. if (!vertexBuffer) {
  27336. return null;
  27337. }
  27338. var orig = vertexBuffer.getData();
  27339. if (!copyWhenShared || this._meshes.length === 1) {
  27340. return orig;
  27341. }
  27342. else {
  27343. var len = orig.length;
  27344. var copy = [];
  27345. for (var i = 0; i < len; i++) {
  27346. copy.push(orig[i]);
  27347. }
  27348. return copy;
  27349. }
  27350. };
  27351. Geometry.prototype.getVertexBuffer = function (kind) {
  27352. if (!this.isReady()) {
  27353. return null;
  27354. }
  27355. return this._vertexBuffers[kind];
  27356. };
  27357. Geometry.prototype.getVertexBuffers = function () {
  27358. if (!this.isReady()) {
  27359. return null;
  27360. }
  27361. return this._vertexBuffers;
  27362. };
  27363. Geometry.prototype.isVerticesDataPresent = function (kind) {
  27364. if (!this._vertexBuffers) {
  27365. if (this._delayInfo) {
  27366. return this._delayInfo.indexOf(kind) !== -1;
  27367. }
  27368. return false;
  27369. }
  27370. return this._vertexBuffers[kind] !== undefined;
  27371. };
  27372. Geometry.prototype.getVerticesDataKinds = function () {
  27373. var result = [];
  27374. if (!this._vertexBuffers && this._delayInfo) {
  27375. for (var kind in this._delayInfo) {
  27376. result.push(kind);
  27377. }
  27378. }
  27379. else {
  27380. for (kind in this._vertexBuffers) {
  27381. result.push(kind);
  27382. }
  27383. }
  27384. return result;
  27385. };
  27386. Geometry.prototype.setIndices = function (indices, totalVertices) {
  27387. if (this._indexBuffer) {
  27388. this._engine._releaseBuffer(this._indexBuffer);
  27389. }
  27390. this._indices = indices;
  27391. if (this._meshes.length !== 0 && this._indices) {
  27392. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27393. }
  27394. if (totalVertices !== undefined) {
  27395. this._totalVertices = totalVertices;
  27396. }
  27397. var meshes = this._meshes;
  27398. var numOfMeshes = meshes.length;
  27399. for (var index = 0; index < numOfMeshes; index++) {
  27400. meshes[index]._createGlobalSubMesh();
  27401. }
  27402. this.notifyUpdate();
  27403. };
  27404. Geometry.prototype.getTotalIndices = function () {
  27405. if (!this.isReady()) {
  27406. return 0;
  27407. }
  27408. return this._indices.length;
  27409. };
  27410. Geometry.prototype.getIndices = function (copyWhenShared) {
  27411. if (!this.isReady()) {
  27412. return null;
  27413. }
  27414. var orig = this._indices;
  27415. if (!copyWhenShared || this._meshes.length === 1) {
  27416. return orig;
  27417. }
  27418. else {
  27419. var len = orig.length;
  27420. var copy = [];
  27421. for (var i = 0; i < len; i++) {
  27422. copy.push(orig[i]);
  27423. }
  27424. return copy;
  27425. }
  27426. };
  27427. Geometry.prototype.getIndexBuffer = function () {
  27428. if (!this.isReady()) {
  27429. return null;
  27430. }
  27431. return this._indexBuffer;
  27432. };
  27433. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  27434. var meshes = this._meshes;
  27435. var index = meshes.indexOf(mesh);
  27436. if (index === -1) {
  27437. return;
  27438. }
  27439. for (var kind in this._vertexBuffers) {
  27440. this._vertexBuffers[kind].dispose();
  27441. }
  27442. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  27443. this._indexBuffer = null;
  27444. }
  27445. meshes.splice(index, 1);
  27446. mesh._geometry = null;
  27447. if (meshes.length === 0 && shouldDispose) {
  27448. this.dispose();
  27449. }
  27450. };
  27451. Geometry.prototype.applyToMesh = function (mesh) {
  27452. if (mesh._geometry === this) {
  27453. return;
  27454. }
  27455. var previousGeometry = mesh._geometry;
  27456. if (previousGeometry) {
  27457. previousGeometry.releaseForMesh(mesh);
  27458. }
  27459. var meshes = this._meshes;
  27460. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  27461. mesh._geometry = this;
  27462. this._scene.pushGeometry(this);
  27463. meshes.push(mesh);
  27464. if (this.isReady()) {
  27465. this._applyToMesh(mesh);
  27466. }
  27467. else {
  27468. mesh._boundingInfo = this._boundingInfo;
  27469. }
  27470. };
  27471. Geometry.prototype._applyToMesh = function (mesh) {
  27472. var numOfMeshes = this._meshes.length;
  27473. // vertexBuffers
  27474. for (var kind in this._vertexBuffers) {
  27475. if (numOfMeshes === 1) {
  27476. this._vertexBuffers[kind].create();
  27477. }
  27478. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  27479. if (kind === BABYLON.VertexBuffer.PositionKind) {
  27480. mesh._resetPointsArrayCache();
  27481. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  27482. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27483. mesh._createGlobalSubMesh();
  27484. //bounding info was just created again, world matrix should be applied again.
  27485. mesh._updateBoundingInfo();
  27486. }
  27487. }
  27488. // indexBuffer
  27489. if (numOfMeshes === 1 && this._indices) {
  27490. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  27491. }
  27492. if (this._indexBuffer) {
  27493. this._indexBuffer.references = numOfMeshes;
  27494. }
  27495. };
  27496. Geometry.prototype.notifyUpdate = function (kind) {
  27497. if (this.onGeometryUpdated) {
  27498. this.onGeometryUpdated(this, kind);
  27499. }
  27500. };
  27501. Geometry.prototype.load = function (scene, onLoaded) {
  27502. var _this = this;
  27503. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  27504. return;
  27505. }
  27506. if (this.isReady()) {
  27507. if (onLoaded) {
  27508. onLoaded();
  27509. }
  27510. return;
  27511. }
  27512. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  27513. scene._addPendingData(this);
  27514. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  27515. _this._delayLoadingFunction(JSON.parse(data), _this);
  27516. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27517. _this._delayInfo = [];
  27518. scene._removePendingData(_this);
  27519. var meshes = _this._meshes;
  27520. var numOfMeshes = meshes.length;
  27521. for (var index = 0; index < numOfMeshes; index++) {
  27522. _this._applyToMesh(meshes[index]);
  27523. }
  27524. if (onLoaded) {
  27525. onLoaded();
  27526. }
  27527. }, function () { }, scene.database);
  27528. };
  27529. Geometry.prototype.isDisposed = function () {
  27530. return this._isDisposed;
  27531. };
  27532. Geometry.prototype.dispose = function () {
  27533. var meshes = this._meshes;
  27534. var numOfMeshes = meshes.length;
  27535. var index;
  27536. for (index = 0; index < numOfMeshes; index++) {
  27537. this.releaseForMesh(meshes[index]);
  27538. }
  27539. this._meshes = [];
  27540. for (var kind in this._vertexBuffers) {
  27541. this._vertexBuffers[kind].dispose();
  27542. }
  27543. this._vertexBuffers = [];
  27544. this._totalVertices = 0;
  27545. if (this._indexBuffer) {
  27546. this._engine._releaseBuffer(this._indexBuffer);
  27547. }
  27548. this._indexBuffer = null;
  27549. this._indices = [];
  27550. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27551. this.delayLoadingFile = null;
  27552. this._delayLoadingFunction = null;
  27553. this._delayInfo = [];
  27554. this._boundingInfo = null; // todo: .dispose()
  27555. this._scene.removeGeometry(this);
  27556. this._isDisposed = true;
  27557. };
  27558. Geometry.prototype.copy = function (id) {
  27559. var vertexData = new BABYLON.VertexData();
  27560. vertexData.indices = [];
  27561. var indices = this.getIndices();
  27562. for (var index = 0; index < indices.length; index++) {
  27563. vertexData.indices.push(indices[index]);
  27564. }
  27565. var updatable = false;
  27566. var stopChecking = false;
  27567. for (var kind in this._vertexBuffers) {
  27568. // using slice() to make a copy of the array and not just reference it
  27569. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  27570. if (!stopChecking) {
  27571. updatable = this.getVertexBuffer(kind).isUpdatable();
  27572. stopChecking = !updatable;
  27573. }
  27574. }
  27575. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  27576. geometry.delayLoadState = this.delayLoadState;
  27577. geometry.delayLoadingFile = this.delayLoadingFile;
  27578. geometry._delayLoadingFunction = this._delayLoadingFunction;
  27579. for (kind in this._delayInfo) {
  27580. geometry._delayInfo = geometry._delayInfo || [];
  27581. geometry._delayInfo.push(kind);
  27582. }
  27583. // Bounding info
  27584. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  27585. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  27586. return geometry;
  27587. };
  27588. // Statics
  27589. Geometry.ExtractFromMesh = function (mesh, id) {
  27590. var geometry = mesh._geometry;
  27591. if (!geometry) {
  27592. return null;
  27593. }
  27594. return geometry.copy(id);
  27595. };
  27596. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  27597. // be aware Math.random() could cause collisions
  27598. Geometry.RandomId = function () {
  27599. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  27600. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  27601. return v.toString(16);
  27602. });
  27603. };
  27604. return Geometry;
  27605. })();
  27606. BABYLON.Geometry = Geometry;
  27607. /////// Primitives //////////////////////////////////////////////
  27608. var Geometry;
  27609. (function (Geometry) {
  27610. var Primitives;
  27611. (function (Primitives) {
  27612. /// Abstract class
  27613. var _Primitive = (function (_super) {
  27614. __extends(_Primitive, _super);
  27615. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  27616. this._beingRegenerated = true;
  27617. this._canBeRegenerated = canBeRegenerated;
  27618. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  27619. this._beingRegenerated = false;
  27620. }
  27621. _Primitive.prototype.canBeRegenerated = function () {
  27622. return this._canBeRegenerated;
  27623. };
  27624. _Primitive.prototype.regenerate = function () {
  27625. if (!this._canBeRegenerated) {
  27626. return;
  27627. }
  27628. this._beingRegenerated = true;
  27629. this.setAllVerticesData(this._regenerateVertexData(), false);
  27630. this._beingRegenerated = false;
  27631. };
  27632. _Primitive.prototype.asNewGeometry = function (id) {
  27633. return _super.prototype.copy.call(this, id);
  27634. };
  27635. // overrides
  27636. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  27637. if (!this._beingRegenerated) {
  27638. return;
  27639. }
  27640. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  27641. };
  27642. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  27643. if (!this._beingRegenerated) {
  27644. return;
  27645. }
  27646. _super.prototype.setVerticesData.call(this, kind, data, false);
  27647. };
  27648. // to override
  27649. // protected
  27650. _Primitive.prototype._regenerateVertexData = function () {
  27651. throw new Error("Abstract method");
  27652. };
  27653. _Primitive.prototype.copy = function (id) {
  27654. throw new Error("Must be overriden in sub-classes.");
  27655. };
  27656. return _Primitive;
  27657. })(Geometry);
  27658. Primitives._Primitive = _Primitive;
  27659. var Ribbon = (function (_super) {
  27660. __extends(Ribbon, _super);
  27661. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  27662. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27663. this.pathArray = pathArray;
  27664. this.closeArray = closeArray;
  27665. this.closePath = closePath;
  27666. this.offset = offset;
  27667. this.side = side;
  27668. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27669. }
  27670. Ribbon.prototype._regenerateVertexData = function () {
  27671. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  27672. };
  27673. Ribbon.prototype.copy = function (id) {
  27674. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  27675. };
  27676. return Ribbon;
  27677. })(_Primitive);
  27678. Primitives.Ribbon = Ribbon;
  27679. var Box = (function (_super) {
  27680. __extends(Box, _super);
  27681. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  27682. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27683. this.size = size;
  27684. this.side = side;
  27685. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27686. }
  27687. Box.prototype._regenerateVertexData = function () {
  27688. return BABYLON.VertexData.CreateBox(this.size, this.side);
  27689. };
  27690. Box.prototype.copy = function (id) {
  27691. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27692. };
  27693. return Box;
  27694. })(_Primitive);
  27695. Primitives.Box = Box;
  27696. var Sphere = (function (_super) {
  27697. __extends(Sphere, _super);
  27698. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  27699. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27700. this.segments = segments;
  27701. this.diameter = diameter;
  27702. this.side = side;
  27703. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27704. }
  27705. Sphere.prototype._regenerateVertexData = function () {
  27706. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  27707. };
  27708. Sphere.prototype.copy = function (id) {
  27709. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  27710. };
  27711. return Sphere;
  27712. })(_Primitive);
  27713. Primitives.Sphere = Sphere;
  27714. var Cylinder = (function (_super) {
  27715. __extends(Cylinder, _super);
  27716. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  27717. if (subdivisions === void 0) { subdivisions = 1; }
  27718. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27719. this.height = height;
  27720. this.diameterTop = diameterTop;
  27721. this.diameterBottom = diameterBottom;
  27722. this.tessellation = tessellation;
  27723. this.subdivisions = subdivisions;
  27724. this.side = side;
  27725. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27726. }
  27727. Cylinder.prototype._regenerateVertexData = function () {
  27728. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  27729. };
  27730. Cylinder.prototype.copy = function (id) {
  27731. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  27732. };
  27733. return Cylinder;
  27734. })(_Primitive);
  27735. Primitives.Cylinder = Cylinder;
  27736. var Torus = (function (_super) {
  27737. __extends(Torus, _super);
  27738. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  27739. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27740. this.diameter = diameter;
  27741. this.thickness = thickness;
  27742. this.tessellation = tessellation;
  27743. this.side = side;
  27744. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27745. }
  27746. Torus.prototype._regenerateVertexData = function () {
  27747. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  27748. };
  27749. Torus.prototype.copy = function (id) {
  27750. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  27751. };
  27752. return Torus;
  27753. })(_Primitive);
  27754. Primitives.Torus = Torus;
  27755. var Ground = (function (_super) {
  27756. __extends(Ground, _super);
  27757. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  27758. this.width = width;
  27759. this.height = height;
  27760. this.subdivisions = subdivisions;
  27761. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27762. }
  27763. Ground.prototype._regenerateVertexData = function () {
  27764. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  27765. };
  27766. Ground.prototype.copy = function (id) {
  27767. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  27768. };
  27769. return Ground;
  27770. })(_Primitive);
  27771. Primitives.Ground = Ground;
  27772. var TiledGround = (function (_super) {
  27773. __extends(TiledGround, _super);
  27774. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  27775. this.xmin = xmin;
  27776. this.zmin = zmin;
  27777. this.xmax = xmax;
  27778. this.zmax = zmax;
  27779. this.subdivisions = subdivisions;
  27780. this.precision = precision;
  27781. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27782. }
  27783. TiledGround.prototype._regenerateVertexData = function () {
  27784. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  27785. };
  27786. TiledGround.prototype.copy = function (id) {
  27787. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  27788. };
  27789. return TiledGround;
  27790. })(_Primitive);
  27791. Primitives.TiledGround = TiledGround;
  27792. var Plane = (function (_super) {
  27793. __extends(Plane, _super);
  27794. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  27795. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27796. this.size = size;
  27797. this.side = side;
  27798. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27799. }
  27800. Plane.prototype._regenerateVertexData = function () {
  27801. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  27802. };
  27803. Plane.prototype.copy = function (id) {
  27804. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  27805. };
  27806. return Plane;
  27807. })(_Primitive);
  27808. Primitives.Plane = Plane;
  27809. var TorusKnot = (function (_super) {
  27810. __extends(TorusKnot, _super);
  27811. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  27812. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  27813. this.radius = radius;
  27814. this.tube = tube;
  27815. this.radialSegments = radialSegments;
  27816. this.tubularSegments = tubularSegments;
  27817. this.p = p;
  27818. this.q = q;
  27819. this.side = side;
  27820. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  27821. }
  27822. TorusKnot.prototype._regenerateVertexData = function () {
  27823. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  27824. };
  27825. TorusKnot.prototype.copy = function (id) {
  27826. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  27827. };
  27828. return TorusKnot;
  27829. })(_Primitive);
  27830. Primitives.TorusKnot = TorusKnot;
  27831. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  27832. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  27833. })(BABYLON || (BABYLON = {}));
  27834. //# sourceMappingURL=babylon.geometry.js.map
  27835. var BABYLON;
  27836. (function (BABYLON) {
  27837. var GroundMesh = (function (_super) {
  27838. __extends(GroundMesh, _super);
  27839. function GroundMesh(name, scene) {
  27840. _super.call(this, name, scene);
  27841. this.generateOctree = false;
  27842. this._worldInverse = new BABYLON.Matrix();
  27843. }
  27844. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  27845. get: function () {
  27846. return this._subdivisions;
  27847. },
  27848. enumerable: true,
  27849. configurable: true
  27850. });
  27851. GroundMesh.prototype.optimize = function (chunksCount) {
  27852. this.subdivide(this._subdivisions);
  27853. this.createOrUpdateSubmeshesOctree(32);
  27854. };
  27855. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  27856. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  27857. this.getWorldMatrix().invertToRef(this._worldInverse);
  27858. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  27859. var pickInfo = this.intersects(ray);
  27860. if (pickInfo.hit) {
  27861. return pickInfo.pickedPoint.y;
  27862. }
  27863. return 0;
  27864. };
  27865. return GroundMesh;
  27866. })(BABYLON.Mesh);
  27867. BABYLON.GroundMesh = GroundMesh;
  27868. })(BABYLON || (BABYLON = {}));
  27869. //# sourceMappingURL=babylon.groundMesh.js.map
  27870. var BABYLON;
  27871. (function (BABYLON) {
  27872. var LinesMesh = (function (_super) {
  27873. __extends(LinesMesh, _super);
  27874. function LinesMesh(name, scene, updatable) {
  27875. if (updatable === void 0) { updatable = false; }
  27876. _super.call(this, name, scene);
  27877. this.color = new BABYLON.Color3(1, 1, 1);
  27878. this.alpha = 1;
  27879. this._indices = new Array();
  27880. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  27881. attributes: ["position"],
  27882. uniforms: ["worldViewProjection", "color"],
  27883. needAlphaBlending: true
  27884. });
  27885. }
  27886. Object.defineProperty(LinesMesh.prototype, "material", {
  27887. get: function () {
  27888. return this._colorShader;
  27889. },
  27890. enumerable: true,
  27891. configurable: true
  27892. });
  27893. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  27894. get: function () {
  27895. return false;
  27896. },
  27897. enumerable: true,
  27898. configurable: true
  27899. });
  27900. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  27901. get: function () {
  27902. return false;
  27903. },
  27904. enumerable: true,
  27905. configurable: true
  27906. });
  27907. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  27908. var engine = this.getScene().getEngine();
  27909. var indexToBind = this._geometry.getIndexBuffer();
  27910. // VBOs
  27911. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  27912. // Color
  27913. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  27914. };
  27915. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  27916. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  27917. return;
  27918. }
  27919. var engine = this.getScene().getEngine();
  27920. // Draw order
  27921. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  27922. };
  27923. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  27924. return null;
  27925. };
  27926. LinesMesh.prototype.dispose = function (doNotRecurse) {
  27927. this._colorShader.dispose();
  27928. _super.prototype.dispose.call(this, doNotRecurse);
  27929. };
  27930. return LinesMesh;
  27931. })(BABYLON.Mesh);
  27932. BABYLON.LinesMesh = LinesMesh;
  27933. })(BABYLON || (BABYLON = {}));
  27934. //# sourceMappingURL=babylon.linesMesh.js.map
  27935. var BABYLON;
  27936. (function (BABYLON) {
  27937. var OutlineRenderer = (function () {
  27938. function OutlineRenderer(scene) {
  27939. this._scene = scene;
  27940. }
  27941. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  27942. var _this = this;
  27943. if (useOverlay === void 0) { useOverlay = false; }
  27944. var scene = this._scene;
  27945. var engine = this._scene.getEngine();
  27946. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  27947. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  27948. return;
  27949. }
  27950. var mesh = subMesh.getRenderingMesh();
  27951. var material = subMesh.getMaterial();
  27952. engine.enableEffect(this._effect);
  27953. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  27954. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  27955. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  27956. // Bones
  27957. if (mesh.useBones) {
  27958. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  27959. }
  27960. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  27961. // Alpha test
  27962. if (material && material.needAlphaTesting()) {
  27963. var alphaTexture = material.getAlphaTestTexture();
  27964. this._effect.setTexture("diffuseSampler", alphaTexture);
  27965. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  27966. }
  27967. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  27968. };
  27969. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  27970. var defines = [];
  27971. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  27972. var mesh = subMesh.getMesh();
  27973. var material = subMesh.getMaterial();
  27974. // Alpha test
  27975. if (material && material.needAlphaTesting()) {
  27976. defines.push("#define ALPHATEST");
  27977. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27978. attribs.push(BABYLON.VertexBuffer.UVKind);
  27979. defines.push("#define UV1");
  27980. }
  27981. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27982. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27983. defines.push("#define UV2");
  27984. }
  27985. }
  27986. // Bones
  27987. if (mesh.useBones) {
  27988. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  27989. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  27990. defines.push("#define BONES");
  27991. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  27992. }
  27993. // Instances
  27994. if (useInstances) {
  27995. defines.push("#define INSTANCES");
  27996. attribs.push("world0");
  27997. attribs.push("world1");
  27998. attribs.push("world2");
  27999. attribs.push("world3");
  28000. }
  28001. // Get correct effect
  28002. var join = defines.join("\n");
  28003. if (this._cachedDefines !== join) {
  28004. this._cachedDefines = join;
  28005. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  28006. }
  28007. return this._effect.isReady();
  28008. };
  28009. return OutlineRenderer;
  28010. })();
  28011. BABYLON.OutlineRenderer = OutlineRenderer;
  28012. })(BABYLON || (BABYLON = {}));
  28013. //# sourceMappingURL=babylon.outlineRenderer.js.map
  28014. var BABYLON;
  28015. (function (BABYLON) {
  28016. var MeshAssetTask = (function () {
  28017. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  28018. this.name = name;
  28019. this.meshesNames = meshesNames;
  28020. this.rootUrl = rootUrl;
  28021. this.sceneFilename = sceneFilename;
  28022. this.isCompleted = false;
  28023. }
  28024. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28025. var _this = this;
  28026. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  28027. _this.loadedMeshes = meshes;
  28028. _this.loadedParticleSystems = particleSystems;
  28029. _this.loadedSkeletons = skeletons;
  28030. _this.isCompleted = true;
  28031. if (_this.onSuccess) {
  28032. _this.onSuccess(_this);
  28033. }
  28034. onSuccess();
  28035. }, null, function () {
  28036. if (_this.onError) {
  28037. _this.onError(_this);
  28038. }
  28039. onError();
  28040. });
  28041. };
  28042. return MeshAssetTask;
  28043. })();
  28044. BABYLON.MeshAssetTask = MeshAssetTask;
  28045. var TextFileAssetTask = (function () {
  28046. function TextFileAssetTask(name, url) {
  28047. this.name = name;
  28048. this.url = url;
  28049. this.isCompleted = false;
  28050. }
  28051. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28052. var _this = this;
  28053. BABYLON.Tools.LoadFile(this.url, function (data) {
  28054. _this.text = data;
  28055. _this.isCompleted = true;
  28056. if (_this.onSuccess) {
  28057. _this.onSuccess(_this);
  28058. }
  28059. onSuccess();
  28060. }, null, scene.database, false, function () {
  28061. if (_this.onError) {
  28062. _this.onError(_this);
  28063. }
  28064. onError();
  28065. });
  28066. };
  28067. return TextFileAssetTask;
  28068. })();
  28069. BABYLON.TextFileAssetTask = TextFileAssetTask;
  28070. var BinaryFileAssetTask = (function () {
  28071. function BinaryFileAssetTask(name, url) {
  28072. this.name = name;
  28073. this.url = url;
  28074. this.isCompleted = false;
  28075. }
  28076. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28077. var _this = this;
  28078. BABYLON.Tools.LoadFile(this.url, function (data) {
  28079. _this.data = data;
  28080. _this.isCompleted = true;
  28081. if (_this.onSuccess) {
  28082. _this.onSuccess(_this);
  28083. }
  28084. onSuccess();
  28085. }, null, scene.database, true, function () {
  28086. if (_this.onError) {
  28087. _this.onError(_this);
  28088. }
  28089. onError();
  28090. });
  28091. };
  28092. return BinaryFileAssetTask;
  28093. })();
  28094. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  28095. var ImageAssetTask = (function () {
  28096. function ImageAssetTask(name, url) {
  28097. this.name = name;
  28098. this.url = url;
  28099. this.isCompleted = false;
  28100. }
  28101. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28102. var _this = this;
  28103. var img = new Image();
  28104. img.onload = function () {
  28105. _this.image = img;
  28106. _this.isCompleted = true;
  28107. if (_this.onSuccess) {
  28108. _this.onSuccess(_this);
  28109. }
  28110. onSuccess();
  28111. };
  28112. img.onerror = function () {
  28113. if (_this.onError) {
  28114. _this.onError(_this);
  28115. }
  28116. onError();
  28117. };
  28118. img.src = this.url;
  28119. };
  28120. return ImageAssetTask;
  28121. })();
  28122. BABYLON.ImageAssetTask = ImageAssetTask;
  28123. var TextureAssetTask = (function () {
  28124. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  28125. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28126. this.name = name;
  28127. this.url = url;
  28128. this.noMipmap = noMipmap;
  28129. this.invertY = invertY;
  28130. this.samplingMode = samplingMode;
  28131. this.isCompleted = false;
  28132. }
  28133. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  28134. var _this = this;
  28135. var onload = function () {
  28136. _this.isCompleted = true;
  28137. if (_this.onSuccess) {
  28138. _this.onSuccess(_this);
  28139. }
  28140. onSuccess();
  28141. };
  28142. var onerror = function () {
  28143. if (_this.onError) {
  28144. _this.onError(_this);
  28145. }
  28146. onError();
  28147. };
  28148. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  28149. };
  28150. return TextureAssetTask;
  28151. })();
  28152. BABYLON.TextureAssetTask = TextureAssetTask;
  28153. var AssetsManager = (function () {
  28154. function AssetsManager(scene) {
  28155. this._tasks = new Array();
  28156. this._waitingTasksCount = 0;
  28157. this.useDefaultLoadingScreen = true;
  28158. this._scene = scene;
  28159. }
  28160. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  28161. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  28162. this._tasks.push(task);
  28163. return task;
  28164. };
  28165. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  28166. var task = new TextFileAssetTask(taskName, url);
  28167. this._tasks.push(task);
  28168. return task;
  28169. };
  28170. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  28171. var task = new BinaryFileAssetTask(taskName, url);
  28172. this._tasks.push(task);
  28173. return task;
  28174. };
  28175. AssetsManager.prototype.addImageTask = function (taskName, url) {
  28176. var task = new ImageAssetTask(taskName, url);
  28177. this._tasks.push(task);
  28178. return task;
  28179. };
  28180. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  28181. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28182. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  28183. this._tasks.push(task);
  28184. return task;
  28185. };
  28186. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  28187. this._waitingTasksCount--;
  28188. if (this._waitingTasksCount === 0) {
  28189. if (this.onFinish) {
  28190. this.onFinish(this._tasks);
  28191. }
  28192. this._scene.getEngine().hideLoadingUI();
  28193. }
  28194. };
  28195. AssetsManager.prototype._runTask = function (task) {
  28196. var _this = this;
  28197. task.run(this._scene, function () {
  28198. if (_this.onTaskSuccess) {
  28199. _this.onTaskSuccess(task);
  28200. }
  28201. _this._decreaseWaitingTasksCount();
  28202. }, function () {
  28203. if (_this.onTaskError) {
  28204. _this.onTaskError(task);
  28205. }
  28206. _this._decreaseWaitingTasksCount();
  28207. });
  28208. };
  28209. AssetsManager.prototype.reset = function () {
  28210. this._tasks = new Array();
  28211. return this;
  28212. };
  28213. AssetsManager.prototype.load = function () {
  28214. this._waitingTasksCount = this._tasks.length;
  28215. if (this._waitingTasksCount === 0) {
  28216. if (this.onFinish) {
  28217. this.onFinish(this._tasks);
  28218. }
  28219. return this;
  28220. }
  28221. if (this.useDefaultLoadingScreen) {
  28222. this._scene.getEngine().displayLoadingUI();
  28223. }
  28224. for (var index = 0; index < this._tasks.length; index++) {
  28225. var task = this._tasks[index];
  28226. this._runTask(task);
  28227. }
  28228. return this;
  28229. };
  28230. return AssetsManager;
  28231. })();
  28232. BABYLON.AssetsManager = AssetsManager;
  28233. })(BABYLON || (BABYLON = {}));
  28234. //# sourceMappingURL=babylon.assetsManager.js.map
  28235. var BABYLON;
  28236. (function (BABYLON) {
  28237. var VRDeviceOrientationFreeCamera = (function (_super) {
  28238. __extends(VRDeviceOrientationFreeCamera, _super);
  28239. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistorsion) {
  28240. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  28241. _super.call(this, name, position, scene);
  28242. this._alpha = 0;
  28243. this._beta = 0;
  28244. this._gamma = 0;
  28245. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  28246. metrics.compensateDistorsion = compensateDistorsion;
  28247. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  28248. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  28249. }
  28250. VRDeviceOrientationFreeCamera.prototype._onOrientationEvent = function (evt) {
  28251. this._alpha = +evt.alpha | 0;
  28252. this._beta = +evt.beta | 0;
  28253. this._gamma = +evt.gamma | 0;
  28254. if (this._gamma < 0) {
  28255. this._gamma = 90 + this._gamma;
  28256. }
  28257. else {
  28258. // Incline it in the correct angle.
  28259. this._gamma = 270 - this._gamma;
  28260. }
  28261. this.rotation.x = this._gamma / 180.0 * Math.PI;
  28262. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  28263. this.rotation.z = this._beta / 180.0 * Math.PI;
  28264. };
  28265. VRDeviceOrientationFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  28266. _super.prototype.attachControl.call(this, element, noPreventDefault);
  28267. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  28268. };
  28269. VRDeviceOrientationFreeCamera.prototype.detachControl = function (element) {
  28270. _super.prototype.detachControl.call(this, element);
  28271. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  28272. };
  28273. return VRDeviceOrientationFreeCamera;
  28274. })(BABYLON.FreeCamera);
  28275. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  28276. })(BABYLON || (BABYLON = {}));
  28277. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  28278. var BABYLON;
  28279. (function (BABYLON) {
  28280. var WebVRFreeCamera = (function (_super) {
  28281. __extends(WebVRFreeCamera, _super);
  28282. function WebVRFreeCamera(name, position, scene, compensateDistorsion) {
  28283. if (compensateDistorsion === void 0) { compensateDistorsion = true; }
  28284. _super.call(this, name, position, scene);
  28285. this._hmdDevice = null;
  28286. this._sensorDevice = null;
  28287. this._cacheState = null;
  28288. this._cacheQuaternion = new BABYLON.Quaternion();
  28289. this._cacheRotation = BABYLON.Vector3.Zero();
  28290. this._vrEnabled = false;
  28291. var metrics = BABYLON.VRCameraMetrics.GetDefault();
  28292. metrics.compensateDistorsion = compensateDistorsion;
  28293. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: metrics });
  28294. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  28295. }
  28296. WebVRFreeCamera.prototype._getWebVRDevices = function (devices) {
  28297. var size = devices.length;
  28298. var i = 0;
  28299. // Reset devices.
  28300. this._sensorDevice = null;
  28301. this._hmdDevice = null;
  28302. // Search for a HmdDevice.
  28303. while (i < size && this._hmdDevice === null) {
  28304. if (devices[i] instanceof HMDVRDevice) {
  28305. this._hmdDevice = devices[i];
  28306. }
  28307. i++;
  28308. }
  28309. i = 0;
  28310. while (i < size && this._sensorDevice === null) {
  28311. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  28312. this._sensorDevice = devices[i];
  28313. }
  28314. i++;
  28315. }
  28316. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  28317. };
  28318. WebVRFreeCamera.prototype._checkInputs = function () {
  28319. if (this._vrEnabled) {
  28320. this._cacheState = this._sensorDevice.getState();
  28321. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  28322. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  28323. this.rotation.x = -this._cacheRotation.z;
  28324. this.rotation.y = -this._cacheRotation.y;
  28325. this.rotation.z = this._cacheRotation.x;
  28326. }
  28327. _super.prototype._checkInputs.call(this);
  28328. };
  28329. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  28330. _super.prototype.attachControl.call(this, element, noPreventDefault);
  28331. if (navigator.getVRDevices) {
  28332. navigator.getVRDevices().then(this._getWebVRDevices);
  28333. }
  28334. else if (navigator.mozGetVRDevices) {
  28335. navigator.mozGetVRDevices(this._getWebVRDevices);
  28336. }
  28337. };
  28338. WebVRFreeCamera.prototype.detachControl = function (element) {
  28339. _super.prototype.detachControl.call(this, element);
  28340. this._vrEnabled = false;
  28341. };
  28342. return WebVRFreeCamera;
  28343. })(BABYLON.FreeCamera);
  28344. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  28345. })(BABYLON || (BABYLON = {}));
  28346. //# sourceMappingURL=babylon.webVRCamera.js.map
  28347. var BABYLON;
  28348. (function (BABYLON) {
  28349. // Standard optimizations
  28350. var SceneOptimization = (function () {
  28351. function SceneOptimization(priority) {
  28352. if (priority === void 0) { priority = 0; }
  28353. this.priority = priority;
  28354. this.apply = function (scene) {
  28355. return true; // Return true if everything that can be done was applied
  28356. };
  28357. }
  28358. return SceneOptimization;
  28359. })();
  28360. BABYLON.SceneOptimization = SceneOptimization;
  28361. var TextureOptimization = (function (_super) {
  28362. __extends(TextureOptimization, _super);
  28363. function TextureOptimization(priority, maximumSize) {
  28364. var _this = this;
  28365. if (priority === void 0) { priority = 0; }
  28366. if (maximumSize === void 0) { maximumSize = 1024; }
  28367. _super.call(this, priority);
  28368. this.priority = priority;
  28369. this.maximumSize = maximumSize;
  28370. this.apply = function (scene) {
  28371. var allDone = true;
  28372. for (var index = 0; index < scene.textures.length; index++) {
  28373. var texture = scene.textures[index];
  28374. if (!texture.canRescale) {
  28375. continue;
  28376. }
  28377. var currentSize = texture.getSize();
  28378. var maxDimension = Math.max(currentSize.width, currentSize.height);
  28379. if (maxDimension > _this.maximumSize) {
  28380. texture.scale(0.5);
  28381. allDone = false;
  28382. }
  28383. }
  28384. return allDone;
  28385. };
  28386. }
  28387. return TextureOptimization;
  28388. })(SceneOptimization);
  28389. BABYLON.TextureOptimization = TextureOptimization;
  28390. var HardwareScalingOptimization = (function (_super) {
  28391. __extends(HardwareScalingOptimization, _super);
  28392. function HardwareScalingOptimization(priority, maximumScale) {
  28393. var _this = this;
  28394. if (priority === void 0) { priority = 0; }
  28395. if (maximumScale === void 0) { maximumScale = 2; }
  28396. _super.call(this, priority);
  28397. this.priority = priority;
  28398. this.maximumScale = maximumScale;
  28399. this._currentScale = 1;
  28400. this.apply = function (scene) {
  28401. _this._currentScale++;
  28402. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  28403. return _this._currentScale >= _this.maximumScale;
  28404. };
  28405. }
  28406. return HardwareScalingOptimization;
  28407. })(SceneOptimization);
  28408. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  28409. var ShadowsOptimization = (function (_super) {
  28410. __extends(ShadowsOptimization, _super);
  28411. function ShadowsOptimization() {
  28412. _super.apply(this, arguments);
  28413. this.apply = function (scene) {
  28414. scene.shadowsEnabled = false;
  28415. return true;
  28416. };
  28417. }
  28418. return ShadowsOptimization;
  28419. })(SceneOptimization);
  28420. BABYLON.ShadowsOptimization = ShadowsOptimization;
  28421. var PostProcessesOptimization = (function (_super) {
  28422. __extends(PostProcessesOptimization, _super);
  28423. function PostProcessesOptimization() {
  28424. _super.apply(this, arguments);
  28425. this.apply = function (scene) {
  28426. scene.postProcessesEnabled = false;
  28427. return true;
  28428. };
  28429. }
  28430. return PostProcessesOptimization;
  28431. })(SceneOptimization);
  28432. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  28433. var LensFlaresOptimization = (function (_super) {
  28434. __extends(LensFlaresOptimization, _super);
  28435. function LensFlaresOptimization() {
  28436. _super.apply(this, arguments);
  28437. this.apply = function (scene) {
  28438. scene.lensFlaresEnabled = false;
  28439. return true;
  28440. };
  28441. }
  28442. return LensFlaresOptimization;
  28443. })(SceneOptimization);
  28444. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  28445. var ParticlesOptimization = (function (_super) {
  28446. __extends(ParticlesOptimization, _super);
  28447. function ParticlesOptimization() {
  28448. _super.apply(this, arguments);
  28449. this.apply = function (scene) {
  28450. scene.particlesEnabled = false;
  28451. return true;
  28452. };
  28453. }
  28454. return ParticlesOptimization;
  28455. })(SceneOptimization);
  28456. BABYLON.ParticlesOptimization = ParticlesOptimization;
  28457. var RenderTargetsOptimization = (function (_super) {
  28458. __extends(RenderTargetsOptimization, _super);
  28459. function RenderTargetsOptimization() {
  28460. _super.apply(this, arguments);
  28461. this.apply = function (scene) {
  28462. scene.renderTargetsEnabled = false;
  28463. return true;
  28464. };
  28465. }
  28466. return RenderTargetsOptimization;
  28467. })(SceneOptimization);
  28468. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  28469. var MergeMeshesOptimization = (function (_super) {
  28470. __extends(MergeMeshesOptimization, _super);
  28471. function MergeMeshesOptimization() {
  28472. var _this = this;
  28473. _super.apply(this, arguments);
  28474. this._canBeMerged = function (abstractMesh) {
  28475. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  28476. return false;
  28477. }
  28478. var mesh = abstractMesh;
  28479. if (!mesh.isVisible || !mesh.isEnabled()) {
  28480. return false;
  28481. }
  28482. if (mesh.instances.length > 0) {
  28483. return false;
  28484. }
  28485. if (mesh.skeleton || mesh.hasLODLevels) {
  28486. return false;
  28487. }
  28488. return true;
  28489. };
  28490. this.apply = function (scene) {
  28491. var globalPool = scene.meshes.slice(0);
  28492. var globalLength = globalPool.length;
  28493. for (var index = 0; index < globalLength; index++) {
  28494. var currentPool = new Array();
  28495. var current = globalPool[index];
  28496. // Checks
  28497. if (!_this._canBeMerged(current)) {
  28498. continue;
  28499. }
  28500. currentPool.push(current);
  28501. // Find compatible meshes
  28502. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  28503. var otherMesh = globalPool[subIndex];
  28504. if (!_this._canBeMerged(otherMesh)) {
  28505. continue;
  28506. }
  28507. if (otherMesh.material !== current.material) {
  28508. continue;
  28509. }
  28510. if (otherMesh.checkCollisions !== current.checkCollisions) {
  28511. continue;
  28512. }
  28513. currentPool.push(otherMesh);
  28514. globalLength--;
  28515. globalPool.splice(subIndex, 1);
  28516. subIndex--;
  28517. }
  28518. if (currentPool.length < 2) {
  28519. continue;
  28520. }
  28521. // Merge meshes
  28522. BABYLON.Mesh.MergeMeshes(currentPool);
  28523. }
  28524. return true;
  28525. };
  28526. }
  28527. return MergeMeshesOptimization;
  28528. })(SceneOptimization);
  28529. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  28530. // Options
  28531. var SceneOptimizerOptions = (function () {
  28532. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  28533. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  28534. if (trackerDuration === void 0) { trackerDuration = 2000; }
  28535. this.targetFrameRate = targetFrameRate;
  28536. this.trackerDuration = trackerDuration;
  28537. this.optimizations = new Array();
  28538. }
  28539. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  28540. var result = new SceneOptimizerOptions(targetFrameRate);
  28541. var priority = 0;
  28542. result.optimizations.push(new MergeMeshesOptimization(priority));
  28543. result.optimizations.push(new ShadowsOptimization(priority));
  28544. result.optimizations.push(new LensFlaresOptimization(priority));
  28545. // Next priority
  28546. priority++;
  28547. result.optimizations.push(new PostProcessesOptimization(priority));
  28548. result.optimizations.push(new ParticlesOptimization(priority));
  28549. // Next priority
  28550. priority++;
  28551. result.optimizations.push(new TextureOptimization(priority, 1024));
  28552. return result;
  28553. };
  28554. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  28555. var result = new SceneOptimizerOptions(targetFrameRate);
  28556. var priority = 0;
  28557. result.optimizations.push(new MergeMeshesOptimization(priority));
  28558. result.optimizations.push(new ShadowsOptimization(priority));
  28559. result.optimizations.push(new LensFlaresOptimization(priority));
  28560. // Next priority
  28561. priority++;
  28562. result.optimizations.push(new PostProcessesOptimization(priority));
  28563. result.optimizations.push(new ParticlesOptimization(priority));
  28564. // Next priority
  28565. priority++;
  28566. result.optimizations.push(new TextureOptimization(priority, 512));
  28567. // Next priority
  28568. priority++;
  28569. result.optimizations.push(new RenderTargetsOptimization(priority));
  28570. // Next priority
  28571. priority++;
  28572. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  28573. return result;
  28574. };
  28575. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  28576. var result = new SceneOptimizerOptions(targetFrameRate);
  28577. var priority = 0;
  28578. result.optimizations.push(new MergeMeshesOptimization(priority));
  28579. result.optimizations.push(new ShadowsOptimization(priority));
  28580. result.optimizations.push(new LensFlaresOptimization(priority));
  28581. // Next priority
  28582. priority++;
  28583. result.optimizations.push(new PostProcessesOptimization(priority));
  28584. result.optimizations.push(new ParticlesOptimization(priority));
  28585. // Next priority
  28586. priority++;
  28587. result.optimizations.push(new TextureOptimization(priority, 256));
  28588. // Next priority
  28589. priority++;
  28590. result.optimizations.push(new RenderTargetsOptimization(priority));
  28591. // Next priority
  28592. priority++;
  28593. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  28594. return result;
  28595. };
  28596. return SceneOptimizerOptions;
  28597. })();
  28598. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  28599. // Scene optimizer tool
  28600. var SceneOptimizer = (function () {
  28601. function SceneOptimizer() {
  28602. }
  28603. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  28604. // TODO: add an epsilon
  28605. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  28606. if (onSuccess) {
  28607. onSuccess();
  28608. }
  28609. return;
  28610. }
  28611. // Apply current level of optimizations
  28612. var allDone = true;
  28613. var noOptimizationApplied = true;
  28614. for (var index = 0; index < options.optimizations.length; index++) {
  28615. var optimization = options.optimizations[index];
  28616. if (optimization.priority === currentPriorityLevel) {
  28617. noOptimizationApplied = false;
  28618. allDone = allDone && optimization.apply(scene);
  28619. }
  28620. }
  28621. // If no optimization was applied, this is a failure :(
  28622. if (noOptimizationApplied) {
  28623. if (onFailure) {
  28624. onFailure();
  28625. }
  28626. return;
  28627. }
  28628. // If all optimizations were done, move to next level
  28629. if (allDone) {
  28630. currentPriorityLevel++;
  28631. }
  28632. // Let's the system running for a specific amount of time before checking FPS
  28633. scene.executeWhenReady(function () {
  28634. setTimeout(function () {
  28635. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  28636. }, options.trackerDuration);
  28637. });
  28638. };
  28639. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  28640. if (!options) {
  28641. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  28642. }
  28643. // Let's the system running for a specific amount of time before checking FPS
  28644. scene.executeWhenReady(function () {
  28645. setTimeout(function () {
  28646. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  28647. }, options.trackerDuration);
  28648. });
  28649. };
  28650. return SceneOptimizer;
  28651. })();
  28652. BABYLON.SceneOptimizer = SceneOptimizer;
  28653. })(BABYLON || (BABYLON = {}));
  28654. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  28655. var BABYLON;
  28656. (function (BABYLON) {
  28657. var Internals;
  28658. (function (Internals) {
  28659. var MeshLODLevel = (function () {
  28660. function MeshLODLevel(distance, mesh) {
  28661. this.distance = distance;
  28662. this.mesh = mesh;
  28663. }
  28664. return MeshLODLevel;
  28665. })();
  28666. Internals.MeshLODLevel = MeshLODLevel;
  28667. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28668. })(BABYLON || (BABYLON = {}));
  28669. //# sourceMappingURL=babylon.meshLODLevel.js.map
  28670. var BABYLON;
  28671. (function (BABYLON) {
  28672. var AudioEngine = (function () {
  28673. function AudioEngine() {
  28674. this._audioContext = null;
  28675. this._audioContextInitialized = false;
  28676. this.canUseWebAudio = false;
  28677. this.WarnedWebAudioUnsupported = false;
  28678. if (typeof AudioContext !== 'undefined' || typeof webkitAudioContext !== 'undefined') {
  28679. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  28680. this.canUseWebAudio = true;
  28681. }
  28682. }
  28683. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  28684. get: function () {
  28685. if (!this._audioContextInitialized) {
  28686. this._initializeAudioContext();
  28687. }
  28688. return this._audioContext;
  28689. },
  28690. enumerable: true,
  28691. configurable: true
  28692. });
  28693. AudioEngine.prototype._initializeAudioContext = function () {
  28694. try {
  28695. if (this.canUseWebAudio) {
  28696. this._audioContext = new AudioContext();
  28697. // create a global volume gain node
  28698. this.masterGain = this._audioContext.createGain();
  28699. this.masterGain.gain.value = 1;
  28700. this.masterGain.connect(this._audioContext.destination);
  28701. this._audioContextInitialized = true;
  28702. }
  28703. }
  28704. catch (e) {
  28705. this.canUseWebAudio = false;
  28706. BABYLON.Tools.Error("Web Audio: " + e.message);
  28707. }
  28708. };
  28709. AudioEngine.prototype.dispose = function () {
  28710. if (this.canUseWebAudio && this._audioContextInitialized) {
  28711. if (this._connectedAnalyser) {
  28712. this._connectedAnalyser.stopDebugCanvas();
  28713. this._connectedAnalyser.dispose();
  28714. this.masterGain.disconnect();
  28715. this.masterGain.connect(this._audioContext.destination);
  28716. this._connectedAnalyser = null;
  28717. }
  28718. this.masterGain.gain.value = 1;
  28719. }
  28720. this.WarnedWebAudioUnsupported = false;
  28721. };
  28722. AudioEngine.prototype.getGlobalVolume = function () {
  28723. if (this.canUseWebAudio && this._audioContextInitialized) {
  28724. return this.masterGain.gain.value;
  28725. }
  28726. else {
  28727. return -1;
  28728. }
  28729. };
  28730. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  28731. if (this.canUseWebAudio && this._audioContextInitialized) {
  28732. this.masterGain.gain.value = newVolume;
  28733. }
  28734. };
  28735. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  28736. if (this._connectedAnalyser) {
  28737. this._connectedAnalyser.stopDebugCanvas();
  28738. }
  28739. if (this.canUseWebAudio && this._audioContextInitialized) {
  28740. this._connectedAnalyser = analyser;
  28741. this.masterGain.disconnect();
  28742. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  28743. }
  28744. };
  28745. return AudioEngine;
  28746. })();
  28747. BABYLON.AudioEngine = AudioEngine;
  28748. })(BABYLON || (BABYLON = {}));
  28749. //# sourceMappingURL=babylon.audioEngine.js.map
  28750. var BABYLON;
  28751. (function (BABYLON) {
  28752. var Sound = (function () {
  28753. /**
  28754. * Create a sound and attach it to a scene
  28755. * @param name Name of your sound
  28756. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  28757. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  28758. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  28759. */
  28760. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  28761. var _this = this;
  28762. this.autoplay = false;
  28763. this.loop = false;
  28764. this.useCustomAttenuation = false;
  28765. this.spatialSound = false;
  28766. this.refDistance = 1;
  28767. this.rolloffFactor = 1;
  28768. this.maxDistance = 100;
  28769. this.distanceModel = "linear";
  28770. this._panningModel = "equalpower";
  28771. this._playbackRate = 1;
  28772. this._startTime = 0;
  28773. this._startOffset = 0;
  28774. this._position = BABYLON.Vector3.Zero();
  28775. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  28776. this._volume = 1;
  28777. this._isLoaded = false;
  28778. this._isReadyToPlay = false;
  28779. this.isPlaying = false;
  28780. this.isPaused = false;
  28781. this._isDirectional = false;
  28782. // Used if you'd like to create a directional sound.
  28783. // If not set, the sound will be omnidirectional
  28784. this._coneInnerAngle = 360;
  28785. this._coneOuterAngle = 360;
  28786. this._coneOuterGain = 0;
  28787. this.name = name;
  28788. this._scene = scene;
  28789. this._readyToPlayCallback = readyToPlayCallback;
  28790. // Default custom attenuation function is a linear attenuation
  28791. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  28792. if (currentDistance < maxDistance) {
  28793. return currentVolume * (1 - currentDistance / maxDistance);
  28794. }
  28795. else {
  28796. return 0;
  28797. }
  28798. };
  28799. if (options) {
  28800. this.autoplay = options.autoplay || false;
  28801. this.loop = options.loop || false;
  28802. // if volume === 0, we need another way to check this option
  28803. if (options.volume !== undefined) {
  28804. this._volume = options.volume;
  28805. }
  28806. this.spatialSound = options.spatialSound || false;
  28807. this.maxDistance = options.maxDistance || 100;
  28808. this.useCustomAttenuation = options.useCustomAttenuation || false;
  28809. this.rolloffFactor = options.rolloffFactor || 1;
  28810. this.refDistance = options.refDistance || 1;
  28811. this.distanceModel = options.distanceModel || "linear";
  28812. this._playbackRate = options.playbackRate || 1;
  28813. }
  28814. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28815. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  28816. this._soundGain.gain.value = this._volume;
  28817. this._inputAudioNode = this._soundGain;
  28818. this._ouputAudioNode = this._soundGain;
  28819. if (this.spatialSound) {
  28820. this._createSpatialParameters();
  28821. }
  28822. this._scene.mainSoundTrack.AddSound(this);
  28823. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  28824. if (urlOrArrayBuffer) {
  28825. // If it's an URL
  28826. if (typeof (urlOrArrayBuffer) === "string") {
  28827. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) { _this._soundLoaded(data); }, null, null, true);
  28828. }
  28829. else {
  28830. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  28831. this._soundLoaded(urlOrArrayBuffer);
  28832. }
  28833. else {
  28834. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  28835. }
  28836. }
  28837. }
  28838. }
  28839. else {
  28840. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  28841. this._scene.mainSoundTrack.AddSound(this);
  28842. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  28843. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  28844. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  28845. }
  28846. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  28847. if (this._readyToPlayCallback) {
  28848. window.setTimeout(function () {
  28849. _this._readyToPlayCallback();
  28850. }, 1000);
  28851. }
  28852. }
  28853. }
  28854. Sound.prototype.dispose = function () {
  28855. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  28856. if (this.isPlaying) {
  28857. this.stop();
  28858. }
  28859. this._isReadyToPlay = false;
  28860. if (this.soundTrackId === -1) {
  28861. this._scene.mainSoundTrack.RemoveSound(this);
  28862. }
  28863. else {
  28864. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  28865. }
  28866. if (this._soundGain) {
  28867. this._soundGain.disconnect();
  28868. this._soundGain = null;
  28869. }
  28870. if (this._soundPanner) {
  28871. this._soundPanner.disconnect();
  28872. this._soundPanner = null;
  28873. }
  28874. if (this._soundSource) {
  28875. this._soundSource.disconnect();
  28876. this._soundSource = null;
  28877. }
  28878. this._audioBuffer = null;
  28879. if (this._connectedMesh) {
  28880. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  28881. this._connectedMesh = null;
  28882. }
  28883. }
  28884. };
  28885. Sound.prototype._soundLoaded = function (audioData) {
  28886. var _this = this;
  28887. this._isLoaded = true;
  28888. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  28889. _this._audioBuffer = buffer;
  28890. _this._isReadyToPlay = true;
  28891. if (_this.autoplay) {
  28892. _this.play();
  28893. }
  28894. if (_this._readyToPlayCallback) {
  28895. _this._readyToPlayCallback();
  28896. }
  28897. }, function (error) { BABYLON.Tools.Error("Error while decoding audio data: " + error.err); });
  28898. };
  28899. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  28900. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28901. this._audioBuffer = audioBuffer;
  28902. this._isReadyToPlay = true;
  28903. }
  28904. };
  28905. Sound.prototype.updateOptions = function (options) {
  28906. if (options) {
  28907. this.loop = options.loop || this.loop;
  28908. this.maxDistance = options.maxDistance || this.maxDistance;
  28909. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  28910. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  28911. this.refDistance = options.refDistance || this.refDistance;
  28912. this.distanceModel = options.distanceModel || this.distanceModel;
  28913. this._playbackRate = options.playbackRate || this._playbackRate;
  28914. this._updateSpatialParameters();
  28915. if (this.isPlaying) {
  28916. this._soundSource.playbackRate.value = this._playbackRate;
  28917. }
  28918. }
  28919. };
  28920. Sound.prototype._createSpatialParameters = function () {
  28921. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28922. if (this._scene.headphone) {
  28923. this._panningModel = "HRTF";
  28924. }
  28925. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  28926. this._updateSpatialParameters();
  28927. this._soundPanner.connect(this._ouputAudioNode);
  28928. this._inputAudioNode = this._soundPanner;
  28929. }
  28930. };
  28931. Sound.prototype._updateSpatialParameters = function () {
  28932. if (this.spatialSound) {
  28933. if (this.useCustomAttenuation) {
  28934. // Tricks to disable in a way embedded Web Audio attenuation
  28935. this._soundPanner.distanceModel = "linear";
  28936. this._soundPanner.maxDistance = Number.MAX_VALUE;
  28937. this._soundPanner.refDistance = 1;
  28938. this._soundPanner.rolloffFactor = 1;
  28939. this._soundPanner.panningModel = this._panningModel;
  28940. }
  28941. else {
  28942. this._soundPanner.distanceModel = this.distanceModel;
  28943. this._soundPanner.maxDistance = this.maxDistance;
  28944. this._soundPanner.refDistance = this.refDistance;
  28945. this._soundPanner.rolloffFactor = this.rolloffFactor;
  28946. this._soundPanner.panningModel = this._panningModel;
  28947. }
  28948. }
  28949. };
  28950. Sound.prototype.switchPanningModelToHRTF = function () {
  28951. this._panningModel = "HRTF";
  28952. this._switchPanningModel();
  28953. };
  28954. Sound.prototype.switchPanningModelToEqualPower = function () {
  28955. this._panningModel = "equalpower";
  28956. this._switchPanningModel();
  28957. };
  28958. Sound.prototype._switchPanningModel = function () {
  28959. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  28960. this._soundPanner.panningModel = this._panningModel;
  28961. }
  28962. };
  28963. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  28964. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28965. this._ouputAudioNode.disconnect();
  28966. this._ouputAudioNode.connect(soundTrackAudioNode);
  28967. }
  28968. };
  28969. /**
  28970. * Transform this sound into a directional source
  28971. * @param coneInnerAngle Size of the inner cone in degree
  28972. * @param coneOuterAngle Size of the outer cone in degree
  28973. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  28974. */
  28975. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  28976. if (coneOuterAngle < coneInnerAngle) {
  28977. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  28978. return;
  28979. }
  28980. this._coneInnerAngle = coneInnerAngle;
  28981. this._coneOuterAngle = coneOuterAngle;
  28982. this._coneOuterGain = coneOuterGain;
  28983. this._isDirectional = true;
  28984. if (this.isPlaying && this.loop) {
  28985. this.stop();
  28986. this.play();
  28987. }
  28988. };
  28989. Sound.prototype.setPosition = function (newPosition) {
  28990. this._position = newPosition;
  28991. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  28992. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  28993. }
  28994. };
  28995. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  28996. this._localDirection = newLocalDirection;
  28997. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  28998. this._updateDirection();
  28999. }
  29000. };
  29001. Sound.prototype._updateDirection = function () {
  29002. var mat = this._connectedMesh.getWorldMatrix();
  29003. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  29004. direction.normalize();
  29005. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  29006. };
  29007. Sound.prototype.updateDistanceFromListener = function () {
  29008. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  29009. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  29010. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  29011. }
  29012. };
  29013. Sound.prototype.setAttenuationFunction = function (callback) {
  29014. this._customAttenuationFunction = callback;
  29015. };
  29016. /**
  29017. * Play the sound
  29018. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  29019. */
  29020. Sound.prototype.play = function (time) {
  29021. var _this = this;
  29022. if (this._isReadyToPlay && this._scene.audioEnabled) {
  29023. try {
  29024. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  29025. if (!this._soundSource) {
  29026. if (this.spatialSound) {
  29027. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  29028. if (this._isDirectional) {
  29029. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  29030. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  29031. this._soundPanner.coneOuterGain = this._coneOuterGain;
  29032. if (this._connectedMesh) {
  29033. this._updateDirection();
  29034. }
  29035. else {
  29036. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  29037. }
  29038. }
  29039. }
  29040. }
  29041. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  29042. this._soundSource.buffer = this._audioBuffer;
  29043. this._soundSource.connect(this._inputAudioNode);
  29044. this._soundSource.loop = this.loop;
  29045. this._soundSource.playbackRate.value = this._playbackRate;
  29046. this._startTime = startTime;
  29047. this._soundSource.onended = function () { _this._onended(); };
  29048. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  29049. this.isPlaying = true;
  29050. this.isPaused = false;
  29051. }
  29052. catch (ex) {
  29053. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  29054. }
  29055. }
  29056. };
  29057. Sound.prototype._onended = function () {
  29058. this.isPlaying = false;
  29059. if (this.onended) {
  29060. this.onended();
  29061. }
  29062. };
  29063. /**
  29064. * Stop the sound
  29065. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  29066. */
  29067. Sound.prototype.stop = function (time) {
  29068. if (this.isPlaying) {
  29069. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  29070. this._soundSource.stop(stopTime);
  29071. this.isPlaying = false;
  29072. }
  29073. };
  29074. Sound.prototype.pause = function () {
  29075. if (this.isPlaying) {
  29076. this.stop(0);
  29077. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  29078. this.isPaused = true;
  29079. }
  29080. };
  29081. Sound.prototype.setVolume = function (newVolume, time) {
  29082. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29083. if (time) {
  29084. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  29085. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  29086. }
  29087. else {
  29088. this._soundGain.gain.value = newVolume;
  29089. }
  29090. }
  29091. this._volume = newVolume;
  29092. };
  29093. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  29094. this._playbackRate = newPlaybackRate;
  29095. if (this.isPlaying) {
  29096. this._soundSource.playbackRate.value = this._playbackRate;
  29097. }
  29098. };
  29099. Sound.prototype.getVolume = function () {
  29100. return this._volume;
  29101. };
  29102. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  29103. var _this = this;
  29104. this._connectedMesh = meshToConnectTo;
  29105. if (!this.spatialSound) {
  29106. this.spatialSound = true;
  29107. this._createSpatialParameters();
  29108. if (this.isPlaying && this.loop) {
  29109. this.stop();
  29110. this.play();
  29111. }
  29112. }
  29113. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  29114. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  29115. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  29116. };
  29117. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  29118. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  29119. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  29120. this._updateDirection();
  29121. }
  29122. };
  29123. return Sound;
  29124. })();
  29125. BABYLON.Sound = Sound;
  29126. })(BABYLON || (BABYLON = {}));
  29127. //# sourceMappingURL=babylon.sound.js.map
  29128. var BABYLON;
  29129. (function (BABYLON) {
  29130. var SoundTrack = (function () {
  29131. function SoundTrack(scene, options) {
  29132. this.id = -1;
  29133. this._isMainTrack = false;
  29134. this._scene = scene;
  29135. this._audioEngine = BABYLON.Engine.audioEngine;
  29136. this.soundCollection = new Array();
  29137. if (this._audioEngine.canUseWebAudio) {
  29138. this._outputAudioNode = this._audioEngine.audioContext.createGain();
  29139. this._outputAudioNode.connect(this._audioEngine.masterGain);
  29140. if (options) {
  29141. if (options.volume) {
  29142. this._outputAudioNode.gain.value = options.volume;
  29143. }
  29144. if (options.mainTrack) {
  29145. this._isMainTrack = options.mainTrack;
  29146. }
  29147. }
  29148. }
  29149. if (!this._isMainTrack) {
  29150. this._scene.soundTracks.push(this);
  29151. this.id = this._scene.soundTracks.length - 1;
  29152. }
  29153. }
  29154. SoundTrack.prototype.dispose = function () {
  29155. if (this._audioEngine.canUseWebAudio) {
  29156. if (this._connectedAnalyser) {
  29157. this._connectedAnalyser.stopDebugCanvas();
  29158. }
  29159. while (this.soundCollection.length) {
  29160. this.soundCollection[0].dispose();
  29161. }
  29162. this._outputAudioNode.disconnect();
  29163. this._outputAudioNode = null;
  29164. }
  29165. };
  29166. SoundTrack.prototype.AddSound = function (sound) {
  29167. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29168. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  29169. }
  29170. if (sound.soundTrackId) {
  29171. if (sound.soundTrackId === -1) {
  29172. this._scene.mainSoundTrack.RemoveSound(sound);
  29173. }
  29174. else {
  29175. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  29176. }
  29177. }
  29178. this.soundCollection.push(sound);
  29179. sound.soundTrackId = this.id;
  29180. };
  29181. SoundTrack.prototype.RemoveSound = function (sound) {
  29182. var index = this.soundCollection.indexOf(sound);
  29183. if (index !== -1) {
  29184. this.soundCollection.splice(index, 1);
  29185. }
  29186. };
  29187. SoundTrack.prototype.setVolume = function (newVolume) {
  29188. if (this._audioEngine.canUseWebAudio) {
  29189. this._outputAudioNode.gain.value = newVolume;
  29190. }
  29191. };
  29192. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  29193. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29194. for (var i = 0; i < this.soundCollection.length; i++) {
  29195. this.soundCollection[i].switchPanningModelToHRTF();
  29196. }
  29197. }
  29198. };
  29199. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  29200. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29201. for (var i = 0; i < this.soundCollection.length; i++) {
  29202. this.soundCollection[i].switchPanningModelToEqualPower();
  29203. }
  29204. }
  29205. };
  29206. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  29207. if (this._connectedAnalyser) {
  29208. this._connectedAnalyser.stopDebugCanvas();
  29209. }
  29210. this._connectedAnalyser = analyser;
  29211. if (this._audioEngine.canUseWebAudio) {
  29212. this._outputAudioNode.disconnect();
  29213. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, this._audioEngine.masterGain);
  29214. }
  29215. };
  29216. return SoundTrack;
  29217. })();
  29218. BABYLON.SoundTrack = SoundTrack;
  29219. })(BABYLON || (BABYLON = {}));
  29220. //# sourceMappingURL=babylon.soundtrack.js.map
  29221. var BABYLON;
  29222. (function (BABYLON) {
  29223. var DebugLayer = (function () {
  29224. function DebugLayer(scene) {
  29225. var _this = this;
  29226. this._transformationMatrix = BABYLON.Matrix.Identity();
  29227. this._enabled = false;
  29228. this._labelsEnabled = false;
  29229. this._displayStatistics = true;
  29230. this._displayTree = false;
  29231. this._displayLogs = false;
  29232. this._identityMatrix = BABYLON.Matrix.Identity();
  29233. this.axisRatio = 0.02;
  29234. this.accentColor = "orange";
  29235. this._scene = scene;
  29236. this._syncPositions = function () {
  29237. var engine = _this._scene.getEngine();
  29238. var canvasRect = engine.getRenderingCanvasClientRect();
  29239. if (_this._showUI) {
  29240. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  29241. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  29242. _this._statsDiv.style.width = "400px";
  29243. _this._statsDiv.style.height = "auto";
  29244. _this._statsSubsetDiv.style.maxHeight = "240px";
  29245. _this._optionsDiv.style.left = "0px";
  29246. _this._optionsDiv.style.top = "10px";
  29247. _this._optionsDiv.style.width = "200px";
  29248. _this._optionsDiv.style.height = "auto";
  29249. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  29250. _this._logDiv.style.left = "0px";
  29251. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  29252. _this._logDiv.style.width = "600px";
  29253. _this._logDiv.style.height = "160px";
  29254. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  29255. _this._treeDiv.style.top = "10px";
  29256. _this._treeDiv.style.width = "300px";
  29257. _this._treeDiv.style.height = "auto";
  29258. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  29259. }
  29260. _this._globalDiv.style.left = canvasRect.left + "px";
  29261. _this._globalDiv.style.top = canvasRect.top + "px";
  29262. _this._drawingCanvas.style.left = "0px";
  29263. _this._drawingCanvas.style.top = "0px";
  29264. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  29265. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  29266. var devicePixelRatio = window.devicePixelRatio || 1;
  29267. var context = _this._drawingContext;
  29268. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  29269. context.mozBackingStorePixelRatio ||
  29270. context.msBackingStorePixelRatio ||
  29271. context.oBackingStorePixelRatio ||
  29272. context.backingStorePixelRatio || 1;
  29273. _this._ratio = devicePixelRatio / backingStoreRatio;
  29274. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  29275. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  29276. };
  29277. this._onCanvasClick = function (evt) {
  29278. _this._clickPosition = {
  29279. x: evt.clientX * _this._ratio,
  29280. y: evt.clientY * _this._ratio
  29281. };
  29282. };
  29283. this._syncUI = function () {
  29284. if (_this._showUI) {
  29285. if (_this._displayStatistics) {
  29286. _this._displayStats();
  29287. _this._statsDiv.style.display = "";
  29288. }
  29289. else {
  29290. _this._statsDiv.style.display = "none";
  29291. }
  29292. if (_this._displayLogs) {
  29293. _this._logDiv.style.display = "";
  29294. }
  29295. else {
  29296. _this._logDiv.style.display = "none";
  29297. }
  29298. if (_this._displayTree) {
  29299. _this._treeDiv.style.display = "";
  29300. if (_this._needToRefreshMeshesTree) {
  29301. _this._needToRefreshMeshesTree = false;
  29302. _this._refreshMeshesTreeContent();
  29303. }
  29304. }
  29305. else {
  29306. _this._treeDiv.style.display = "none";
  29307. }
  29308. }
  29309. };
  29310. this._syncData = function () {
  29311. if (_this._labelsEnabled || !_this._showUI) {
  29312. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  29313. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  29314. var engine = _this._scene.getEngine();
  29315. var viewport = _this._camera.viewport;
  29316. var globalViewport = viewport.toGlobal(engine);
  29317. // Meshes
  29318. var meshes = _this._camera.getActiveMeshes();
  29319. for (var index = 0; index < meshes.length; index++) {
  29320. var mesh = meshes.data[index];
  29321. var position = mesh.getBoundingInfo().boundingSphere.center;
  29322. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29323. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  29324. _this._renderAxis(projectedPosition, mesh, globalViewport);
  29325. }
  29326. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  29327. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  29328. }
  29329. }
  29330. // Cameras
  29331. var cameras = _this._scene.cameras;
  29332. for (index = 0; index < cameras.length; index++) {
  29333. var camera = cameras[index];
  29334. if (camera === _this._camera) {
  29335. continue;
  29336. }
  29337. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  29338. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  29339. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  29340. _this._camera.detachControl(engine.getRenderingCanvas());
  29341. _this._camera = camera;
  29342. _this._camera.attachControl(engine.getRenderingCanvas());
  29343. }, function () { return "purple"; });
  29344. }
  29345. }
  29346. // Lights
  29347. var lights = _this._scene.lights;
  29348. for (index = 0; index < lights.length; index++) {
  29349. var light = lights[index];
  29350. if (light.position) {
  29351. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  29352. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  29353. _this._renderLabel(light.name, projectedPosition, -20, function () {
  29354. light.setEnabled(!light.isEnabled());
  29355. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  29356. }
  29357. }
  29358. }
  29359. }
  29360. _this._clickPosition = undefined;
  29361. };
  29362. }
  29363. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  29364. while (this._treeSubsetDiv.hasChildNodes()) {
  29365. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  29366. }
  29367. // Add meshes
  29368. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  29369. sortedArray.sort(function (a, b) {
  29370. if (a.name === b.name) {
  29371. return 0;
  29372. }
  29373. return (a.name > b.name) ? 1 : -1;
  29374. });
  29375. for (var index = 0; index < sortedArray.length; index++) {
  29376. var mesh = sortedArray[index];
  29377. if (!mesh.isEnabled()) {
  29378. continue;
  29379. }
  29380. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  29381. m.isVisible = element.checked;
  29382. }, mesh);
  29383. }
  29384. };
  29385. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  29386. this._drawingContext.beginPath();
  29387. this._drawingContext.moveTo(zero.x, zero.y);
  29388. this._drawingContext.lineTo(unit.x, unit.y);
  29389. this._drawingContext.strokeStyle = color;
  29390. this._drawingContext.lineWidth = 4;
  29391. this._drawingContext.stroke();
  29392. this._drawingContext.font = "normal 14px Segoe UI";
  29393. this._drawingContext.fillStyle = color;
  29394. this._drawingContext.fillText(label, unitText.x, unitText.y);
  29395. };
  29396. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  29397. var position = mesh.getBoundingInfo().boundingSphere.center;
  29398. var worldMatrix = mesh.getWorldMatrix();
  29399. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  29400. var unit = (unprojectedVector.subtract(position)).length();
  29401. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29402. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29403. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  29404. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29405. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  29406. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  29407. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  29408. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  29409. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  29410. };
  29411. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  29412. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  29413. this._drawingContext.font = "normal 12px Segoe UI";
  29414. var textMetrics = this._drawingContext.measureText(text);
  29415. var centerX = projectedPosition.x - textMetrics.width / 2;
  29416. var centerY = projectedPosition.y;
  29417. var clientRect = this._drawingCanvas.getBoundingClientRect();
  29418. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  29419. onClick();
  29420. }
  29421. this._drawingContext.beginPath();
  29422. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  29423. this._drawingContext.fillStyle = getFillStyle();
  29424. this._drawingContext.globalAlpha = 0.5;
  29425. this._drawingContext.fill();
  29426. this._drawingContext.globalAlpha = 1.0;
  29427. this._drawingContext.strokeStyle = '#FFFFFF';
  29428. this._drawingContext.lineWidth = 1;
  29429. this._drawingContext.stroke();
  29430. this._drawingContext.fillStyle = "#FFFFFF";
  29431. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  29432. this._drawingContext.beginPath();
  29433. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  29434. this._drawingContext.fill();
  29435. }
  29436. };
  29437. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  29438. if (!this._clickPosition) {
  29439. return false;
  29440. }
  29441. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  29442. return false;
  29443. }
  29444. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  29445. return false;
  29446. }
  29447. return true;
  29448. };
  29449. DebugLayer.prototype.isVisible = function () {
  29450. return this._enabled;
  29451. };
  29452. DebugLayer.prototype.hide = function () {
  29453. if (!this._enabled) {
  29454. return;
  29455. }
  29456. this._enabled = false;
  29457. var engine = this._scene.getEngine();
  29458. this._scene.unregisterBeforeRender(this._syncData);
  29459. this._scene.unregisterAfterRender(this._syncUI);
  29460. document.body.removeChild(this._globalDiv);
  29461. window.removeEventListener("resize", this._syncPositions);
  29462. this._scene.forceShowBoundingBoxes = false;
  29463. this._scene.forceWireframe = false;
  29464. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  29465. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  29466. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  29467. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  29468. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  29469. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  29470. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  29471. this._scene.shadowsEnabled = true;
  29472. this._scene.particlesEnabled = true;
  29473. this._scene.postProcessesEnabled = true;
  29474. this._scene.collisionsEnabled = true;
  29475. this._scene.lightsEnabled = true;
  29476. this._scene.texturesEnabled = true;
  29477. this._scene.lensFlaresEnabled = true;
  29478. this._scene.proceduralTexturesEnabled = true;
  29479. this._scene.renderTargetsEnabled = true;
  29480. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  29481. };
  29482. DebugLayer.prototype.show = function (showUI, camera) {
  29483. if (showUI === void 0) { showUI = true; }
  29484. if (camera === void 0) { camera = null; }
  29485. if (this._enabled) {
  29486. return;
  29487. }
  29488. this._enabled = true;
  29489. if (camera) {
  29490. this._camera = camera;
  29491. }
  29492. else {
  29493. this._camera = this._scene.activeCamera;
  29494. }
  29495. this._showUI = showUI;
  29496. var engine = this._scene.getEngine();
  29497. this._globalDiv = document.createElement("div");
  29498. document.body.appendChild(this._globalDiv);
  29499. this._generateDOMelements();
  29500. window.addEventListener("resize", this._syncPositions);
  29501. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  29502. this._syncPositions();
  29503. this._scene.registerBeforeRender(this._syncData);
  29504. this._scene.registerAfterRender(this._syncUI);
  29505. };
  29506. DebugLayer.prototype._clearLabels = function () {
  29507. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  29508. for (var index = 0; index < this._scene.meshes.length; index++) {
  29509. var mesh = this._scene.meshes[index];
  29510. mesh.renderOverlay = false;
  29511. }
  29512. };
  29513. DebugLayer.prototype._generateheader = function (root, text) {
  29514. var header = document.createElement("div");
  29515. header.innerHTML = text + "&nbsp;";
  29516. header.style.textAlign = "right";
  29517. header.style.width = "100%";
  29518. header.style.color = "white";
  29519. header.style.backgroundColor = "Black";
  29520. header.style.padding = "5px 5px 4px 0px";
  29521. header.style.marginLeft = "-5px";
  29522. header.style.fontWeight = "bold";
  29523. root.appendChild(header);
  29524. };
  29525. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  29526. var label = document.createElement("label");
  29527. label.innerHTML = title;
  29528. label.style.color = color;
  29529. root.appendChild(label);
  29530. root.appendChild(document.createElement("br"));
  29531. };
  29532. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  29533. if (tag === void 0) { tag = null; }
  29534. var label = document.createElement("label");
  29535. var boundingBoxesCheckbox = document.createElement("input");
  29536. boundingBoxesCheckbox.type = "checkbox";
  29537. boundingBoxesCheckbox.checked = initialState;
  29538. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  29539. task(evt.target, tag);
  29540. });
  29541. label.appendChild(boundingBoxesCheckbox);
  29542. var container = document.createElement("span");
  29543. var leftPart = document.createElement("span");
  29544. var rightPart = document.createElement("span");
  29545. rightPart.style.cssFloat = "right";
  29546. leftPart.innerHTML = leftTitle;
  29547. rightPart.innerHTML = rightTitle;
  29548. rightPart.style.fontSize = "12px";
  29549. rightPart.style.maxWidth = "200px";
  29550. container.appendChild(leftPart);
  29551. container.appendChild(rightPart);
  29552. label.appendChild(container);
  29553. root.appendChild(label);
  29554. root.appendChild(document.createElement("br"));
  29555. };
  29556. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  29557. if (tag === void 0) { tag = null; }
  29558. var label = document.createElement("label");
  29559. var checkBox = document.createElement("input");
  29560. checkBox.type = "checkbox";
  29561. checkBox.checked = initialState;
  29562. checkBox.addEventListener("change", function (evt) {
  29563. task(evt.target, tag);
  29564. });
  29565. label.appendChild(checkBox);
  29566. label.appendChild(document.createTextNode(title));
  29567. root.appendChild(label);
  29568. root.appendChild(document.createElement("br"));
  29569. };
  29570. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  29571. if (tag === void 0) { tag = null; }
  29572. var button = document.createElement("button");
  29573. button.innerHTML = title;
  29574. button.style.height = "24px";
  29575. button.style.color = "#444444";
  29576. button.style.border = "1px solid white";
  29577. button.className = "debugLayerButton";
  29578. button.addEventListener("click", function (evt) {
  29579. task(evt.target, tag);
  29580. });
  29581. root.appendChild(button);
  29582. root.appendChild(document.createElement("br"));
  29583. };
  29584. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  29585. if (tag === void 0) { tag = null; }
  29586. var label = document.createElement("label");
  29587. var boundingBoxesRadio = document.createElement("input");
  29588. boundingBoxesRadio.type = "radio";
  29589. boundingBoxesRadio.name = name;
  29590. boundingBoxesRadio.checked = initialState;
  29591. boundingBoxesRadio.addEventListener("change", function (evt) {
  29592. task(evt.target, tag);
  29593. });
  29594. label.appendChild(boundingBoxesRadio);
  29595. label.appendChild(document.createTextNode(title));
  29596. root.appendChild(label);
  29597. root.appendChild(document.createElement("br"));
  29598. };
  29599. DebugLayer.prototype._generateDOMelements = function () {
  29600. var _this = this;
  29601. this._globalDiv.id = "DebugLayer";
  29602. this._globalDiv.style.position = "absolute";
  29603. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  29604. this._globalDiv.style.fontSize = "14px";
  29605. this._globalDiv.style.color = "white";
  29606. // Drawing canvas
  29607. this._drawingCanvas = document.createElement("canvas");
  29608. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  29609. this._drawingCanvas.style.position = "absolute";
  29610. this._drawingCanvas.style.pointerEvents = "none";
  29611. this._drawingContext = this._drawingCanvas.getContext("2d");
  29612. this._globalDiv.appendChild(this._drawingCanvas);
  29613. if (this._showUI) {
  29614. var background = "rgba(128, 128, 128, 0.4)";
  29615. var border = "rgb(180, 180, 180) solid 1px";
  29616. // Stats
  29617. this._statsDiv = document.createElement("div");
  29618. this._statsDiv.id = "DebugLayerStats";
  29619. this._statsDiv.style.border = border;
  29620. this._statsDiv.style.position = "absolute";
  29621. this._statsDiv.style.background = background;
  29622. this._statsDiv.style.padding = "0px 0px 0px 5px";
  29623. this._generateheader(this._statsDiv, "STATISTICS");
  29624. this._statsSubsetDiv = document.createElement("div");
  29625. this._statsSubsetDiv.style.paddingTop = "5px";
  29626. this._statsSubsetDiv.style.paddingBottom = "5px";
  29627. this._statsSubsetDiv.style.overflowY = "auto";
  29628. this._statsDiv.appendChild(this._statsSubsetDiv);
  29629. // Tree
  29630. this._treeDiv = document.createElement("div");
  29631. this._treeDiv.id = "DebugLayerTree";
  29632. this._treeDiv.style.border = border;
  29633. this._treeDiv.style.position = "absolute";
  29634. this._treeDiv.style.background = background;
  29635. this._treeDiv.style.padding = "0px 0px 0px 5px";
  29636. this._treeDiv.style.display = "none";
  29637. this._generateheader(this._treeDiv, "MESHES TREE");
  29638. this._treeSubsetDiv = document.createElement("div");
  29639. this._treeSubsetDiv.style.paddingTop = "5px";
  29640. this._treeSubsetDiv.style.paddingRight = "5px";
  29641. this._treeSubsetDiv.style.overflowY = "auto";
  29642. this._treeSubsetDiv.style.maxHeight = "300px";
  29643. this._treeDiv.appendChild(this._treeSubsetDiv);
  29644. this._needToRefreshMeshesTree = true;
  29645. // Logs
  29646. this._logDiv = document.createElement("div");
  29647. this._logDiv.style.border = border;
  29648. this._logDiv.id = "DebugLayerLogs";
  29649. this._logDiv.style.position = "absolute";
  29650. this._logDiv.style.background = background;
  29651. this._logDiv.style.padding = "0px 0px 0px 5px";
  29652. this._logDiv.style.display = "none";
  29653. this._generateheader(this._logDiv, "LOGS");
  29654. this._logSubsetDiv = document.createElement("div");
  29655. this._logSubsetDiv.style.height = "127px";
  29656. this._logSubsetDiv.style.paddingTop = "5px";
  29657. this._logSubsetDiv.style.overflowY = "auto";
  29658. this._logSubsetDiv.style.fontSize = "12px";
  29659. this._logSubsetDiv.style.fontFamily = "consolas";
  29660. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  29661. this._logDiv.appendChild(this._logSubsetDiv);
  29662. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  29663. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  29664. };
  29665. // Options
  29666. this._optionsDiv = document.createElement("div");
  29667. this._optionsDiv.id = "DebugLayerOptions";
  29668. this._optionsDiv.style.border = border;
  29669. this._optionsDiv.style.position = "absolute";
  29670. this._optionsDiv.style.background = background;
  29671. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  29672. this._optionsDiv.style.overflowY = "auto";
  29673. this._generateheader(this._optionsDiv, "OPTIONS");
  29674. this._optionsSubsetDiv = document.createElement("div");
  29675. this._optionsSubsetDiv.style.paddingTop = "5px";
  29676. this._optionsSubsetDiv.style.paddingBottom = "5px";
  29677. this._optionsSubsetDiv.style.overflowY = "auto";
  29678. this._optionsSubsetDiv.style.maxHeight = "200px";
  29679. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  29680. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  29681. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  29682. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  29683. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  29684. _this._displayTree = element.checked;
  29685. _this._needToRefreshMeshesTree = true;
  29686. });
  29687. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29688. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  29689. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  29690. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  29691. _this._labelsEnabled = element.checked;
  29692. if (!_this._labelsEnabled) {
  29693. _this._clearLabels();
  29694. }
  29695. });
  29696. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  29697. if (element.checked) {
  29698. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  29699. }
  29700. else {
  29701. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  29702. }
  29703. });
  29704. ;
  29705. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29706. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  29707. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  29708. if (element.checked) {
  29709. _this._scene.forceWireframe = false;
  29710. _this._scene.forcePointsCloud = false;
  29711. }
  29712. });
  29713. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  29714. if (element.checked) {
  29715. _this._scene.forceWireframe = true;
  29716. _this._scene.forcePointsCloud = false;
  29717. }
  29718. });
  29719. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  29720. if (element.checked) {
  29721. _this._scene.forceWireframe = false;
  29722. _this._scene.forcePointsCloud = true;
  29723. }
  29724. });
  29725. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29726. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  29727. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  29728. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  29729. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  29730. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  29731. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  29732. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  29733. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  29734. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  29735. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29736. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  29737. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  29738. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  29739. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  29740. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  29741. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  29742. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  29743. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  29744. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  29745. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  29746. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  29747. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  29748. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  29749. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  29750. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  29751. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29752. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  29753. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  29754. if (element.checked) {
  29755. _this._scene.headphone = true;
  29756. }
  29757. });
  29758. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  29759. if (element.checked) {
  29760. _this._scene.headphone = false;
  29761. }
  29762. });
  29763. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  29764. _this._scene.audioEnabled = !element.checked;
  29765. });
  29766. }
  29767. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29768. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  29769. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  29770. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  29771. this._globalDiv.appendChild(this._statsDiv);
  29772. this._globalDiv.appendChild(this._logDiv);
  29773. this._globalDiv.appendChild(this._optionsDiv);
  29774. this._globalDiv.appendChild(this._treeDiv);
  29775. }
  29776. };
  29777. DebugLayer.prototype._displayStats = function () {
  29778. var scene = this._scene;
  29779. var engine = scene.getEngine();
  29780. var glInfo = engine.getGlInfo();
  29781. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  29782. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29783. + "<b>Count</b><br>"
  29784. + "Total meshes: " + scene.meshes.length + "<br>"
  29785. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  29786. + "Total materials: " + scene.materials.length + "<br>"
  29787. + "Total textures: " + scene.textures.length + "<br>"
  29788. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  29789. + "Active indices: " + scene.getActiveIndices() + "<br>"
  29790. + "Active bones: " + scene.getActiveBones() + "<br>"
  29791. + "Active particles: " + scene.getActiveParticles() + "<br>"
  29792. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  29793. + "<b>Duration</b><br>"
  29794. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  29795. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  29796. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  29797. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  29798. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  29799. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  29800. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>"
  29801. + "</div>"
  29802. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  29803. + "<b>Extensions</b><br>"
  29804. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  29805. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  29806. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  29807. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>"
  29808. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  29809. + "<b>Caps.</b><br>"
  29810. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  29811. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  29812. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>"
  29813. + "</div><br>"
  29814. + "<b>Info</b><br>"
  29815. + glInfo.version + "<br>"
  29816. + glInfo.renderer + "<br>";
  29817. if (this.customStatsFunction) {
  29818. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  29819. }
  29820. };
  29821. return DebugLayer;
  29822. })();
  29823. BABYLON.DebugLayer = DebugLayer;
  29824. })(BABYLON || (BABYLON = {}));
  29825. //# sourceMappingURL=babylon.debugLayer.js.map
  29826. var BABYLON;
  29827. (function (BABYLON) {
  29828. var RawTexture = (function (_super) {
  29829. __extends(RawTexture, _super);
  29830. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  29831. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29832. if (invertY === void 0) { invertY = false; }
  29833. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29834. _super.call(this, null, scene, !generateMipMaps, invertY);
  29835. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  29836. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29837. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29838. }
  29839. // Statics
  29840. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29841. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29842. if (invertY === void 0) { invertY = false; }
  29843. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29844. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  29845. };
  29846. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29847. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29848. if (invertY === void 0) { invertY = false; }
  29849. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29850. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  29851. };
  29852. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29853. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29854. if (invertY === void 0) { invertY = false; }
  29855. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29856. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  29857. };
  29858. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29859. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29860. if (invertY === void 0) { invertY = false; }
  29861. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29862. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  29863. };
  29864. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  29865. if (generateMipMaps === void 0) { generateMipMaps = true; }
  29866. if (invertY === void 0) { invertY = false; }
  29867. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29868. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  29869. };
  29870. return RawTexture;
  29871. })(BABYLON.Texture);
  29872. BABYLON.RawTexture = RawTexture;
  29873. })(BABYLON || (BABYLON = {}));
  29874. //# sourceMappingURL=babylon.rawTexture.js.map
  29875. var BABYLON;
  29876. (function (BABYLON) {
  29877. var IndexedVector2 = (function (_super) {
  29878. __extends(IndexedVector2, _super);
  29879. function IndexedVector2(original, index) {
  29880. _super.call(this, original.x, original.y);
  29881. this.index = index;
  29882. }
  29883. return IndexedVector2;
  29884. })(BABYLON.Vector2);
  29885. var PolygonPoints = (function () {
  29886. function PolygonPoints() {
  29887. this.elements = new Array();
  29888. }
  29889. PolygonPoints.prototype.add = function (originalPoints) {
  29890. var _this = this;
  29891. var result = new Array();
  29892. originalPoints.forEach(function (point) {
  29893. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  29894. var newPoint = new IndexedVector2(point, _this.elements.length);
  29895. result.push(newPoint);
  29896. _this.elements.push(newPoint);
  29897. }
  29898. });
  29899. return result;
  29900. };
  29901. PolygonPoints.prototype.computeBounds = function () {
  29902. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  29903. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  29904. this.elements.forEach(function (point) {
  29905. // x
  29906. if (point.x < lmin.x) {
  29907. lmin.x = point.x;
  29908. }
  29909. else if (point.x > lmax.x) {
  29910. lmax.x = point.x;
  29911. }
  29912. // y
  29913. if (point.y < lmin.y) {
  29914. lmin.y = point.y;
  29915. }
  29916. else if (point.y > lmax.y) {
  29917. lmax.y = point.y;
  29918. }
  29919. });
  29920. return {
  29921. min: lmin,
  29922. max: lmax,
  29923. width: lmax.x - lmin.x,
  29924. height: lmax.y - lmin.y
  29925. };
  29926. };
  29927. return PolygonPoints;
  29928. })();
  29929. var Polygon = (function () {
  29930. function Polygon() {
  29931. }
  29932. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  29933. return [
  29934. new BABYLON.Vector2(xmin, ymin),
  29935. new BABYLON.Vector2(xmax, ymin),
  29936. new BABYLON.Vector2(xmax, ymax),
  29937. new BABYLON.Vector2(xmin, ymax)
  29938. ];
  29939. };
  29940. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  29941. if (cx === void 0) { cx = 0; }
  29942. if (cy === void 0) { cy = 0; }
  29943. if (numberOfSides === void 0) { numberOfSides = 32; }
  29944. var result = new Array();
  29945. var angle = 0;
  29946. var increment = (Math.PI * 2) / numberOfSides;
  29947. for (var i = 0; i < numberOfSides; i++) {
  29948. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  29949. angle -= increment;
  29950. }
  29951. return result;
  29952. };
  29953. Polygon.Parse = function (input) {
  29954. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  29955. var i, result = [];
  29956. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  29957. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  29958. }
  29959. return result;
  29960. };
  29961. Polygon.StartingAt = function (x, y) {
  29962. return BABYLON.Path2.StartingAt(x, y);
  29963. };
  29964. return Polygon;
  29965. })();
  29966. BABYLON.Polygon = Polygon;
  29967. var PolygonMeshBuilder = (function () {
  29968. function PolygonMeshBuilder(name, contours, scene) {
  29969. this._points = new PolygonPoints();
  29970. this._outlinepoints = new PolygonPoints();
  29971. this._holes = [];
  29972. if (!("poly2tri" in window)) {
  29973. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  29974. }
  29975. this._name = name;
  29976. this._scene = scene;
  29977. var points;
  29978. if (contours instanceof BABYLON.Path2) {
  29979. points = contours.getPoints();
  29980. }
  29981. else {
  29982. points = contours;
  29983. }
  29984. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  29985. this._outlinepoints.add(points);
  29986. }
  29987. PolygonMeshBuilder.prototype.addHole = function (hole) {
  29988. this._swctx.addHole(this._points.add(hole));
  29989. var holepoints = new PolygonPoints();
  29990. holepoints.add(hole);
  29991. this._holes.push(holepoints);
  29992. return this;
  29993. };
  29994. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  29995. var _this = this;
  29996. if (updatable === void 0) { updatable = false; }
  29997. var result = new BABYLON.Mesh(this._name, this._scene);
  29998. var normals = [];
  29999. var positions = [];
  30000. var uvs = [];
  30001. var bounds = this._points.computeBounds();
  30002. this._points.elements.forEach(function (p) {
  30003. normals.push(0, 1.0, 0);
  30004. positions.push(p.x, 0, p.y);
  30005. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  30006. });
  30007. var indices = [];
  30008. this._swctx.triangulate();
  30009. this._swctx.getTriangles().forEach(function (triangle) {
  30010. triangle.getPoints().forEach(function (point) {
  30011. indices.push(point.index);
  30012. });
  30013. });
  30014. if (depth > 0) {
  30015. var positionscount = (positions.length / 3); //get the current pointcount
  30016. this._points.elements.forEach(function (p) {
  30017. normals.push(0, -1.0, 0);
  30018. positions.push(p.x, -depth, p.y);
  30019. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  30020. });
  30021. var p1; //we need to change order of point so the triangles are made in the rigth way.
  30022. var p2;
  30023. var poscounter = 0;
  30024. this._swctx.getTriangles().forEach(function (triangle) {
  30025. triangle.getPoints().forEach(function (point) {
  30026. switch (poscounter) {
  30027. case 0:
  30028. p1 = point;
  30029. break;
  30030. case 1:
  30031. p2 = point;
  30032. break;
  30033. case 2:
  30034. indices.push(point.index + positionscount);
  30035. indices.push(p2.index + positionscount);
  30036. indices.push(p1.index + positionscount);
  30037. poscounter = -1;
  30038. break;
  30039. }
  30040. poscounter++;
  30041. //indices.push((<IndexedVector2>point).index + positionscount);
  30042. });
  30043. });
  30044. //Add the sides
  30045. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  30046. this._holes.forEach(function (hole) {
  30047. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  30048. });
  30049. }
  30050. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  30051. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  30052. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  30053. result.setIndices(indices);
  30054. return result;
  30055. };
  30056. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  30057. var StartIndex = positions.length / 3;
  30058. var ulength = 0;
  30059. for (var i = 0; i < points.elements.length; i++) {
  30060. var p = points.elements[i];
  30061. var p1;
  30062. if ((i + 1) > points.elements.length - 1) {
  30063. p1 = points.elements[0];
  30064. }
  30065. else {
  30066. p1 = points.elements[i + 1];
  30067. }
  30068. positions.push(p.x, 0, p.y);
  30069. positions.push(p.x, -depth, p.y);
  30070. positions.push(p1.x, 0, p1.y);
  30071. positions.push(p1.x, -depth, p1.y);
  30072. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  30073. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  30074. var v3 = v2.subtract(v1);
  30075. var v4 = new BABYLON.Vector3(0, 1, 0);
  30076. var vn = BABYLON.Vector3.Cross(v3, v4);
  30077. vn = vn.normalize();
  30078. uvs.push(ulength / bounds.width, 0);
  30079. uvs.push(ulength / bounds.width, 1);
  30080. ulength += v3.length();
  30081. uvs.push((ulength / bounds.width), 0);
  30082. uvs.push((ulength / bounds.width), 1);
  30083. if (!flip) {
  30084. normals.push(-vn.x, -vn.y, -vn.z);
  30085. normals.push(-vn.x, -vn.y, -vn.z);
  30086. normals.push(-vn.x, -vn.y, -vn.z);
  30087. normals.push(-vn.x, -vn.y, -vn.z);
  30088. indices.push(StartIndex);
  30089. indices.push(StartIndex + 1);
  30090. indices.push(StartIndex + 2);
  30091. indices.push(StartIndex + 1);
  30092. indices.push(StartIndex + 3);
  30093. indices.push(StartIndex + 2);
  30094. }
  30095. else {
  30096. normals.push(vn.x, vn.y, vn.z);
  30097. normals.push(vn.x, vn.y, vn.z);
  30098. normals.push(vn.x, vn.y, vn.z);
  30099. normals.push(vn.x, vn.y, vn.z);
  30100. indices.push(StartIndex);
  30101. indices.push(StartIndex + 2);
  30102. indices.push(StartIndex + 1);
  30103. indices.push(StartIndex + 1);
  30104. indices.push(StartIndex + 2);
  30105. indices.push(StartIndex + 3);
  30106. }
  30107. StartIndex += 4;
  30108. }
  30109. ;
  30110. };
  30111. return PolygonMeshBuilder;
  30112. })();
  30113. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  30114. })(BABYLON || (BABYLON = {}));
  30115. //# sourceMappingURL=babylon.polygonMesh.js.map
  30116. var BABYLON;
  30117. (function (BABYLON) {
  30118. var SimplificationSettings = (function () {
  30119. function SimplificationSettings(quality, distance, optimizeMesh) {
  30120. this.quality = quality;
  30121. this.distance = distance;
  30122. this.optimizeMesh = optimizeMesh;
  30123. }
  30124. return SimplificationSettings;
  30125. })();
  30126. BABYLON.SimplificationSettings = SimplificationSettings;
  30127. var SimplificationQueue = (function () {
  30128. function SimplificationQueue() {
  30129. this.running = false;
  30130. this._simplificationArray = [];
  30131. }
  30132. SimplificationQueue.prototype.addTask = function (task) {
  30133. this._simplificationArray.push(task);
  30134. };
  30135. SimplificationQueue.prototype.executeNext = function () {
  30136. var task = this._simplificationArray.pop();
  30137. if (task) {
  30138. this.running = true;
  30139. this.runSimplification(task);
  30140. }
  30141. else {
  30142. this.running = false;
  30143. }
  30144. };
  30145. SimplificationQueue.prototype.runSimplification = function (task) {
  30146. var _this = this;
  30147. if (task.parallelProcessing) {
  30148. //parallel simplifier
  30149. task.settings.forEach(function (setting) {
  30150. var simplifier = _this.getSimplifier(task);
  30151. simplifier.simplify(setting, function (newMesh) {
  30152. task.mesh.addLODLevel(setting.distance, newMesh);
  30153. newMesh.isVisible = true;
  30154. //check if it is the last
  30155. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  30156. //all done, run the success callback.
  30157. task.successCallback();
  30158. }
  30159. _this.executeNext();
  30160. });
  30161. });
  30162. }
  30163. else {
  30164. //single simplifier.
  30165. var simplifier = this.getSimplifier(task);
  30166. var runDecimation = function (setting, callback) {
  30167. simplifier.simplify(setting, function (newMesh) {
  30168. task.mesh.addLODLevel(setting.distance, newMesh);
  30169. newMesh.isVisible = true;
  30170. //run the next quality level
  30171. callback();
  30172. });
  30173. };
  30174. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  30175. runDecimation(task.settings[loop.index], function () {
  30176. loop.executeNext();
  30177. });
  30178. }, function () {
  30179. //execution ended, run the success callback.
  30180. if (task.successCallback) {
  30181. task.successCallback();
  30182. }
  30183. _this.executeNext();
  30184. });
  30185. }
  30186. };
  30187. SimplificationQueue.prototype.getSimplifier = function (task) {
  30188. switch (task.simplificationType) {
  30189. case SimplificationType.QUADRATIC:
  30190. default:
  30191. return new QuadraticErrorSimplification(task.mesh);
  30192. }
  30193. };
  30194. return SimplificationQueue;
  30195. })();
  30196. BABYLON.SimplificationQueue = SimplificationQueue;
  30197. /**
  30198. * The implemented types of simplification.
  30199. * At the moment only Quadratic Error Decimation is implemented.
  30200. */
  30201. (function (SimplificationType) {
  30202. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  30203. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  30204. var SimplificationType = BABYLON.SimplificationType;
  30205. var DecimationTriangle = (function () {
  30206. function DecimationTriangle(vertices) {
  30207. this.vertices = vertices;
  30208. this.error = new Array(4);
  30209. this.deleted = false;
  30210. this.isDirty = false;
  30211. this.deletePending = false;
  30212. this.borderFactor = 0;
  30213. }
  30214. return DecimationTriangle;
  30215. })();
  30216. BABYLON.DecimationTriangle = DecimationTriangle;
  30217. var DecimationVertex = (function () {
  30218. function DecimationVertex(position, id) {
  30219. this.position = position;
  30220. this.id = id;
  30221. this.isBorder = true;
  30222. this.q = new QuadraticMatrix();
  30223. this.triangleCount = 0;
  30224. this.triangleStart = 0;
  30225. this.originalOffsets = [];
  30226. }
  30227. DecimationVertex.prototype.updatePosition = function (newPosition) {
  30228. this.position.copyFrom(newPosition);
  30229. };
  30230. return DecimationVertex;
  30231. })();
  30232. BABYLON.DecimationVertex = DecimationVertex;
  30233. var QuadraticMatrix = (function () {
  30234. function QuadraticMatrix(data) {
  30235. this.data = new Array(10);
  30236. for (var i = 0; i < 10; ++i) {
  30237. if (data && data[i]) {
  30238. this.data[i] = data[i];
  30239. }
  30240. else {
  30241. this.data[i] = 0;
  30242. }
  30243. }
  30244. }
  30245. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  30246. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  30247. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  30248. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  30249. return det;
  30250. };
  30251. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  30252. for (var i = 0; i < 10; ++i) {
  30253. this.data[i] += matrix.data[i];
  30254. }
  30255. };
  30256. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  30257. for (var i = 0; i < 10; ++i) {
  30258. this.data[i] += data[i];
  30259. }
  30260. };
  30261. QuadraticMatrix.prototype.add = function (matrix) {
  30262. var m = new QuadraticMatrix();
  30263. for (var i = 0; i < 10; ++i) {
  30264. m.data[i] = this.data[i] + matrix.data[i];
  30265. }
  30266. return m;
  30267. };
  30268. QuadraticMatrix.FromData = function (a, b, c, d) {
  30269. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  30270. };
  30271. //returning an array to avoid garbage collection
  30272. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  30273. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  30274. };
  30275. return QuadraticMatrix;
  30276. })();
  30277. BABYLON.QuadraticMatrix = QuadraticMatrix;
  30278. var Reference = (function () {
  30279. function Reference(vertexId, triangleId) {
  30280. this.vertexId = vertexId;
  30281. this.triangleId = triangleId;
  30282. }
  30283. return Reference;
  30284. })();
  30285. BABYLON.Reference = Reference;
  30286. /**
  30287. * An implementation of the Quadratic Error simplification algorithm.
  30288. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  30289. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  30290. * @author RaananW
  30291. */
  30292. var QuadraticErrorSimplification = (function () {
  30293. function QuadraticErrorSimplification(_mesh) {
  30294. this._mesh = _mesh;
  30295. this.initialized = false;
  30296. this.syncIterations = 5000;
  30297. this.aggressiveness = 7;
  30298. this.decimationIterations = 100;
  30299. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  30300. }
  30301. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  30302. var _this = this;
  30303. this.initDecimatedMesh();
  30304. //iterating through the submeshes array, one after the other.
  30305. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  30306. _this.initWithMesh(loop.index, function () {
  30307. _this.runDecimation(settings, loop.index, function () {
  30308. loop.executeNext();
  30309. });
  30310. }, settings.optimizeMesh);
  30311. }, function () {
  30312. setTimeout(function () {
  30313. successCallback(_this._reconstructedMesh);
  30314. }, 0);
  30315. });
  30316. };
  30317. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  30318. var _this = this;
  30319. var gCount = 0;
  30320. triangle.vertices.forEach(function (vertex) {
  30321. var count = 0;
  30322. var vPos = vertex.position;
  30323. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  30324. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  30325. ++count;
  30326. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  30327. ++count;
  30328. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  30329. ++count;
  30330. if (count > 1) {
  30331. ++gCount;
  30332. }
  30333. ;
  30334. });
  30335. if (gCount > 1) {
  30336. console.log(triangle, gCount);
  30337. }
  30338. return gCount > 1;
  30339. };
  30340. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  30341. var _this = this;
  30342. var targetCount = ~~(this.triangles.length * settings.quality);
  30343. var deletedTriangles = 0;
  30344. var triangleCount = this.triangles.length;
  30345. var iterationFunction = function (iteration, callback) {
  30346. setTimeout(function () {
  30347. if (iteration % 5 === 0) {
  30348. _this.updateMesh(iteration === 0);
  30349. }
  30350. for (var i = 0; i < _this.triangles.length; ++i) {
  30351. _this.triangles[i].isDirty = false;
  30352. }
  30353. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  30354. var trianglesIterator = function (i) {
  30355. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  30356. var t = _this.triangles[tIdx];
  30357. if (!t)
  30358. return;
  30359. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  30360. return;
  30361. }
  30362. for (var j = 0; j < 3; ++j) {
  30363. if (t.error[j] < threshold) {
  30364. var deleted0 = [];
  30365. var deleted1 = [];
  30366. var v0 = t.vertices[j];
  30367. var v1 = t.vertices[(j + 1) % 3];
  30368. if (v0.isBorder !== v1.isBorder)
  30369. continue;
  30370. var p = BABYLON.Vector3.Zero();
  30371. var n = BABYLON.Vector3.Zero();
  30372. var uv = BABYLON.Vector2.Zero();
  30373. var color = new BABYLON.Color4(0, 0, 0, 1);
  30374. _this.calculateError(v0, v1, p, n, uv, color);
  30375. var delTr = [];
  30376. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  30377. continue;
  30378. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  30379. continue;
  30380. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  30381. continue;
  30382. var uniqueArray = [];
  30383. delTr.forEach(function (deletedT) {
  30384. if (uniqueArray.indexOf(deletedT) === -1) {
  30385. deletedT.deletePending = true;
  30386. uniqueArray.push(deletedT);
  30387. }
  30388. });
  30389. if (uniqueArray.length % 2 != 0) {
  30390. continue;
  30391. }
  30392. v0.q = v1.q.add(v0.q);
  30393. v0.updatePosition(p);
  30394. var tStart = _this.references.length;
  30395. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  30396. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  30397. var tCount = _this.references.length - tStart;
  30398. if (tCount <= v0.triangleCount) {
  30399. if (tCount) {
  30400. for (var c = 0; c < tCount; c++) {
  30401. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  30402. }
  30403. }
  30404. }
  30405. else {
  30406. v0.triangleStart = tStart;
  30407. }
  30408. v0.triangleCount = tCount;
  30409. break;
  30410. }
  30411. }
  30412. };
  30413. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  30414. }, 0);
  30415. };
  30416. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  30417. if (triangleCount - deletedTriangles <= targetCount)
  30418. loop.breakLoop();
  30419. else {
  30420. iterationFunction(loop.index, function () {
  30421. loop.executeNext();
  30422. });
  30423. }
  30424. }, function () {
  30425. setTimeout(function () {
  30426. //reconstruct this part of the mesh
  30427. _this.reconstructMesh(submeshIndex);
  30428. successCallback();
  30429. }, 0);
  30430. });
  30431. };
  30432. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  30433. var _this = this;
  30434. this.vertices = [];
  30435. this.triangles = [];
  30436. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30437. var indices = this._mesh.getIndices();
  30438. var submesh = this._mesh.subMeshes[submeshIndex];
  30439. var findInVertices = function (positionToSearch) {
  30440. if (optimizeMesh) {
  30441. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  30442. if (_this.vertices[ii].position.equals(positionToSearch)) {
  30443. return _this.vertices[ii];
  30444. }
  30445. }
  30446. }
  30447. return null;
  30448. };
  30449. var vertexReferences = [];
  30450. var vertexInit = function (i) {
  30451. var offset = i + submesh.verticesStart;
  30452. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  30453. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  30454. vertex.originalOffsets.push(offset);
  30455. if (vertex.id == _this.vertices.length) {
  30456. _this.vertices.push(vertex);
  30457. }
  30458. vertexReferences.push(vertex.id);
  30459. };
  30460. //var totalVertices = mesh.getTotalVertices();
  30461. var totalVertices = submesh.verticesCount;
  30462. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  30463. var indicesInit = function (i) {
  30464. var offset = (submesh.indexStart / 3) + i;
  30465. var pos = (offset * 3);
  30466. var i0 = indices[pos + 0];
  30467. var i1 = indices[pos + 1];
  30468. var i2 = indices[pos + 2];
  30469. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  30470. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  30471. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  30472. var triangle = new DecimationTriangle([v0, v1, v2]);
  30473. triangle.originalOffset = pos;
  30474. _this.triangles.push(triangle);
  30475. };
  30476. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  30477. _this.init(callback);
  30478. });
  30479. });
  30480. };
  30481. QuadraticErrorSimplification.prototype.init = function (callback) {
  30482. var _this = this;
  30483. var triangleInit1 = function (i) {
  30484. var t = _this.triangles[i];
  30485. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  30486. for (var j = 0; j < 3; j++) {
  30487. 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))));
  30488. }
  30489. };
  30490. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  30491. var triangleInit2 = function (i) {
  30492. var t = _this.triangles[i];
  30493. for (var j = 0; j < 3; ++j) {
  30494. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  30495. }
  30496. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30497. };
  30498. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  30499. _this.initialized = true;
  30500. callback();
  30501. });
  30502. });
  30503. };
  30504. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  30505. var newTriangles = [];
  30506. var i;
  30507. for (i = 0; i < this.vertices.length; ++i) {
  30508. this.vertices[i].triangleCount = 0;
  30509. }
  30510. var t;
  30511. var j;
  30512. for (i = 0; i < this.triangles.length; ++i) {
  30513. if (!this.triangles[i].deleted) {
  30514. t = this.triangles[i];
  30515. for (j = 0; j < 3; ++j) {
  30516. t.vertices[j].triangleCount = 1;
  30517. }
  30518. newTriangles.push(t);
  30519. }
  30520. }
  30521. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  30522. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  30523. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  30524. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  30525. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30526. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  30527. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  30528. var vertexCount = 0;
  30529. for (i = 0; i < this.vertices.length; ++i) {
  30530. var vertex = this.vertices[i];
  30531. vertex.id = vertexCount;
  30532. if (vertex.triangleCount) {
  30533. vertex.originalOffsets.forEach(function (originalOffset) {
  30534. newPositionData.push(vertex.position.x);
  30535. newPositionData.push(vertex.position.y);
  30536. newPositionData.push(vertex.position.z);
  30537. newNormalData.push(normalData[originalOffset * 3]);
  30538. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  30539. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  30540. if (uvs && uvs.length) {
  30541. newUVsData.push(uvs[(originalOffset * 2)]);
  30542. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  30543. }
  30544. else if (colorsData && colorsData.length) {
  30545. newColorsData.push(colorsData[(originalOffset * 4)]);
  30546. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  30547. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  30548. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  30549. }
  30550. ++vertexCount;
  30551. });
  30552. }
  30553. }
  30554. var startingIndex = this._reconstructedMesh.getTotalIndices();
  30555. var startingVertex = this._reconstructedMesh.getTotalVertices();
  30556. var submeshesArray = this._reconstructedMesh.subMeshes;
  30557. this._reconstructedMesh.subMeshes = [];
  30558. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  30559. var originalIndices = this._mesh.getIndices();
  30560. for (i = 0; i < newTriangles.length; ++i) {
  30561. var t = newTriangles[i];
  30562. //now get the new referencing point for each vertex
  30563. [0, 1, 2].forEach(function (idx) {
  30564. var id = originalIndices[t.originalOffset + idx];
  30565. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  30566. if (offset < 0)
  30567. offset = 0;
  30568. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  30569. });
  30570. }
  30571. //overwriting the old vertex buffers and indices.
  30572. this._reconstructedMesh.setIndices(newIndicesArray);
  30573. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  30574. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  30575. if (newUVsData.length > 0)
  30576. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  30577. if (newColorsData.length > 0)
  30578. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  30579. //create submesh
  30580. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  30581. if (submeshIndex > 0) {
  30582. this._reconstructedMesh.subMeshes = [];
  30583. submeshesArray.forEach(function (submesh) {
  30584. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  30585. });
  30586. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  30587. }
  30588. };
  30589. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  30590. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  30591. this._reconstructedMesh.material = this._mesh.material;
  30592. this._reconstructedMesh.parent = this._mesh.parent;
  30593. this._reconstructedMesh.isVisible = false;
  30594. };
  30595. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  30596. for (var i = 0; i < vertex1.triangleCount; ++i) {
  30597. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  30598. if (t.deleted)
  30599. continue;
  30600. var s = this.references[vertex1.triangleStart + i].vertexId;
  30601. var v1 = t.vertices[(s + 1) % 3];
  30602. var v2 = t.vertices[(s + 2) % 3];
  30603. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  30604. deletedArray[i] = true;
  30605. delTr.push(t);
  30606. continue;
  30607. }
  30608. var d1 = v1.position.subtract(point);
  30609. d1 = d1.normalize();
  30610. var d2 = v2.position.subtract(point);
  30611. d2 = d2.normalize();
  30612. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  30613. return true;
  30614. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  30615. deletedArray[i] = false;
  30616. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  30617. return true;
  30618. }
  30619. return false;
  30620. };
  30621. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  30622. var newDeleted = deletedTriangles;
  30623. for (var i = 0; i < vertex.triangleCount; ++i) {
  30624. var ref = this.references[vertex.triangleStart + i];
  30625. var t = this.triangles[ref.triangleId];
  30626. if (t.deleted)
  30627. continue;
  30628. if (deletedArray[i] && t.deletePending) {
  30629. t.deleted = true;
  30630. newDeleted++;
  30631. continue;
  30632. }
  30633. t.vertices[ref.vertexId] = origVertex;
  30634. t.isDirty = true;
  30635. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  30636. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  30637. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  30638. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  30639. this.references.push(ref);
  30640. }
  30641. return newDeleted;
  30642. };
  30643. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  30644. for (var i = 0; i < this.vertices.length; ++i) {
  30645. var vCount = [];
  30646. var vId = [];
  30647. var v = this.vertices[i];
  30648. var j;
  30649. for (j = 0; j < v.triangleCount; ++j) {
  30650. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  30651. for (var ii = 0; ii < 3; ii++) {
  30652. var ofs = 0;
  30653. var vv = triangle.vertices[ii];
  30654. while (ofs < vCount.length) {
  30655. if (vId[ofs] === vv.id)
  30656. break;
  30657. ++ofs;
  30658. }
  30659. if (ofs === vCount.length) {
  30660. vCount.push(1);
  30661. vId.push(vv.id);
  30662. }
  30663. else {
  30664. vCount[ofs]++;
  30665. }
  30666. }
  30667. }
  30668. for (j = 0; j < vCount.length; ++j) {
  30669. if (vCount[j] === 1) {
  30670. this.vertices[vId[j]].isBorder = true;
  30671. }
  30672. else {
  30673. this.vertices[vId[j]].isBorder = false;
  30674. }
  30675. }
  30676. }
  30677. };
  30678. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  30679. if (identifyBorders === void 0) { identifyBorders = false; }
  30680. var i;
  30681. if (!identifyBorders) {
  30682. var newTrianglesVector = [];
  30683. for (i = 0; i < this.triangles.length; ++i) {
  30684. if (!this.triangles[i].deleted) {
  30685. newTrianglesVector.push(this.triangles[i]);
  30686. }
  30687. }
  30688. this.triangles = newTrianglesVector;
  30689. }
  30690. for (i = 0; i < this.vertices.length; ++i) {
  30691. this.vertices[i].triangleCount = 0;
  30692. this.vertices[i].triangleStart = 0;
  30693. }
  30694. var t;
  30695. var j;
  30696. var v;
  30697. for (i = 0; i < this.triangles.length; ++i) {
  30698. t = this.triangles[i];
  30699. for (j = 0; j < 3; ++j) {
  30700. v = t.vertices[j];
  30701. v.triangleCount++;
  30702. }
  30703. }
  30704. var tStart = 0;
  30705. for (i = 0; i < this.vertices.length; ++i) {
  30706. this.vertices[i].triangleStart = tStart;
  30707. tStart += this.vertices[i].triangleCount;
  30708. this.vertices[i].triangleCount = 0;
  30709. }
  30710. var newReferences = new Array(this.triangles.length * 3);
  30711. for (i = 0; i < this.triangles.length; ++i) {
  30712. t = this.triangles[i];
  30713. for (j = 0; j < 3; ++j) {
  30714. v = t.vertices[j];
  30715. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  30716. v.triangleCount++;
  30717. }
  30718. }
  30719. this.references = newReferences;
  30720. if (identifyBorders) {
  30721. this.identifyBorder();
  30722. }
  30723. };
  30724. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  30725. var x = point.x;
  30726. var y = point.y;
  30727. var z = point.z;
  30728. 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
  30729. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  30730. };
  30731. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  30732. var q = vertex1.q.add(vertex2.q);
  30733. var border = vertex1.isBorder && vertex2.isBorder;
  30734. var error = 0;
  30735. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  30736. if (qDet !== 0 && !border) {
  30737. if (!pointResult) {
  30738. pointResult = BABYLON.Vector3.Zero();
  30739. }
  30740. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  30741. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  30742. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  30743. error = this.vertexError(q, pointResult);
  30744. }
  30745. else {
  30746. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  30747. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  30748. var error1 = this.vertexError(q, vertex1.position);
  30749. var error2 = this.vertexError(q, vertex2.position);
  30750. var error3 = this.vertexError(q, p3);
  30751. error = Math.min(error1, error2, error3);
  30752. if (error === error1) {
  30753. if (pointResult) {
  30754. pointResult.copyFrom(vertex1.position);
  30755. }
  30756. }
  30757. else if (error === error2) {
  30758. if (pointResult) {
  30759. pointResult.copyFrom(vertex2.position);
  30760. }
  30761. }
  30762. else {
  30763. if (pointResult) {
  30764. pointResult.copyFrom(p3);
  30765. }
  30766. }
  30767. }
  30768. return error;
  30769. };
  30770. return QuadraticErrorSimplification;
  30771. })();
  30772. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  30773. })(BABYLON || (BABYLON = {}));
  30774. //# sourceMappingURL=babylon.meshSimplification.js.map
  30775. var BABYLON;
  30776. (function (BABYLON) {
  30777. var Analyser = (function () {
  30778. function Analyser(scene) {
  30779. this.SMOOTHING = 0.75;
  30780. this.FFT_SIZE = 512;
  30781. this.BARGRAPHAMPLITUDE = 256;
  30782. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  30783. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  30784. this._scene = scene;
  30785. this._audioEngine = BABYLON.Engine.audioEngine;
  30786. if (this._audioEngine.canUseWebAudio) {
  30787. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  30788. this._webAudioAnalyser.minDecibels = -140;
  30789. this._webAudioAnalyser.maxDecibels = 0;
  30790. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  30791. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  30792. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  30793. }
  30794. }
  30795. Analyser.prototype.getFrequencyBinCount = function () {
  30796. if (this._audioEngine.canUseWebAudio) {
  30797. return this._webAudioAnalyser.frequencyBinCount;
  30798. }
  30799. else {
  30800. return 0;
  30801. }
  30802. };
  30803. Analyser.prototype.getByteFrequencyData = function () {
  30804. if (this._audioEngine.canUseWebAudio) {
  30805. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30806. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30807. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  30808. }
  30809. return this._byteFreqs;
  30810. };
  30811. Analyser.prototype.getByteTimeDomainData = function () {
  30812. if (this._audioEngine.canUseWebAudio) {
  30813. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30814. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30815. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  30816. }
  30817. return this._byteTime;
  30818. };
  30819. Analyser.prototype.getFloatFrequencyData = function () {
  30820. if (this._audioEngine.canUseWebAudio) {
  30821. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  30822. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  30823. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  30824. }
  30825. return this._floatFreqs;
  30826. };
  30827. Analyser.prototype.drawDebugCanvas = function () {
  30828. var _this = this;
  30829. if (this._audioEngine.canUseWebAudio) {
  30830. if (!this._debugCanvas) {
  30831. this._debugCanvas = document.createElement("canvas");
  30832. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  30833. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  30834. this._debugCanvas.style.position = "absolute";
  30835. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  30836. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  30837. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  30838. document.body.appendChild(this._debugCanvas);
  30839. this._registerFunc = function () {
  30840. _this.drawDebugCanvas();
  30841. };
  30842. this._scene.registerBeforeRender(this._registerFunc);
  30843. }
  30844. if (this._registerFunc) {
  30845. var workingArray = this.getByteFrequencyData();
  30846. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  30847. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  30848. // Draw the frequency domain chart.
  30849. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  30850. var value = workingArray[i];
  30851. var percent = value / this.BARGRAPHAMPLITUDE;
  30852. var height = this.DEBUGCANVASSIZE.height * percent;
  30853. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  30854. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  30855. var hue = i / this.getFrequencyBinCount() * 360;
  30856. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  30857. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  30858. }
  30859. }
  30860. }
  30861. };
  30862. Analyser.prototype.stopDebugCanvas = function () {
  30863. if (this._debugCanvas) {
  30864. this._scene.unregisterBeforeRender(this._registerFunc);
  30865. this._registerFunc = null;
  30866. document.body.removeChild(this._debugCanvas);
  30867. this._debugCanvas = null;
  30868. this._debugCanvasContext = null;
  30869. }
  30870. };
  30871. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  30872. if (this._audioEngine.canUseWebAudio) {
  30873. inputAudioNode.connect(this._webAudioAnalyser);
  30874. this._webAudioAnalyser.connect(outputAudioNode);
  30875. }
  30876. };
  30877. Analyser.prototype.dispose = function () {
  30878. if (this._audioEngine.canUseWebAudio) {
  30879. this._webAudioAnalyser.disconnect();
  30880. }
  30881. };
  30882. return Analyser;
  30883. })();
  30884. BABYLON.Analyser = Analyser;
  30885. })(BABYLON || (BABYLON = {}));
  30886. //# sourceMappingURL=babylon.analyser.js.map
  30887. var BABYLON;
  30888. (function (BABYLON) {
  30889. var DepthRenderer = (function () {
  30890. function DepthRenderer(scene, type) {
  30891. var _this = this;
  30892. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  30893. this._viewMatrix = BABYLON.Matrix.Zero();
  30894. this._projectionMatrix = BABYLON.Matrix.Zero();
  30895. this._transformMatrix = BABYLON.Matrix.Zero();
  30896. this._worldViewProjection = BABYLON.Matrix.Zero();
  30897. this._scene = scene;
  30898. var engine = scene.getEngine();
  30899. // Render target
  30900. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  30901. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30902. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  30903. this._depthMap.refreshRate = 1;
  30904. this._depthMap.renderParticles = false;
  30905. this._depthMap.renderList = null;
  30906. // set default depth value to 1.0 (far away)
  30907. this._depthMap.onClear = function (engine) {
  30908. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  30909. };
  30910. // Custom render function
  30911. var renderSubMesh = function (subMesh) {
  30912. var mesh = subMesh.getRenderingMesh();
  30913. var scene = _this._scene;
  30914. var engine = scene.getEngine();
  30915. // Culling
  30916. engine.setState(subMesh.getMaterial().backFaceCulling);
  30917. // Managing instances
  30918. var batch = mesh._getInstancesRenderList(subMesh._id);
  30919. if (batch.mustReturn) {
  30920. return;
  30921. }
  30922. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  30923. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  30924. engine.enableEffect(_this._effect);
  30925. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  30926. var material = subMesh.getMaterial();
  30927. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  30928. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  30929. // Alpha test
  30930. if (material && material.needAlphaTesting()) {
  30931. var alphaTexture = material.getAlphaTestTexture();
  30932. _this._effect.setTexture("diffuseSampler", alphaTexture);
  30933. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  30934. }
  30935. // Bones
  30936. if (mesh.useBones) {
  30937. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  30938. }
  30939. // Draw
  30940. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  30941. }
  30942. };
  30943. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  30944. var index;
  30945. for (index = 0; index < opaqueSubMeshes.length; index++) {
  30946. renderSubMesh(opaqueSubMeshes.data[index]);
  30947. }
  30948. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  30949. renderSubMesh(alphaTestSubMeshes.data[index]);
  30950. }
  30951. };
  30952. }
  30953. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  30954. var defines = [];
  30955. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30956. var mesh = subMesh.getMesh();
  30957. var scene = mesh.getScene();
  30958. var material = subMesh.getMaterial();
  30959. // Alpha test
  30960. if (material && material.needAlphaTesting()) {
  30961. defines.push("#define ALPHATEST");
  30962. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  30963. attribs.push(BABYLON.VertexBuffer.UVKind);
  30964. defines.push("#define UV1");
  30965. }
  30966. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  30967. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30968. defines.push("#define UV2");
  30969. }
  30970. }
  30971. // Bones
  30972. if (mesh.useBones) {
  30973. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  30974. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  30975. defines.push("#define BONES");
  30976. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  30977. }
  30978. // Instances
  30979. if (useInstances) {
  30980. defines.push("#define INSTANCES");
  30981. attribs.push("world0");
  30982. attribs.push("world1");
  30983. attribs.push("world2");
  30984. attribs.push("world3");
  30985. }
  30986. // Get correct effect
  30987. var join = defines.join("\n");
  30988. if (this._cachedDefines !== join) {
  30989. this._cachedDefines = join;
  30990. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  30991. }
  30992. return this._effect.isReady();
  30993. };
  30994. DepthRenderer.prototype.getDepthMap = function () {
  30995. return this._depthMap;
  30996. };
  30997. // Methods
  30998. DepthRenderer.prototype.dispose = function () {
  30999. this._depthMap.dispose();
  31000. };
  31001. return DepthRenderer;
  31002. })();
  31003. BABYLON.DepthRenderer = DepthRenderer;
  31004. })(BABYLON || (BABYLON = {}));
  31005. //# sourceMappingURL=babylon.depthRenderer.js.map
  31006. var BABYLON;
  31007. (function (BABYLON) {
  31008. var SSAORenderingPipeline = (function (_super) {
  31009. __extends(SSAORenderingPipeline, _super);
  31010. /**
  31011. * @constructor
  31012. * @param {string} name - The rendering pipeline name
  31013. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  31014. * @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 }
  31015. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  31016. */
  31017. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  31018. var _this = this;
  31019. _super.call(this, scene.getEngine(), name);
  31020. // Members
  31021. /**
  31022. * The PassPostProcess id in the pipeline that contains the original scene color
  31023. * @type {string}
  31024. */
  31025. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  31026. /**
  31027. * The SSAO PostProcess id in the pipeline
  31028. * @type {string}
  31029. */
  31030. this.SSAORenderEffect = "SSAORenderEffect";
  31031. /**
  31032. * The horizontal blur PostProcess id in the pipeline
  31033. * @type {string}
  31034. */
  31035. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  31036. /**
  31037. * The vertical blur PostProcess id in the pipeline
  31038. * @type {string}
  31039. */
  31040. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  31041. /**
  31042. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  31043. * @type {string}
  31044. */
  31045. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  31046. /**
  31047. * The output strength of the SSAO post-process. Default value is 1.0.
  31048. * @type {number}
  31049. */
  31050. this.totalStrength = 1.0;
  31051. /**
  31052. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0002
  31053. * @type {number}
  31054. */
  31055. this.radius = 0.0002;
  31056. /**
  31057. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  31058. * Must not be equal to fallOff and superior to fallOff.
  31059. * Default value is 0.0075
  31060. * @type {number}
  31061. */
  31062. this.area = 0.0075;
  31063. /**
  31064. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  31065. * Must not be equal to area and inferior to area.
  31066. * Default value is 0.0002
  31067. * @type {number}
  31068. */
  31069. this.fallOff = 0.0002;
  31070. this._firstUpdate = true;
  31071. this._scene = scene;
  31072. // Set up assets
  31073. this._createRandomTexture();
  31074. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  31075. var ssaoRatio = ratio.ssaoRatio || ratio;
  31076. var combineRatio = ratio.combineRatio || ratio;
  31077. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  31078. this._createSSAOPostProcess(ssaoRatio);
  31079. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  31080. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 2.0, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  31081. this._createSSAOCombinePostProcess(combineRatio);
  31082. // Set up pipeline
  31083. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  31084. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  31085. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  31086. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  31087. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  31088. // Finish
  31089. scene.postProcessRenderPipelineManager.addPipeline(this);
  31090. if (cameras)
  31091. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  31092. }
  31093. // Public Methods
  31094. /**
  31095. * Returns the horizontal blur PostProcess
  31096. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  31097. */
  31098. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  31099. return this._blurHPostProcess;
  31100. };
  31101. /**
  31102. * Returns the vertical blur PostProcess
  31103. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  31104. */
  31105. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  31106. return this._blurVPostProcess;
  31107. };
  31108. /**
  31109. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  31110. */
  31111. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  31112. if (disableDepthRender === void 0) { disableDepthRender = false; }
  31113. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  31114. this._originalColorPostProcess = undefined;
  31115. this._ssaoPostProcess = undefined;
  31116. this._blurHPostProcess = undefined;
  31117. this._blurVPostProcess = undefined;
  31118. this._ssaoCombinePostProcess = undefined;
  31119. this._randomTexture.dispose();
  31120. if (disableDepthRender)
  31121. this._scene.disableDepthRenderer();
  31122. };
  31123. // Private Methods
  31124. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  31125. var _this = this;
  31126. var sampleSphere = [
  31127. 0.5381, 0.1856, -0.4319,
  31128. 0.1379, 0.2486, 0.4430,
  31129. 0.3371, 0.5679, -0.0057,
  31130. -0.6999, -0.0451, -0.0019,
  31131. 0.0689, -0.1598, -0.8547,
  31132. 0.0560, 0.0069, -0.1843,
  31133. -0.0146, 0.1402, 0.0762,
  31134. 0.0100, -0.1924, -0.0344,
  31135. -0.3577, -0.5301, -0.4358,
  31136. -0.3169, 0.1063, 0.0158,
  31137. 0.0103, -0.5869, 0.0046,
  31138. -0.0897, -0.4940, 0.3287,
  31139. 0.7119, -0.0154, -0.0918,
  31140. -0.0533, 0.0596, -0.5411,
  31141. 0.0352, -0.0631, 0.5460,
  31142. -0.4776, 0.2847, -0.0271
  31143. ];
  31144. var samplesFactor = 1.0 / 16.0;
  31145. 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);
  31146. this._ssaoPostProcess.onApply = function (effect) {
  31147. if (_this._firstUpdate) {
  31148. effect.setArray3("sampleSphere", sampleSphere);
  31149. effect.setFloat("samplesFactor", samplesFactor);
  31150. effect.setFloat("randTextureTiles", 4.0 / ratio);
  31151. _this._firstUpdate = false;
  31152. }
  31153. effect.setFloat("totalStrength", _this.totalStrength);
  31154. effect.setFloat("radius", _this.radius);
  31155. effect.setFloat("area", _this.area);
  31156. effect.setFloat("fallOff", _this.fallOff);
  31157. effect.setTexture("textureSampler", _this._depthTexture);
  31158. effect.setTexture("randomSampler", _this._randomTexture);
  31159. };
  31160. };
  31161. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  31162. var _this = this;
  31163. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31164. this._ssaoCombinePostProcess.onApply = function (effect) {
  31165. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  31166. };
  31167. };
  31168. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  31169. var size = 512;
  31170. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31171. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31172. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31173. var context = this._randomTexture.getContext();
  31174. var rand = function (min, max) {
  31175. return Math.random() * (max - min) + min;
  31176. };
  31177. for (var x = 0; x < size; x++) {
  31178. for (var y = 0; y < size; y++) {
  31179. var randVector = BABYLON.Vector3.Zero();
  31180. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  31181. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  31182. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  31183. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  31184. context.fillRect(x, y, 1, 1);
  31185. }
  31186. }
  31187. this._randomTexture.update(false);
  31188. };
  31189. return SSAORenderingPipeline;
  31190. })(BABYLON.PostProcessRenderPipeline);
  31191. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  31192. })(BABYLON || (BABYLON = {}));
  31193. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  31194. var BABYLON;
  31195. (function (BABYLON) {
  31196. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  31197. var VolumetricLightScatteringPostProcess = (function (_super) {
  31198. __extends(VolumetricLightScatteringPostProcess, _super);
  31199. /**
  31200. * @constructor
  31201. * @param {string} name - The post-process name
  31202. * @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)
  31203. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  31204. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  31205. * @param {number} samples - The post-process quality, default 100
  31206. * @param {number} samplingMode - The post-process filtering mode
  31207. * @param {BABYLON.Engine} engine - The babylon engine
  31208. * @param {boolean} reusable - If the post-process is reusable
  31209. */
  31210. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  31211. var _this = this;
  31212. if (samples === void 0) { samples = 100; }
  31213. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  31214. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  31215. this._screenCoordinates = BABYLON.Vector2.Zero();
  31216. /**
  31217. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  31218. * @type {boolean}
  31219. */
  31220. this.useCustomMeshPosition = false;
  31221. /**
  31222. * If the post-process should inverse the light scattering direction
  31223. * @type {boolean}
  31224. */
  31225. this.invert = true;
  31226. /**
  31227. * Set to true to use the diffuseColor instead of the diffuseTexture
  31228. * @type {boolean}
  31229. */
  31230. this.useDiffuseColor = false;
  31231. /**
  31232. * Array containing the excluded meshes not rendered in the internal pass
  31233. */
  31234. this.excludedMeshes = new Array();
  31235. this.exposure = 0.3;
  31236. this.decay = 0.96815;
  31237. this.weight = 0.58767;
  31238. this.density = 0.926;
  31239. var scene = camera.getScene();
  31240. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  31241. // Configure mesh
  31242. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  31243. // Configure
  31244. this._createPass(scene, ratio.passRatio || ratio);
  31245. this.onApply = function (effect) {
  31246. _this._updateMeshScreenCoordinates(scene);
  31247. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  31248. effect.setFloat("exposure", _this.exposure);
  31249. effect.setFloat("decay", _this.decay);
  31250. effect.setFloat("weight", _this.weight);
  31251. effect.setFloat("density", _this.density);
  31252. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  31253. };
  31254. }
  31255. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  31256. var mesh = subMesh.getMesh();
  31257. var defines = [];
  31258. var attribs = [BABYLON.VertexBuffer.PositionKind];
  31259. var material = subMesh.getMaterial();
  31260. var needUV = false;
  31261. // Render this.mesh as default
  31262. if (mesh === this.mesh) {
  31263. if (this.useDiffuseColor) {
  31264. defines.push("#define DIFFUSE_COLOR_RENDER");
  31265. }
  31266. else {
  31267. defines.push("#define BASIC_RENDER");
  31268. }
  31269. defines.push("#define NEED_UV");
  31270. needUV = true;
  31271. }
  31272. // Alpha test
  31273. if (material) {
  31274. if (material.needAlphaTesting()) {
  31275. defines.push("#define ALPHATEST");
  31276. }
  31277. if (material.opacityTexture !== undefined) {
  31278. defines.push("#define OPACITY");
  31279. if (material.opacityTexture.getAlphaFromRGB)
  31280. defines.push("#define OPACITYRGB");
  31281. if (!needUV)
  31282. defines.push("#define NEED_UV");
  31283. }
  31284. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31285. attribs.push(BABYLON.VertexBuffer.UVKind);
  31286. defines.push("#define UV1");
  31287. }
  31288. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31289. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  31290. defines.push("#define UV2");
  31291. }
  31292. }
  31293. // Bones
  31294. if (mesh.useBones) {
  31295. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  31296. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  31297. defines.push("#define BONES");
  31298. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  31299. }
  31300. // Instances
  31301. if (useInstances) {
  31302. defines.push("#define INSTANCES");
  31303. attribs.push("world0");
  31304. attribs.push("world1");
  31305. attribs.push("world2");
  31306. attribs.push("world3");
  31307. }
  31308. // Get correct effect
  31309. var join = defines.join("\n");
  31310. if (this._cachedDefines !== join) {
  31311. this._cachedDefines = join;
  31312. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel", "color"], ["diffuseSampler", "opacitySampler"], join);
  31313. }
  31314. return this._volumetricLightScatteringPass.isReady();
  31315. };
  31316. /**
  31317. * Sets the new light position for light scattering effect
  31318. * @param {BABYLON.Vector3} The new custom light position
  31319. */
  31320. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  31321. this._customMeshPosition = position;
  31322. };
  31323. /**
  31324. * Returns the light position for light scattering effect
  31325. * @return {BABYLON.Vector3} The custom light position
  31326. */
  31327. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  31328. return this._customMeshPosition;
  31329. };
  31330. /**
  31331. * Disposes the internal assets and detaches the post-process from the camera
  31332. */
  31333. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  31334. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  31335. if (rttIndex !== -1) {
  31336. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  31337. }
  31338. this._volumetricLightScatteringRTT.dispose();
  31339. _super.prototype.dispose.call(this, camera);
  31340. };
  31341. /**
  31342. * Returns the render target texture used by the post-process
  31343. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  31344. */
  31345. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  31346. return this._volumetricLightScatteringRTT;
  31347. };
  31348. // Private methods
  31349. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  31350. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  31351. return true;
  31352. }
  31353. return false;
  31354. };
  31355. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  31356. var _this = this;
  31357. var engine = scene.getEngine();
  31358. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  31359. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31360. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31361. this._volumetricLightScatteringRTT.renderList = null;
  31362. this._volumetricLightScatteringRTT.renderParticles = false;
  31363. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  31364. // Custom render function for submeshes
  31365. var renderSubMesh = function (subMesh) {
  31366. var mesh = subMesh.getRenderingMesh();
  31367. if (_this._meshExcluded(mesh)) {
  31368. return;
  31369. }
  31370. var scene = mesh.getScene();
  31371. var engine = scene.getEngine();
  31372. // Culling
  31373. engine.setState(subMesh.getMaterial().backFaceCulling);
  31374. // Managing instances
  31375. var batch = mesh._getInstancesRenderList(subMesh._id);
  31376. if (batch.mustReturn) {
  31377. return;
  31378. }
  31379. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  31380. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  31381. engine.enableEffect(_this._volumetricLightScatteringPass);
  31382. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  31383. var material = subMesh.getMaterial();
  31384. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  31385. // Alpha test
  31386. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  31387. var alphaTexture = material.getAlphaTestTexture();
  31388. if (_this.useDiffuseColor && mesh === _this.mesh) {
  31389. _this._volumetricLightScatteringPass.setColor3("color", material.diffuseColor);
  31390. }
  31391. else {
  31392. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  31393. if (alphaTexture) {
  31394. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  31395. }
  31396. }
  31397. if (material.opacityTexture !== undefined) {
  31398. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  31399. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  31400. }
  31401. }
  31402. // Bones
  31403. if (mesh.useBones) {
  31404. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  31405. }
  31406. // Draw
  31407. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  31408. }
  31409. };
  31410. // Render target texture callbacks
  31411. var savedSceneClearColor;
  31412. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  31413. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  31414. savedSceneClearColor = scene.clearColor;
  31415. scene.clearColor = sceneClearColor;
  31416. };
  31417. this._volumetricLightScatteringRTT.onAfterRender = function () {
  31418. scene.clearColor = savedSceneClearColor;
  31419. };
  31420. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  31421. var engine = scene.getEngine();
  31422. var index;
  31423. for (index = 0; index < opaqueSubMeshes.length; index++) {
  31424. renderSubMesh(opaqueSubMeshes.data[index]);
  31425. }
  31426. engine.setAlphaTesting(true);
  31427. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  31428. renderSubMesh(alphaTestSubMeshes.data[index]);
  31429. }
  31430. engine.setAlphaTesting(false);
  31431. if (transparentSubMeshes.length) {
  31432. // Sort sub meshes
  31433. for (index = 0; index < transparentSubMeshes.length; index++) {
  31434. var submesh = transparentSubMeshes.data[index];
  31435. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  31436. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  31437. }
  31438. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  31439. sortedArray.sort(function (a, b) {
  31440. // Alpha index first
  31441. if (a._alphaIndex > b._alphaIndex) {
  31442. return 1;
  31443. }
  31444. if (a._alphaIndex < b._alphaIndex) {
  31445. return -1;
  31446. }
  31447. // Then distance to camera
  31448. if (a._distanceToCamera < b._distanceToCamera) {
  31449. return 1;
  31450. }
  31451. if (a._distanceToCamera > b._distanceToCamera) {
  31452. return -1;
  31453. }
  31454. return 0;
  31455. });
  31456. // Render sub meshes
  31457. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  31458. for (index = 0; index < sortedArray.length; index++) {
  31459. renderSubMesh(sortedArray[index]);
  31460. }
  31461. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31462. }
  31463. };
  31464. };
  31465. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  31466. var transform = scene.getTransformMatrix();
  31467. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  31468. this._screenCoordinates.x = pos.x / this._viewPort.width;
  31469. this._screenCoordinates.y = pos.y / this._viewPort.height;
  31470. if (this.invert)
  31471. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  31472. };
  31473. // Static methods
  31474. /**
  31475. * Creates a default mesh for the Volumeric Light Scattering post-process
  31476. * @param {string} The mesh name
  31477. * @param {BABYLON.Scene} The scene where to create the mesh
  31478. * @return {BABYLON.Mesh} the default mesh
  31479. */
  31480. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  31481. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  31482. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  31483. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  31484. return mesh;
  31485. };
  31486. return VolumetricLightScatteringPostProcess;
  31487. })(BABYLON.PostProcess);
  31488. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  31489. })(BABYLON || (BABYLON = {}));
  31490. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  31491. var BABYLON;
  31492. (function (BABYLON) {
  31493. var LensRenderingPipeline = (function (_super) {
  31494. __extends(LensRenderingPipeline, _super);
  31495. /**
  31496. * @constructor
  31497. *
  31498. * Effect parameters are as follow:
  31499. * {
  31500. * chromatic_aberration: number; // from 0 to x (1 for realism)
  31501. * edge_blur: number; // from 0 to x (1 for realism)
  31502. * distortion: number; // from 0 to x (1 for realism)
  31503. * grain_amount: number; // from 0 to 1
  31504. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  31505. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  31506. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  31507. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  31508. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  31509. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  31510. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  31511. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  31512. * }
  31513. * Note: if an effect parameter is unset, effect is disabled
  31514. *
  31515. * @param {string} name - The rendering pipeline name
  31516. * @param {object} parameters - An object containing all parameters (see above)
  31517. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  31518. * @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)
  31519. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  31520. */
  31521. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  31522. var _this = this;
  31523. if (ratio === void 0) { ratio = 1.0; }
  31524. _super.call(this, scene.getEngine(), name);
  31525. // Lens effects can be of the following:
  31526. // - chromatic aberration (slight shift of RGB colors)
  31527. // - blur on the edge of the lens
  31528. // - lens distortion
  31529. // - depth-of-field blur & highlights enhancing
  31530. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  31531. // - grain effect (noise or custom texture)
  31532. // Two additional texture samplers are needed:
  31533. // - depth map (for depth-of-field)
  31534. // - grain texture
  31535. /**
  31536. * The chromatic aberration PostProcess id in the pipeline
  31537. * @type {string}
  31538. */
  31539. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  31540. /**
  31541. * The highlights enhancing PostProcess id in the pipeline
  31542. * @type {string}
  31543. */
  31544. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  31545. /**
  31546. * The depth-of-field PostProcess id in the pipeline
  31547. * @type {string}
  31548. */
  31549. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  31550. this._scene = scene;
  31551. // Fetch texture samplers
  31552. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  31553. if (parameters.grain_texture) {
  31554. this._grainTexture = parameters.grain_texture;
  31555. }
  31556. else {
  31557. this._createGrainTexture();
  31558. }
  31559. // save parameters
  31560. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  31561. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  31562. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  31563. this._distortion = parameters.distortion ? parameters.distortion : 0;
  31564. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  31565. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  31566. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  31567. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  31568. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  31569. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  31570. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  31571. // Create effects
  31572. this._createChromaticAberrationPostProcess(ratio);
  31573. this._createHighlightsPostProcess(ratio);
  31574. this._createDepthOfFieldPostProcess(ratio / 4);
  31575. // Set up pipeline
  31576. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  31577. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  31578. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  31579. if (this._highlightsGain == -1) {
  31580. this._disableEffect(this.HighlightsEnhancingEffect, null);
  31581. }
  31582. // Finish
  31583. scene.postProcessRenderPipelineManager.addPipeline(this);
  31584. if (cameras) {
  31585. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  31586. }
  31587. }
  31588. // public methods (self explanatory)
  31589. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  31590. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  31591. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  31592. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  31593. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  31594. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  31595. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  31596. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  31597. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  31598. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  31599. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  31600. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  31601. LensRenderingPipeline.prototype.enablePentagonBokeh = function () { this._dofPentagon = true; };
  31602. LensRenderingPipeline.prototype.disablePentagonBokeh = function () { this._dofPentagon = false; };
  31603. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  31604. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  31605. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  31606. this._highlightsGain = amount;
  31607. };
  31608. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  31609. if (this._highlightsGain == -1) {
  31610. this._highlightsGain = 1.0;
  31611. }
  31612. this._highlightsThreshold = amount;
  31613. };
  31614. LensRenderingPipeline.prototype.disableHighlights = function () {
  31615. this._highlightsGain = -1;
  31616. };
  31617. /**
  31618. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  31619. */
  31620. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  31621. if (disableDepthRender === void 0) { disableDepthRender = false; }
  31622. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  31623. this._chromaticAberrationPostProcess = undefined;
  31624. this._highlightsPostProcess = undefined;
  31625. this._depthOfFieldPostProcess = undefined;
  31626. this._grainTexture.dispose();
  31627. if (disableDepthRender)
  31628. this._scene.disableDepthRenderer();
  31629. };
  31630. // colors shifting and distortion
  31631. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  31632. var _this = this;
  31633. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31634. this._chromaticAberrationPostProcess.onApply = function (effect) {
  31635. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  31636. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31637. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31638. };
  31639. };
  31640. // highlights enhancing
  31641. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  31642. var _this = this;
  31643. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["pentagon", "gain", "threshold", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31644. this._highlightsPostProcess.onApply = function (effect) {
  31645. effect.setFloat('gain', _this._highlightsGain);
  31646. effect.setFloat('threshold', _this._highlightsThreshold);
  31647. effect.setBool('pentagon', _this._dofPentagon);
  31648. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  31649. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31650. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31651. };
  31652. };
  31653. // colors shifting and distortion
  31654. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  31655. var _this = this;
  31656. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  31657. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  31658. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  31659. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  31660. this._depthOfFieldPostProcess.onApply = function (effect) {
  31661. effect.setTexture("depthSampler", _this._depthTexture);
  31662. effect.setTexture("grainSampler", _this._grainTexture);
  31663. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  31664. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  31665. effect.setFloat('grain_amount', _this._grainAmount);
  31666. effect.setBool('blur_noise', _this._blurNoise);
  31667. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  31668. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  31669. effect.setFloat('distortion', _this._distortion);
  31670. effect.setBool('dof_enabled', (_this._dofDistance != -1));
  31671. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  31672. effect.setFloat('aperture', _this._dofAperture);
  31673. effect.setFloat('darken', _this._dofDarken);
  31674. effect.setFloat('edge_blur', _this._edgeBlur);
  31675. effect.setBool('highlights', (_this._highlightsGain != -1));
  31676. effect.setFloat('near', _this._scene.activeCamera.minZ);
  31677. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  31678. };
  31679. };
  31680. // creates a black and white random noise texture, 512x512
  31681. LensRenderingPipeline.prototype._createGrainTexture = function () {
  31682. var size = 512;
  31683. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  31684. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  31685. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  31686. var context = this._grainTexture.getContext();
  31687. var rand = function (min, max) {
  31688. return Math.random() * (max - min) + min;
  31689. };
  31690. var value;
  31691. for (var x = 0; x < size; x++) {
  31692. for (var y = 0; y < size; y++) {
  31693. value = Math.floor(rand(0.42, 0.58) * 255);
  31694. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  31695. context.fillRect(x, y, 1, 1);
  31696. }
  31697. }
  31698. this._grainTexture.update(false);
  31699. };
  31700. return LensRenderingPipeline;
  31701. })(BABYLON.PostProcessRenderPipeline);
  31702. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  31703. })(BABYLON || (BABYLON = {}));
  31704. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  31705. //
  31706. // This post-process allows the modification of rendered colors by using
  31707. // a 'look-up table' (LUT). This effect is also called Color Grading.
  31708. //
  31709. // The object needs to be provided an url to a texture containing the color
  31710. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  31711. // Use an image editing software to tweak the LUT to match your needs.
  31712. //
  31713. // For an example of a color LUT, see here:
  31714. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  31715. // For explanations on color grading, see here:
  31716. // http://udn.epicgames.com/Three/ColorGrading.html
  31717. //
  31718. var BABYLON;
  31719. (function (BABYLON) {
  31720. var ColorCorrectionPostProcess = (function (_super) {
  31721. __extends(ColorCorrectionPostProcess, _super);
  31722. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  31723. var _this = this;
  31724. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  31725. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  31726. this._colorTableTexture.anisotropicFilteringLevel = 1;
  31727. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31728. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  31729. this.onApply = function (effect) {
  31730. effect.setTexture("colorTable", _this._colorTableTexture);
  31731. };
  31732. }
  31733. return ColorCorrectionPostProcess;
  31734. })(BABYLON.PostProcess);
  31735. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  31736. })(BABYLON || (BABYLON = {}));
  31737. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  31738. var BABYLON;
  31739. (function (BABYLON) {
  31740. var AnaglyphFreeCamera = (function (_super) {
  31741. __extends(AnaglyphFreeCamera, _super);
  31742. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  31743. _super.call(this, name, position, scene);
  31744. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  31745. }
  31746. return AnaglyphFreeCamera;
  31747. })(BABYLON.FreeCamera);
  31748. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  31749. var AnaglyphArcRotateCamera = (function (_super) {
  31750. __extends(AnaglyphArcRotateCamera, _super);
  31751. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  31752. _super.call(this, name, alpha, beta, radius, target, scene);
  31753. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  31754. }
  31755. return AnaglyphArcRotateCamera;
  31756. })(BABYLON.ArcRotateCamera);
  31757. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  31758. var AnaglyphGamepadCamera = (function (_super) {
  31759. __extends(AnaglyphGamepadCamera, _super);
  31760. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  31761. _super.call(this, name, position, scene);
  31762. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  31763. }
  31764. return AnaglyphGamepadCamera;
  31765. })(BABYLON.GamepadCamera);
  31766. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  31767. var StereoscopicFreeCamera = (function (_super) {
  31768. __extends(StereoscopicFreeCamera, _super);
  31769. function StereoscopicFreeCamera(name, position, interaxialDistance, isSideBySide, scene) {
  31770. _super.call(this, name, position, scene);
  31771. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  31772. }
  31773. return StereoscopicFreeCamera;
  31774. })(BABYLON.FreeCamera);
  31775. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  31776. var StereoscopicArcRotateCamera = (function (_super) {
  31777. __extends(StereoscopicArcRotateCamera, _super);
  31778. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isSideBySide, scene) {
  31779. _super.call(this, name, alpha, beta, radius, target, scene);
  31780. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  31781. }
  31782. return StereoscopicArcRotateCamera;
  31783. })(BABYLON.ArcRotateCamera);
  31784. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  31785. var StereoscopicGamepadCamera = (function (_super) {
  31786. __extends(StereoscopicGamepadCamera, _super);
  31787. function StereoscopicGamepadCamera(name, position, interaxialDistance, isSideBySide, scene) {
  31788. _super.call(this, name, position, scene);
  31789. this.setCameraRigMode(isSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  31790. }
  31791. return StereoscopicGamepadCamera;
  31792. })(BABYLON.GamepadCamera);
  31793. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  31794. })(BABYLON || (BABYLON = {}));
  31795. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  31796. 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;\r\n\r\nuniform vec4 color;\r\n\r\nvoid main(void) {\r\n\tgl_FragColor = color;\r\n}","colorVertexShader":"precision highp float;\r\n\r\n// Attributes\r\nattribute vec3 position;\r\n\r\n// Uniforms\r\nuniform mat4 worldViewProjection;\r\n\r\nvoid main(void) {\r\n\tgl_Position = worldViewProjection * vec4(position, 1.0);\r\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 bool blur_noise;\r\nuniform float screen_width;\r\nuniform float screen_height;\r\nuniform float distortion;\r\nuniform bool dof_enabled;\r\n//uniform float focus_distance;\t\t// not needed; already used to compute screen distance\r\nuniform float screen_distance;\t\t// precomputed screen distance from lens center; based on focal length & desired focus distance\r\nuniform float aperture;\r\nuniform float darken;\r\nuniform float edge_blur;\r\nuniform bool highlights;\r\n\r\n// preconputed uniforms (not effect parameters)\r\nuniform float near;\r\nuniform float far;\r\n\r\n// varyings\r\nvarying vec2 vUV;\r\n\r\n// constants\r\n#define PI \t\t3.14159265\r\n#define TWOPI \t6.28318530\r\n#define inverse_focal_length 0.1\t// a property of the lens used\r\n\r\n// common calculations\r\nvec2 centered_screen_pos;\r\nvec2 distorted_coords;\r\nfloat radius2;\r\nfloat radius;\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\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// sample screen with an offset (randomize offset angle for better smothness), returns partial sample weight\r\nfloat sampleScreen(inout vec4 color, const in vec2 offset, const in float weight) {\r\n\r\n\t// compute coords with offset (a random angle is added)\r\n\tvec2 coords = distorted_coords;\r\n\tfloat angle = rand(coords * 100.0).x * TWOPI;\r\n\tcoords += vec2(offset.x * cos(angle) - offset.y * sin(angle), offset.x * sin(angle) + offset.y * cos(angle));\r\n\r\n\tcolor += texture2D(textureSampler, coords)*weight;\r\n\r\n\treturn weight;\r\n}\r\n\r\n// returns blur level according to blur size required\r\nfloat getBlurLevel(float size) {\r\n\treturn min(3.0, ceil(size / 1.0));\r\n}\r\n\r\n// returns original screen color after blur\r\nvec4 getBlurColor(float size) {\r\n\r\n\tvec4 col = texture2D(textureSampler, distorted_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 = getBlurLevel(size);\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\tvec2 sample_coords;\r\n\r\n\ttotal_weight += sampleScreen(col, vec2(-0.50*w, 0.24*h), 0.93);\r\n\ttotal_weight += sampleScreen(col, vec2(0.30*w, -0.75*h), 0.90);\r\n\ttotal_weight += sampleScreen(col, vec2(0.36*w, 0.96*h), 0.87);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.08*w, -0.55*h), 0.85);\r\n\ttotal_weight += sampleScreen(col, vec2(1.33*w, -0.37*h), 0.83);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.82*w, 1.31*h), 0.80);\r\n\ttotal_weight += sampleScreen(col, vec2(-0.31*w, -1.67*h), 0.78);\r\n\ttotal_weight += sampleScreen(col, vec2(1.47*w, 1.11*h), 0.76);\r\n\ttotal_weight += sampleScreen(col, vec2(-1.97*w, 0.19*h), 0.74);\r\n\ttotal_weight += sampleScreen(col, vec2(1.42*w, -1.57*h), 0.72);\r\n\r\n\tif (blur_level > 1.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.01*w, 2.25*h), 0.70);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.62*w, -1.74*h), 0.67);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.49*w, 0.20*h), 0.65);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.07*w, 1.61*h), 0.63);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.46*w, -2.70*h), 0.61);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.55*w, 2.40*h), 0.59);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.88*w, -0.75*h), 0.56);\r\n\t\ttotal_weight += sampleScreen(col, vec2(2.73*w, -1.44*h), 0.54);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.08*w, 3.02*h), 0.52);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-1.28*w, -3.05*h), 0.49);\r\n\t}\r\n\r\n\tif (blur_level > 2.0) {\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.11*w, 1.43*h), 0.46);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.36*w, 1.08*h), 0.44);\r\n\t\ttotal_weight += sampleScreen(col, vec2(1.80*w, -3.16*h), 0.41);\r\n\t\ttotal_weight += sampleScreen(col, vec2(0.83*w, 3.65*h), 0.38);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-3.16*w, -2.19*h), 0.34);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.92*w, -0.53*h), 0.31);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-2.59*w, 3.12*h), 0.26);\r\n\t\ttotal_weight += sampleScreen(col, vec2(-0.20*w, -4.15*h), 0.22);\r\n\t\ttotal_weight += sampleScreen(col, vec2(3.02*w, 3.00*h), 0.15);\r\n\t}\r\n\r\n\tcol /= total_weight;\t\t// scales color according to weights\r\n\r\n\t\t\t\t\t\t\t\t// darken if out of focus\r\n\tif (darken > 0.0) {\r\n\t\tcol.rgb *= clamp(0.3, 1.0, 1.05 - size*0.5*darken);\r\n\t}\r\n\r\n\t// blur levels debug\r\n\t// if(blur_level == 1.0) { col.b *= 0.5; }\r\n\t// if(blur_level == 2.0) { col.r *= 0.5; }\r\n\t// if(blur_level == 3.0) { col.g *= 0.5; }\r\n\r\n\treturn col;\r\n}\r\n\r\nvoid main(void)\r\n{\r\n\r\n\t// Common calc: position relative to screen center, screen radius, distorted coords, position in texel space\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\tdistorted_coords = getDistortedCoords(vUV);\t\t// we distort the screen coordinates (lens \"magnifying\" effect)\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\tfloat depth = texture2D(depthSampler, distorted_coords).r;\t// depth value from DepthRenderer: 0 to 1\r\n\tfloat distance = near + (far - near)*depth;\t\t// actual distance from the lens\r\n\tvec4 color = texture2D(textureSampler, vUV);\t// original raster\r\n\r\n\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// compute the circle of confusion size (CoC), i.e. blur radius depending on depth\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t// screen_distance is precomputed in code\r\n\tfloat coc = abs(aperture * (screen_distance * (inverse_focal_length - 1.0 / distance) - 1.0));\r\n\r\n\t// disable blur\r\n\tif (dof_enabled == false || coc < 0.07) { coc = 0.0; }\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, coc);\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(blur_amount * 1.7);\r\n\r\n\t\t// if we have computed highlights: enhance highlights\r\n\t\tif (highlights) {\r\n\t\t\tgl_FragColor.rgb += clamp(coc, 0.0, 1.0)*texture2D(highlightsSampler, distorted_coords).rgb;\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\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.30 * grain_amount;\r\n\t}\r\n\r\n}\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(DIFFUSE_COLOR_RENDER)\r\nuniform vec3 color;\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#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.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\r\n\t#if defined(BASIC_RENDER)\r\n\tgl_FragColor = diffuseColor;\r\n\t#elif defined(DIFFUSE_COLOR_RENDER)\r\n\tgl_FragColor = vec4(color.rgb, 1.0);\r\n\t#else\r\n\tgl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\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}"};
  31797. 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,Z=e*m-a*l,E=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*Z)*R,t.m[7]=(i*L-n*E+r*N)*R,t.m[11]=-(i*q-o*E+r*V)*R,t.m[15]=(i*Z-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=_}(BABYLON||(BABYLON={}));";
  31798. if (((window && window.module) || (!window && module)) && module.exports) {
  31799. module.exports = BABYLON;
  31800. };